Wednesday, November 24, 2010

Generate a random alpha-numeric string in Java

By combinig use of Char array that having alphabets and numbers are an string of alphanumberic characters we can generate random alpha numberic strings in java.here is the exampls code that generate random alpha numberic string for the given length.

 /**
     * Generates alpha numeric random number for the given length.
     * for this it accounts lowercase alpha characters(a-z) and numbers(0-9)
     * @param length length of the alpha numeric random to be generated.
     * @return resulting random alpha numeric string for the given length.
     */
    public static String getAlphaNumbericRandom(int length) {
        //include lower case alpha(a-z) and numbers(0-9)
        String chars = "abcdefghijklmnopqrstuvwxyz0123456789";
        int numberOfCodes = 0;//controls the length of alpha numberic string
        String code = "";
        while (numberOfCodes < length) {
            char c = chars.charAt((int) (Math.random() * chars.length()));
            code += c;
            numberOfCodes++;
        }
        System.out.println("Code is :" + code);
        return code;
    }

If we want to create 6 digit apha numberic random means we have call getAlphaNumbericRandom methods as

getAlphaNumbericRandom(6);

Wednesday, October 20, 2010

Format Source Code for Blogging


Here is the interface to change your source code for put in blogging environments. This escapes the html tags so you can display your source codes in blogs




Tab size: 2 4 8

Embed Stylesheet:

Copy the HTML below to your clipboard. Insert the HTML of your blog or wiki.

This is an example of what your text will look like.
    • Tabs are converted to spaces.
    • Quotes and other special characters are converted to HTML.
    • Everything is enclose in HTML's 'pre' and 'code' tags.
    • Style is set:
        • Fixed width font.
        • Shaded box.
        • Dotted line border.
 

Source :formatmysourcecode.blogspot.com

Wednesday, September 8, 2010

Disable Enter key in Form tag

Placing the following code in your page section will disable the enter key operation in text field



 <script type="text/javascript">   
 function stopRKey(evt) {   
  var evt = (evt) ? evt : ((event) ? event : null);   
  var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);   
  if ((evt.keyCode == 13) && (node.type=="text")) {return false;}   
 }   
 document.onkeypress = stopRKey;   
 </script>  
Source : http://www.webcheatsheet.com

Saturday, September 4, 2010

Redirect Action result to another action in struts2

Using special result type in Struts-2 result we can forward one actions result to another action before forwarding it to view logic.
"redirect-action" result type is used to achieve this.here is the sample code snippet to show how to redirect one actions result to another action


 <action name="userInfo" class="UserAction">  
  <!-- Redirect to another namespace -->  
  <result type="redirect-action">  
   <param name="actionName">getDetails</param>  
   <param name="userId">${userId}</param>  
  </result>  
 </action>  

Here after finishing userInfo action getDetails action will be invoked.Here by using "Param" tags we can pass the values to the getDetails action.

Wednesday, August 25, 2010

Displaying Current Date using Javascript

We can get the current date using the javascript build-in functions. To get the current date we have to use

 var dt new Date()  

in javascript.This creates one date type variable which holds all the date related informations like date,moth,year,time etc,.
Displaying this in any component or in alert will give information like

 Wed Aug 25 2010 13:42:41 GMT+0530 (India Standard Time)  

There are various methods are available in javascript to get the details only what we needed from this .We can use these methods like

 dt.getMonth();  
 dt.getDate();  

First one(getMonth()) gives only current month(0-11),getDate() gives the current date.Here is the sample to get MM/DD/YYYY for the current date in javascript

   var curr_date=new Date();   
   var month=curr_date.getMonth()+1;  
   var day=curr_date.getDate();  
   var year=curr_date.getYear();  
   // Y2K compliant  
   if (year < 1000) year +=1900;  
   document.getElementById(component).value = month + "/" + day + "/" + year;  


