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_.

Friday, November 28, 2014

Monday, November 24, 2014

getoutputstream-has-already-been-called-for-this-response + Itext + PDF Writing

http://stackoverflow.com/questions/1776142/getoutputstream-has-already-been-called-for-this-response

Tuesday, November 18, 2014

Java Interview Questions

Object Oriented Programming (OOP)
Java is a computer programming language that is concurrent, class-based and object-oriented. The advantages of object oriented software development are shown below:
  • Modular development of code, which leads to easy maintenance and modification.
  • Reusability of code.
  • Improved reliability and flexibility of code.
  • Increased understanding of code.
Object-oriented programming contains many significant features, such as encapsulation, inheritance, polymorphism and abstraction. We analyze each feature separately in the following sections.
Encapsulation
Encapsulation provides objects with the ability to hide their internal characteristics and behavior. Each object provides a number of methods, which can be accessed by other objects and change its internal data. In Java, there are three access modifiers: public, private and protected. Each modifier imposes different access rights to other classes, either in the same or in external packages. Some of the advantages of using encapsulation are listed below:
  • The internal state of every objected is protected by hiding its attributes.
  • It increases usability and maintenance of code, because the behavior of an object can be independently changed or extended.
  • It improves modularity by preventing objects to interact with each other, in an undesired way.
You can refer to our tutorial here for more details and examples on encapsulation.
Polymorphism
Polymorphism is the ability of programming languages to present the same interface for differing underlying data types. A polymorphic type is a type whose operations can also be applied to values of some other type.
Inheritance
Inheritance provides an object with the ability to acquire the fields and methods of another class, called base class. Inheritance provides re-usability of code and can be used to add additional features to an existing class, without modifying it.
Abstraction
Abstraction is the process of separating ideas from specific instances and thus, develop classes in terms of their own functionality, instead of their implementation details. Java supports the creation and existence of abstract classes that expose interfaces, without including the actual implementation of all methods. The abstraction technique aims to separate the implementation details of a class from its behavior.
Differences between Abstraction and Encapsulation
Abstraction and encapsulation are complementary concepts. On the one hand, abstraction focuses on the behavior of an object. On the other hand, encapsulation focuses on the implementation of an object’s behavior. Encapsulation is usually achieved by hiding information about the internal state of an object and thus, can be seen as a strategy used in order to provide abstraction.
Can you access non static variable in static context ? A static variable in Java belongs to its class and its value remains the same for all its instances. A static variable is initialized when the class is loaded by the JVM. If your code tries to access a non-static variable, without any instance, the compiler will complain, because those variables are not created yet and they are not associated with any instance.

What is Function Overriding and Overloading in Java ? Method overloading in Java occurs when two or more methods in the same class have the exact same name, but different parameters. On the other hand, method overriding is defined as the case when a child class redefines the same method as a parent class. Overridden methods must have the same name, argument list, and return type. The overriding method may not limit the access of the method it overrides.

What is the difference between an Interface and an Abstract class ? Java provides and supports the creation both of abstract classes and interfaces. Both implementations share some common characteristics, but they differ in the following features:
  • All methods in an interface are implicitly abstract. On the other hand, an abstract class may contain both abstract and non-abstract methods.
  • A class may implement a number of Interfaces, but can extend only one abstract class.
  • In order for a class to implement an interface, it must implement all its declared methods. However, a class may not implement all declared methods of an abstract class. Though, in this case, the sub-class must also be declared as abstract.
  • Abstract classes can implement interfaces without even providing the implementation of interface methods.
  • Variables declared in a Java interface is by default final. An abstract class may contain non-final variables.
  • Members of a Java interface are public by default. A member of an abstract class can either be private, protected or public.
  • An interface is absolutely abstract and cannot be instantiated. An abstract class also cannot be instantiated, but can be invoked if it contains a main method.
How HashMap works in Java ? A HashMap in Java stores key-value pairs. The HashMap requires a hash function and uses hashCode and equals methods, in order to put and retrieve elements to and from the collection respectively. When the put method is invoked, the HashMap calculates the hash value of the key and stores the pair in the appropriate index inside the collection. If the key exists, its value is updated with the new value. Some important characteristics of a HashMap are its capacity, its load factor and the threshold resizing.

