Friday, December 19, 2014

Alpha numeric and number validation script for text field

onkeyup ="return isNumeric(this)


function isAlpahaNu(iva ) {
var result = true;
var string = iva .value.length;
var iChars = /[^A-Za-z0-9]/;
var strVal = iva.value.substring(0,iva.value.length);
if(iChars.test(strVal)){
 iva.value =  strVal.replace(/[^A-Za-z0-9]/g,"");
    alert("Please enter a alphaNumeric value ");
    return false;
}
   }
 
   function isNumber(intva) {
var result = true;
var string = intva.value.length;
var iChars = /[^0-9]/;
var strVal = intva.value.substring(0,intva.value.length);
if(iChars.test(strVal)){
  intva.value =  strVal.replace(/[^0-9]/g,"");
    alert("Please enter a Numeric value ");
    return false;
}
   }

Friday, December 12, 2014

getContextPath() vs getRealPath("/")

String filePath = request.getSession().getServletContext().getContextPath(); --- application rool

String fontPath = request.getSession().getServletContext().getRealPath("/");--- webcontent folder

Wednesday, December 10, 2014

Write image to DB

Encode

private static String setBase64EncodedImage(File  Img) throws IOException {
FileInputStream fin = null;

try {
fin = new FileInputStream( Img);

return new String(Base64.encodeToByte(IOUtils.toByteArray(fin),false));

} catch (FileNotFoundException e) {
LOGGER.error("Error  " + e);
} finally {
try {
if (fin != null) {
fin.close();
}
} catch (IOException ioe) {
throw new RuntimeException("context", ioe);
}
}
return null;
}

Decode

public String displayPushItem() throws WebException {

String pushid = getPushItemId();
try {

if (pushid != null) {
CCRPushItem pushItems = getCcrPushBA().getCCRPushItemWithImage(new BigDecimal(pushid));

if (pushItems != null) {
byte[] imgBuf = Base64.decodeFast(pushItems.getImg());
this.response.setContentType("image/jpg");
this.response.setContentLength(imgBuf.length);
this.response.getOutputStream().write(imgBuf, 0, imgBuf.length);
this.response.getOutputStream().flush();
this.response.getOutputStream().close();
}

}

} catch (Exception e) {
throw new WebException(e);
}
return null;

}
interceptor


               
               
           

File upload and download in struts 2

http://www.programering.com/a/MTNxQTNwATg.html


Struts2 file upload, Download

struts2A file upload, Download
Struts2 can achieve upload, download is the component of commons-fileupload-1.2.2.jar and commons-io-2.0.1.jar based on.

The enctype property of the form elements,
The form specified in the enctype property is the form data coding, this property has the following 3 values:
application/x-www-form-urlencoded: This is the default encoding, it deals only with the value attribute of a form field values, the coding form will form field values into URL code.
multipart/form-data: This code to binary stream way to deal with the form data, this code will file the domain specified file content is encapsulated into the request parameters.
text/plain: This encoding mode when the action property of the form of the mailto:URL form is more convenient, this way is applicable to directly through the form to send email.
Sequence:
According to the example analysis:
The JSP page:
      
     


UploadAction :
public  class  UploadAction  extends ActionSupport {
     private String file;//The name and the JSP parameter names, (to set),
     private String fileFileName; //The parameter name +FileName, it must be so. Save the file real name.
     private String fileContentType; //The parameter name +ContentType, it must be so. Save the file type.

     /*
* get/The set method
*/

public String execute() throws Exception {
     //JSP form will form content in binary form of parameter passing to action.
     //At this time, action file save the uploaded file.
     //File path
    System.out.println(file.getAbsolutePath());
}    
}
Note:
Making making the results on the machine, I run the following:

Making making file upload, Struts2 will first temporary the file is saved, struts.multipart.saveDir used to specify the temporary file location. Struts.multipart.saveDir=null (not specified) would be saved to a location server.
Making making making configuration of struts.multipart.saveDir in two ways:
  1. Configuration in the struts.xml, .
  2. Write a sturt.properties, struts.multipart.saveDir=/temp.
struts2The default upload the maximum file size is 2M, We can modify the configuration file to change the size(in bytes)
  1. In thestruts.xmlConfiguration, 
  2. In thestruts.propertiesConfiguration,   struts.multipart.maxSize=10701096.
Note:
        In the struts.propertiesThe configuration can be placed in the struts.xmlUsing constantTo configure.
OK, now get down to business:
Upload a single file:
public String execute() throws Exception {
     //Create a folder in webRoot, used to store the file to upload, "upload".
    //In fact, this document is only a mapping, really save the file upload in the Tomcat.
    //The real path to obtain Tomcat upload.
String  realPath = ServletActionContext
                                     .getRequest()
                                     .getSession()
                                     .getServletContext()
                                     .getRealPath("upload");
//The real path + real file name, the file copy to complete.
File  theCopy = new File(realPath, fileFileName);

//The input stream into a temporary file, read data. The input, output, are relative to the program.
InputStream is = new FileInputStream(file);
//The output stream is inserted into the new file, and write data.
OutputStream os = new OutputStream(theCopy);

//A buffer is an array of bytes.
byte[] buffer = new byte[];
int length=0;
//Start copy
while ( (length=is.read(buffer0)) != -1 ) {
              os.write(buffer, 0, length);
}
}
//Delete temporary files?
Multiple file upload:
   Multiple file upload to upload a single file is similar, but the operation is a collection.
   Examples are as follows:
   jspPage:
    multipart/form-data
