Monday, July 13, 2009

Google Voice Gizmo5 Sipphone and Ekiga on Ubuntu

This summary is not available. Please click here to view the post.

Thursday, June 25, 2009

JSON, DOJO and innerHtml and Java Handler.

JSON : JavaScript Object Notation, it is the data interchange format, It simplify the data exchange between client side to server side script. In the example we will pass two string and return a Java MAP response.

DOJO : Is the working dog for ajax communication.

innerHtml: this is useful to replace a element in the html document to be replaced with a ajax response. call the element by dojo.byId("someid") then replace the content of the id by innerHtml. The id can be given to any html element.

Our Architecture
Format data to JSON content---> Dojo ---------> xhrPost.Post --> Java Handler process-------> send back JSON response to DOJO------> DOJO display on html.
Our Javascript
//Ajax call to return a list of attributes function processBalanceAjaxLookup( CardNo,pinNo, callbackfunction){ var ajaxCommand = {}; ajaxCommand.command="BalanceLookup"; ajaxCommand.formData={"CardNo":CardNo,"pinNo":pinNo}; ajaxCommand.requestURI="/"; var bindArgs = { url: "/ajax", handleAs: "json-comment-filtered", content: {ajaxCommandData: [JSON.stringify(ajaxCommand)]}, error: function(type, errObj){ }, load: function(type, data){ callbackfunction(type); } }; var requestObj = dojo.xhrPost(bindArgs); } //function to be called by the jsp function checkBalance() { var CardNo = document.getElementById("Number").value; var pinNo=document.getElementById("Pin").value; processBalanceAjaxLookup(No,pinNo,processBalanceAjaxLookupCallback); } //call back function or the response function function processBalanceAjaxLookupCallback(attributeData){ //response token var tokens = dojo.objectToQuery(attributeData).split("&") //inner html tags that have to be replaced. var errorTag=dojo.byId("gcError"); var balanceTag = dojo.byId("gcBalance"); var dateTag=dojo.byId("gcDate"); var cardNoTag=dojo.byId("gcNo"); for(var i = 0; i < tokens.length;i++){ var responseData = tokens[i].split("="); if(responseData[0] == "validity"){ if (responseData[1]== "valid" ){ }else{ balanceTag.innerHTML=""; dateTag.innerHTML=""; errorTag.innerHTML="Invalid Card"; } } else if(responseData[0] == "balance") { balanceTag.innerHTML=responseData[1]; } else if(responseData[0] == "date") { var nowdate = new Date(); //alert (nowdate); dateTag.innerHTML= nowdate ; } else if(responseData[0] == "CardNo") { cardNoTag.innerHTML=responseData[1]; } else if(dojo.byId(responseData[0])) errorTag.innerHTML = responseData[1]; } }
The Html code which calls the function
< a href="#getBalance" class="nyroModal" onClick= javascript: checkBalance()>< img src="images/checkBalance-Btn.gif" width="140" height="41" />
The Java Code
public JSONObject process(HttpServletRequest request, WebApplicationContext factory, JSONObject ajaxData) throws JSONException { JSONObject rval = null; try { String balance= new String("199393.00"); //process the info and return Map responseMap = new HashMap (); if ( CardNo != null ){ responseMap.put("validity", "valid"); responseMap.put( "CardNo", maskGc(CardNo)); responseMap.put("date", formatDate); responseMap.put("balance", balance); rval= new JSONObject(responseMap); }else{ responseMap.put("validity", "invalid"); responseMap.put( "CardNo", ""); responseMap.put("date", ""); responseMap.put("balance", ""); rval= new JSONObject(responseMap); } } catch (Exception e) { e.printStackTrace(); throw new JSONException("Error retrieving Card Balance."); } return rval; }
An Abstract class to invoke the Spring handler and process AJAX calls
public class AbstractAjaxServlet extends HttpServlet { private static Logger myLogger = Logger.getLogger(AbstractAjaxServlet.class); @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { try { doProcess(req, resp); } catch (IOException e) { e.printStackTrace(); throw e; } } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { try { doProcess(req, resp); } catch (IOException e) { e.printStackTrace(); throw e; } } /** * Parses an incoming ajax command object and uses the command name to perform * a Spring lookup for an appropriate handler. Returns the handler's return value * as JSON back to the caller. * * @param req * @param res * @throws IOException */ private void doProcess(HttpServletRequest req, HttpServletResponse res) throws IOException { myLogger.info("> doProcess", null); res.setContentType("text/json-comment-filtered"); if (req.getParameterValues("ajaxCommandData") == null) { return; // We don't know how to handle the request. } String json = req.getParameterValues("ajaxCommandData")[0]; try { JSONObject jsonObject = new JSONObject(json); // Delegation time. String command = jsonObject.getString("command"); // Take the command string and lookup a Spring object to handle it. String handlerName = command; handlerName = handlerName.substring(0, 1).toUpperCase() + handlerName.substring(1); handlerName = "AjaxHandler" + handlerName; WebApplicationContext factory = WebApplicationContextUtils.getWebApplicationContext(req.getSession().getServletContext()); if (!factory.containsBean(handlerName)) { throw new IOException("Invalid ajax handler " + handlerName); } AbstractAjaxHandler handler = (AbstractAjaxHandler) factory.getBean(handlerName); JSONObject returnValue = handler.process(req,factory,jsonObject); res.getWriter().println("/* " + returnValue + " */"); } catch (JSONException e) { e.printStackTrace(); throw new IOException(e.toString()); } myLogger.info("< doProcess", null); } }

Masking for Credit Cards

This will show only the last 4 digits .

private String maskGc(String oS){ int beginIndex=0; int endIndex=12; if (oS.length()>15){ oS= oS.replace(oS.substring(beginIndex, endIndex), "****************"); return oS; } Output: ****************3456

Tuesday, June 2, 2009

Solr/Lucene .

I am trying to add up what I learned so far on the Solr.

Lucene : Is the search engine

Solr : The Search Server.

Solr / Lucene Terms.

Facet --- The data that have to be breakdown. example: manufacturer
FacetField -- This will contain the facet data
SolrDocument -- This will contain one solr search data.
setFacetMinCount -- This will limit returning search data with the minimum count of hit.
A sample Query using SolrJ
query.addFacetField("manu"); query.setFacetMinCount(1); query.setIncludeScore(true); List facetFieldList=qr.getFacetFields(); for(FacetField facetField: facetFieldList){ System.out.println(facetField.toString() +"Manufactures"); } And it returns ----------------- [manu:[dell (5), inc (5), corp (1), sharp (1), sonic (1), view (1), viewson (1), vizo (1)]] Notice here it will return only manufactures with facet count 1 and above.
Solr Price Range:
Querying price range need little special skill in solr, I am still exploring different option of querying. The search querys are case sensitive, if you put 'To' instead of 'TO' solr will throw invalid syntax error.
query.addFacetQuery("price:[* TO 500]"); query.addFacetQuery("price:[500 TO 1000]"); query.addFacetQuery("price:[1000 TO *]"); HashMap priceRangeMap = (HashMap) qr.getFacetQuery(); Iterator priceRageIter=priceRangeMap.entrySet().iterator(); System.out.println(qr.getFacetQuery().toString()); while(priceRageIter.hasNext()){ Map.Entry pairs = (Map.Entry)priceRageIter.next(); System.out.println(pairs.getKey() + " -- found -- " + pairs.getValue()); } And it will return ---------------------- {price:[* TO 500]=1, price:[500 TO 1000]=2, price:[1000 TO *]=6} price:[* TO 500] -- found -- 1 price:[500 TO 1000] -- found -- 2 price:[1000 TO *] -- found -- 6

Thursday, May 28, 2009

Ruby on Windows XP installation

Don't install the one click installer from ruby site. This will not help you if your script has some 'fork' command on it. Windows don't support fork.

Get CYGWIN and select the category development select-> make, select interpreters -> ruby , select Base -> cygwin

If you use default Cygwin installation these packages will not be installed. After installation type in 'which ruby' on the $ prompt this will show the ruby installation directory this is import to know about the installation directory so you can add up the location of the ruby binary on the header of your script.

Now if you want to add ruby libraries download the rubygem package from http://rubyforge.org/frs/?group_id=126
un-tar the package and to the directory. type in ruby setup.rb that will setup the gems to your ruby installation. Now to install individual gems

example. gem install hpricot


this will install the hpricot library to ruby installation.

Saturday, May 9, 2009

Generate Torque Schema from existing DB

I came across a situation where there is the excellent DB schema available, but no torque schema to generate the Peer and Maper classes. Solution>

Setup an eclipse JAVA project. create a lib folder add all the torque lib and generator jars from lib folder of each projects. Now we need a build.properties and torque-build.xml. We can get both of them from the generator project. Now setup the build.properties to point to your existing database. point the database name, username password and connection url and don't forget to place the db driver on the lib folder. Run the torque-build.xml ant script when the ant generator dialogue comes select the jdbc option unselect the main task. Make sure to point the place where the generated schema.xml should be put. This can be specified on the build.properties. example builld.properties. ------------------------- torque.project = starcraft torque.schema.dir=. application.root = . torque.database.name = konakart torque.database.type = mysql torque.database.user = starcraft torque.database.password = star torque.database.driver = com.mysql.jdbc.Driver torque.database.url = jdbc:mysql://142.148.1.142:3306/starcraft torque.database.validationQuery = SELECT 1 torque.sameJavaName = false This will dump a torque schema.xml on the root of the project directory. How to Run the torque Schema.xml to generate Java classes. Modify the schema.xml to your database name here ( starcraft-schema.xml) and inside the schema check the database name is correct and all the can be wrong if you have not specified the database property in the build.properties. Now fire the Ant this time select the task OM. This should generate the java classes. You may need to readjust the packages of the generated classes if the package is not properly specified on the build.properties. If any time ant complaints about torquexxx task not found make sure all jars assosiated to the task in the lib folder of the project. Use your Ctrl+ALT+T key for search the task on the eclipse project space.

Wednesday, May 6, 2009

Weblogic startup failed after password change in admin console

weblogic.security.SecurityInitializationException: Authentication denied: Boot i dentity not valid; The user name and/or password from the boot identity file (bo ot.properties) is not valid. The boot identity may have been changed since the b oot identity file was created. Please edit and update the boot identity file wit h the proper values of username and password. The first time the updated boot id entity file is used to start the server, these new values are encrypted. at weblogic.security.service.CommonSecurityServiceManagerDelegateImpl.do BootAuthorization(Unknown Source) at weblogic.security.service.CommonSecurityServiceManagerDelegateImpl.in itialize(Unknown Source) at weblogic.security.service.SecurityServiceManager.initialize(Unknown S ource) at weblogic.security.SecurityService.start(SecurityService.java:141) at weblogic.t3.srvr.SubsystemRequest.run(SubsystemRequest.java:64) Truncated. see log file for complete stacktrace
Solution --------- C:\bea1001\user_projects\domains\otc_domain\servers\AdminServer\security find the boot.properties backup the property file. Edit,it will look like this: username={3DES}3xhQwbNOXngKswp63s8oqg== password={3DES}B+/Hy/ELjHZztOCHsMxzpg==
change to your admin password you changed in plain like: username=weblogic password=weblogic
run your C:\bea1001\user_projects\domains\otc_domain\bin>startWebLogic.cmd Nice server started Look at your boo.properties now it should like this after startup password={3DES}3xhQwbNOXngKswp63s8oqg\=\= username={3DES}3xhQwbNOXngKswp63s8oqg\=\=
Good your are safe and good to go!

Friday, April 17, 2009

Screen Graber Deamon

This was a hack to grab the questions from a paid online quiz. Idea here is, this program will run as a deamon in the background and take the screen shot every 10 second and save it into a jpeg file on temp directory.

public void captureFullScreen() { try { Robot robot = new Robot(); Rectangle area = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()); File target = new File(saveLocation, imageName + "_" + System.currentTimeMillis() + "." + imageType); saveImageToFile(robot.createScreenCapture(area), target); } catch (AWTException e) { System.err.println("Exception while capturing screen. " + e); } } /** * Saves the specified RenderedImage to the specified File. * * @param renderedImage the image to write to file. * @param target the file to write the image to. */ private void saveImageToFile(RenderedImage renderedImage, File target) { try { ImageIO.write(renderedImage, imageType, target); } catch (IOException e) { System.err.println(e); } }
and now the Deamon
public static void main(String args[]) throws InterruptedException { while(true) { new ScreenGraber().captureFullScreen(); Thread.sleep(10000); // will sleep for 10 seconds } }

Wednesday, April 8, 2009

JPA OneToMany using FetchType.EAGER

Scenario: Want to insert multiple address to basket header with a unique basketId.

BasketHeader.java @OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL) @JoinColumn(name = "basketId", nullable = false) public Set getBasketBillTos() { return basketBillTos; }
By specifying @JoinColumn basketId is set as the foreign key column name for the relationship. Otherwise a default name will be given for the foreign key column. If you are mapping to an existing database schema you will typically require setting the @JoinColumn, otherwise the defaults are probably fine. Implementation on action
Set basketBillToSet = new HashSet(); basketBillToSet.add(basketBillTo); basketHeader.setBasketBillTos(basketBillToSet);

Wednesday, April 1, 2009

Struts 2 OGNL variable evaluation

< s: set name="startIndex" value="%{#parameters['start'][0]}"/ > < s: property value="@java.lang.Integer@parseInt(#startIndex)+4"/ >
Here the first statement grab the query string value using parameter object and assign it as a string, the '%{}' syntax is used for this purpose. The second statement convert the string to int and add the two integers.
IMPORTANT: for the parseInt to work you should enable the constant in struts.xml < constant name="struts.ognl.allowStaticMethodAccess" value="true" / >

Monday, March 30, 2009

SVN with Eclipse Ganymede

  1. Install svn server for windows, use the msi package.
  2. Create Repository
svnadmin create "c:\svnrepo"
Navigate to the folder we just created. Within that folder, uncomment the following lines in the /conf/svnserve.conf file:
[general] anon-access = read auth-access = write password-db = passwd
Next, uncomment these lines in the /conf/passwd file:
[users] harry = harryssecret sally = sallyssecret
3. Install subeclipse 1.6.x package for Ganymede. 4. check in the project using these parameters
host svn://localhost use default port repository svnrepo
In Linux if you have created a subversion group, don't forget to change the file group permission, like this.
sudo chown :subversion directory/
Do not forget to commit the project at the end.