What is the importance of hashCode() and equals() methods ? In Java, a HashMap uses the hashCode and equals methods to determine the index of the key-value pair and to detect duplicates. More specifically, the hashCode method is used in order to determine where the specified key will be stored. Since different keys may produce the same hash value, the equals method is used, in order to determine whether the specified key actually exists in the collection or not. Therefore, the implementation of both methods is crucial to the accuracy and efficiency of the HashMap.

What differences exist between HashMap and Hashtable ? Both the HashMap and Hashtable classes implement the Map interface and thus, have very similar characteristics. However, they differ in the following features:
  • A HashMap allows the existence of null keys and values, while a Hashtable doesn’t allow neither null keys, nor null values.
  • A Hashtable is synchronized, while a HashMap is not. Thus, HashMap is preferred in single-threaded environments, while a Hashtable is suitable for multi-threaded environments.
  • A HashMap provides its set of keys and a Java application can iterate over them. Thus, a HashMap is fail-fast. On the other hand, a Hashtable provides an Enumeration of its keys.
  • The Hashtable class is considered to be a legacy class.
What is Comparable and Comparator interface ? List their differences. Java provides the Comparable interface, which contains only one method, called compareTo. This method compares two objects, in order to impose an order between them. Specifically, it returns a negative integer, zero, or a positive integer to indicate that the input object is less than, equal or greater than the existing object. Java provides the Comparator interface, which contains two methods, called compare and equals. The first method compares its two input arguments and imposes an order between them. It returns a negative integer, zero, or a positive integer to indicate that the first argument is less than, equal to, or greater than the second. The second method requires an object as a parameter and aims to decide whether the input object is equal to the comparator. The method returns true, only if the specified object is also a comparator and it imposes the same ordering as the comparator

What is the difference between HashSet and TreeSet ? The HashSet is Implemented using a hash table and thus, its elements are not ordered. The add, remove, and contains methods of a HashSet have constant time complexity O(1). On the other hand, a TreeSet is implemented using a tree structure. The elements in a TreeSet are sorted, and thus, the add, remove, and contains methods have time complexity of O(logn).

When is the finalize() called ? What is the purpose of finalization ? The finalize method is called by the garbage collector, just before releasing the object’s memory. It is normally advised to release resources held by the object inside the finalize method.
What is the difference between throw and throws ? The throw keyword is used to explicitly raise a exception within the program. On the contrary, the throws clause is used to indicate those exceptions that are not handled by a method. Each method must explicitly specify which exceptions does not handle, so the callers of that method can guard against possible exceptions. Finally, multiple exceptions are separated by a comma.

What is meant by implicit objects and what are they ? JSP implicit objects are those Java objects that the JSP Container makes available to developers in each page. A developer can call them directly, without being explicitly declared. JSP Implicit Objects are also called pre-defined variables.The following objects are considered implicit in a JSP page:
  • application
  • page
  • request
  • response
  • session
  • exception
  • out
  • config
  • pageContext

How is it possible for two String objects with identical values not to be equal under the == operator?

Answer:

The == operator compares two objects to determine if they are the same object in memory i.e. present in the same memory location. It is possible for two String objects to have the same value, but located in different areas of memory.
== compares references while .equals compares contents. The method public boolean equals(Object obj) is provided by the Object class and can be overridden. The default implementation returns true only if the object is compared with itself, which is equivalent to the equality operator == being used to compare aliases to the object. String, BitSet, Date, and File override the equals() method. For two String objects, value equality means that they contain the same character sequence. For the Wrapper classes, value equality means that the primitive values are equal.
What does it mean that a class or member is final?
Answer:
  • final – declare constant
  • finally – handles exception
  • finalize – helps in garbage collection
Variables defined in an interface are implicitly final. A final class can’t be extended i.e., final class may not be subclassed. This is done for security reasons with basic classes like String and Integer. It also allows the compiler to make some optimizations, and makes thread safety a little easier to achieve. A final method can’t be overridden when its class is inherited. You can’t change value of a final variable (is a constant). finalize() method is used just before an object is destroyed and garbage collected. finally, a key word used in exception handling and will be executed whether or not an exception is thrown. For example, closing of open connections is done in the finally method.