">
              <! - - All parameters upload must be a name, strutsThey will be packaged into a collection-- >
               
  
               
              
       
     action:
            public  class UploadFileAction extends ActionSupport {
                     private  List  files;
                     private  List  filesFileName;
                     private  List  filesContentType;

                     //get, The set method
                     
                     public  String  execute( ) throws  Exception {
                            String realpath = ServletActionContext
.getRequest()
.getSession() 
.getServletContext()
.getRealPath("upload");
                            for(int i=0;  i
                                   File  copy  =  new  File(realpath, filesFileName.get(i) );
                                   inputStream  is = new  FileInputStream ( files.get(i) );
                                   OutputStream  os  = new FileOutputStream (copy );

                                   byte[]  buffer = new  byte[];
                                   int  length = 0;
                                   while( ( length =is.read(buffer) ) != -1 ) {
                                          os.write( buffer, 0, length );
                                   }
                            }

                            return SUCCESS;
                     }  
              }
File download:
    action:
    public  class DownloadFileAction  extends  ActionSupport {
          
         private String fileName;
         private  InputStream  downloadFile;

              //The main method
        public InputStream  getDownloadFile() {
              try {
                //According to the conditions of the corresponding file download simulation
                if( num == 1 )
                        //Will develop the file as a flow back out;
                    return  return ServletActionContext
                                        .getServletContext()
                                        .getResourceAsStream("/upload/xxoo.jpg");
                else
                       //Will develop the file as a flow back out;
                       return  return ServletActionContext
                                               .getServletContext()
                                               .getResourceAsStream("/upload/jj.txt");

                   } catch (Exception e) {
                       e.printStackTrace();
                   }
              return  null;
         }

         public String  getFileName() {
              return this.fileName;
         }

         public  String  execute() throws Exception {
              return SUCCESS;
         }
     }
    strutsTo configure
    
        <! – The specified file upload, temporary file location- - >
        
         
            <!- - Note that resultIs the type of stream - ->
            stream
" >
<!—inputNameThe source parameters of the specified file, according to the configuration file, find getDownloadFile method to obtain the flow - ->
                inputName
">downloadFile
<!—To specify a download mode, the default isinline, This way, if you can open the file browser, can directly open, but not to download (such as the.Txt file format). AppointattachmentWay, so that the user can select is open or download. - - >
                
name="contentDisposition">attachment;filename="xxoo.jpg"
<! – If you do not want to write the dead file, "xxoo.jpg" can be replaced${fileName},actionMust provide a get method - fileName ->
             
     

jspPage:

">Download the file

    You can also specify a file format, buffer size, such as:
     

          contentType
">image/jpeg
          imageStream
 attachment;filename="document.pdf"
          bufferSize
">1024

Struts 2 file upload

public String fileUpload() throws WebException {
FileInputStream fin = null;

try {
fin = new FileInputStream(getImg());
byte fileContent[] = new byte[(int)getImg().length()];
getPushItem().setImg(new String(Base64.encodeBase64(fileContent)));

} catch (FileNotFoundException e) {
log.error("Error  " + e);
}
finally {
try {
if (fin != null) {
fin.close();
}
}
catch (IOException ioe) {
log.error("Error while closing stream: " + ioe);
}
}


return "success";
}

Tuesday, December 9, 2014

removeLastComma

private StringBuilder removeLastComma(StringBuilder strBuff) {
StringBuilder stringBuff = new StringBuilder(strBuff.toString().trim());
stringBuff.trimToSize();
int lastColPos = stringBuff.lastIndexOf(",");
if (lastColPos > -1 && lastColPos == stringBuff.length() - 1) {
stringBuff.deleteCharAt(lastColPos);
}
return stringBuff;
}

Monday, December 8, 2014

org.hibernate.QueryException: Not all named parameters have been set:

getEntities(String query,  Map params)


Map parameter - is missing 

Wednesday, December 3, 2014

No result defined for action com.opensymphony.xwork2.ActionSupport and result success

No result type specified in the struts config file....

Include the result type corresponding to the result for the action.

Tuesday, December 2, 2014

Spring Web “java.lang.NoClassDefFoundError: antlr/RecognitionException] with root cause” error

Add antlr lib in classpath of project

java.lang.NoSuchMethodError: antlr.collections.AST.getLine()I at org.hibernate.hql.ast.HqlSqlWalker.generateNamedParameter(HqlSqlWalker.java:945)


This is because the antlr-2.7.2.jar struts2 and Hibernate antlr-2.7.7.jar conflict, as long as the antlr-2.7.2.jar struts2 file can either remove this problem does not occur. You can try.
If such an error is reported: Then you go to your tomcat application under this WEB WEB-INF Under the lib antlr-2.7.2.jar will be deleted. .

WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source' to 'org.eclipse.jst.jee.server:AppName' did not find a matching property.

You can change the eclipse tomcat server configuration. Open the server view, double click on you server to open server configuration. Then click to activate "Publish module contents to separate XML files". Finally, restart your server, the message must disappear.

EXPLAIN PLAN FOR in SQL Developer

         SELECT PLAN_TABLE_OUTPUT FROM TABLE(DBMS_XPLAN.DISPLAY());

  EXPLAIN PLAN FOR
        select max(this_.