In this the getYear() method will return non Y2K compliant year(110 for 2010 ! ) to make this Y2K complian ,we need to add 1900 with that.

Wednesday, August 18, 2010

Creating a ZIP file in JAVA

Using ZipOutputStream and  Class in java.util.zip package we can craete an zip entry for the list of files.
The following gives the sample to create an zip file "outfile.zip" .This zip whill be created using the contents those given in the 'filenames' array.

1:  // These are the files to include in the ZIP file  
2:  String[] filenames = new String[]{"filename1", "filename2"};  
3:  // Create a buffer for reading the files  
4:  byte[] buf = new byte[1024];  
5:  try {  
6:    // Create the ZIP file  
7:    String outFilename = "outfile.zip";  
8:    ZipOutputStream out = new ZipOutputStream(new FileOutputStream(outFilename));  
9:    // Compress the files  
10:    for (int i=0; i<filenames.length; i++) {  
11:      FileInputStream in = new FileInputStream(filenames[i]);  
12:      // Add ZIP entry to output stream.  
13:      out.putNextEntry(new ZipEntry(filenames[i]));  
14:      // Transfer bytes from the file to the ZIP file  
15:      int len;  
16:      while ((len = in.read(buf)) > 0) {  
17:        out.write(buf, 0, len);  
18:      }  
19:      // Complete the entry  
20:      out.closeEntry();  
21:      in.close();  
22:    }  
23:    // Complete the ZIP file  
24:    out.close();  
25:  } catch (IOException e) {  
26:  }  

Source : http://www.exampledepot.com

Tuesday, August 10, 2010

Replace All in Javascript

By Using regular expression with javascript replace function we can implement replace all functionality.here is the sample code block for javascript replace all functionlity.

 <Script Language="javascript">   
     var str = "Javascript replace test.";   
     var rs = str.replace(/is/g,"");   
     document.write(st);    
  </Script>   


here /is key for case insensitive search and /g recursive search

Monday, August 9, 2010

Printing Web page

Using javascript methods you can print the webpage contents or portion of webpage for your likes

 calling window.print() method invoke the browser's print dialog.

By setting appropriate styles in css classes you can hide/show particular parts of the display from printing.

To enable it include print.css only on printing time, for this you have to set media to "print"
so the particular css  stylesheet invoked only while printing

 <link rel="stylesheet" type="text/css" href="print.css" media="print" />  

setting media as screen sets the display for browser


sample print.css content

 div { display: none; }  
 #yourdiv { display: block; }  


update :
 @media print {  
   div.header {  
     display: none;  
   }  
   div.printable {  
     page-break-inside: avoid;  
     page-break-after: always;  
   }  
  }  

This will hide the div content those are not need to be printed.
page-break-inside: avoid; page-break-after: always; are the two properties allign print content in a manner.

Thursday, August 5, 2010

Getting multiple out parameters from oracle procedures

By using "DataReadQuery " when calling oracle stored procedure you can get values for multiple out parameters


here is the code snippet one i found in net when searching for this concept


 JpaEntityManager jpaEntityManager = JpaHelper.getEntityManager(em);  
 Session session = jpaEntityManager.getActiveSession();  
 StoredProcedureCall spc = new StoredProcedureCall();  
 spc.setProcedureName(“two_args_out”);  
 spc.addNamedArgument(“x”);  
 spc.addNamedOutputArgument(“y”);  
 spc.addNamedOutputArgument(“z”);  
 DataReadQuery query = new DataReadQuery();  
 query.setCall(spc);  
 query.addArgument(“x”);  
 List args = new ArrayList();  
 args.add(“Wouter”);  
 List results = (List) session.executeQuery(query, args);  
 DatabaseRecord record = (DatabaseRecord)results.get(0);  
 String y = (String) record.get(“y”);  
 String z = (String) record.get(“z”);  

Before this i have used ValueReadQuery to get result set from the procedure.but it doesn't help with multiple out parameters ,it returns only one.