What is the difference between the boolean & operator and the && operator?

Answer:

If an expression involving the boolean & operator is evaluated, both operands are evaluated, whereas the && operator is a short cut operator. When an expression involving the && operator is evaluated, the first operand is evaluated. If the first operand returns a value of true then the second operand is evaluated. If the first operand evaluates to false, the evaluation of the second operand is skipped.

What do you understand by Synchronization?

Answer:

Synchronization is a process of controlling the access of shared resources by the multiple threads in such a manner that only one thread can access one resource at a time. In non synchronized multithreaded application, it is possible for one thread to modify a shared object while another thread is in the process of using or updating the object’s value. Synchronization prevents such type of data corruption.
Which two method you need to implement for key Object in HashMap ?
In order to use any object as Key in HashMap, it must implements equals and hashcode method in Java.
http://javahungry.blogspot.com/2013/08/hashing-how-hash-map-works-in-java-or.html
What is immutable object? Can you write immutable object?Immutable classes are Java classes whose objects can not be modified once created. Any modification in Immutable object result in new object. For example is String is immutable in Java. Mostly Immutable are also final in Java, in order to prevent sub class from overriding methods in Java which can compromise Immutability. You can achieve same functionality by making member as non final but private and not modifying them except in constructor.

What will happen if we put a key object in a HashMap which is already there ?
if you put the same key again than it will replace the old mapping because HashMap doesn't allow duplicate keys
Explain the different forms of Polymorphism.
There are two types of polymorphism one is Compile time polymorphism and the other is run time polymorphism. Compile time polymorphism is method overloading. Runtime time polymorphism is done using inheritance and interface.
Note: From a practical programming viewpoint, polymorphism manifests itself in three distinct forms in Java:
*       Method overloading
*       Method overriding through inheritance
*       Method overriding through the Java interface

Difference between HashSet and TreeSet ?
HashSet
TreeSet
HashSet is under set interface i.e. it does not guarantee for either sorted order or sequence order.
TreeSet is under set i.e. it provides elements in a sorted order (acceding order).
We can add any type of elements to hash set.
We can add only similar types
of elements to tree set.
How do you decide when to use HashMap and when to use TreeMap ?
For inserting, deleting, and locating elements in a Map, the HashMap offers the best alternative. If, however, you need to traverse the keys in a sorted order, then TreeMap is your better alternative. Depending upon the size of your collection, it may be faster to add elements to a HashMap, then convert the map to a TreeMap for sorted key traversal.
Difference between HashMap and Hashtable ?
HashMap
Hashtable
HashMap lets you have null values as well as one null key.
HashTable does not allows null values as key and value.
The iterator in the HashMap is fail-safe (If you change the map while iterating, you’ll know).
The enumerator for the Hashtable is not fail-safe.
HashMap is unsynchronized.
Hashtable is synchronized.
Note: Only one NULL is allowed as a key in HashMap. HashMap does not allow multiple keys to be NULL. Nevertheless, it can have multiple NULL values.
What is the Comparable interface ?
The Comparable interface is used to sort collections and arrays of objects using the Collections.sort() and java.utils.Arrays.sort() methods respectively. The objects of the class implementing the Comparable interface can be ordered.
The Comparable interface in the generic form is written as follows:
       interface Comparable
where T is the name of the type parameter.

All classes implementing the Comparable interface must implement the
compareTo() method that has the return type as an integer. The signature of the compareTo() method is as follows:
      int i = object1.compareTo(object2)
*       If object1 < object2: The value of i returned will be negative.
*       If object1 > object2: The value of i returned will be positive.
*       If object1 = object2: The value of i returned will be zero.

77.What are the differences between the Comparable and Comparator interfaces ?
Comparable
Comparato
It uses the compareTo() method.
int objectOne.compareTo(objectTwo).
t uses the compare() method.

int compare(ObjOne, ObjTwo)
It is necessary to modify the class whose instance is going to be sorted.
A separate class can be created in order to sort the instances.
Only one sort sequence can be created.
Many sort sequences can be created.
It is frequently used by the API classes.
It used by third-party classes to sort instances.