Friday, November 23, 2012

ResultTransformer in Hibernate

Retrieving a non managed entity from database using hibrnate.

If an entity is not mapped to the configuration file and we try to retrieve it from the database generatlly it throws mapping exception.

To get ride of such a situation we can user ResultTranform to retrieve the datafrom the database and map it to a bean which is not an entity or mapped in configuration.

Cautions:Attributes name and datatype in bean and the database should be same.

See the below the snap of code to implement ResultTransformer.

            Session session=Connector.getSession();
            Transaction tx=session.beginTransaction();
                  
           Query query=session.createSQLQuery("SELECT * FROM customer");
           
           List<Customer> list= query.setResultTransformer(Transformers.aliasToBean(Customer.class)).list()
;
    
     Note: Customer is a non mapped entity it is simple a java bean.

Saturday, October 20, 2012

Image Filter for reading image

/*This filter is used to add image location into front of image file.
we can get image from name without pass full path into jsp/html
Similar 
we can do for js and css file also
.
*/
import java.io.IOException;

import javax.servlet.Filter;

import javax.servlet.FilterChain;

import javax.servlet.FilterConfig;

import javax.servlet.ServletException;

import javax.servlet.ServletRequest;

import javax.servlet.ServletResponse;

import javax.servlet.http.HttpServletRequest;





public class ImageFilter implements Filter {



     */

    public ImageFilter() {

        // TODO Auto-generated constructor stub

    }



                /**

                * @see Filter#destroy()

                */

                public void destroy() {
S
                                // TODO Auto-generated method stub

                }



                /**

                * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)

                */

                public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

                                // TODO Auto-generated method stub

                                // place your code here

                                try

                                {



                                final HttpServletRequest req = (HttpServletRequest) request;

                                String imageName= RequestParser.getImageName(RequestParser.getCleanURI(req.getRequestURI()));

                                if(imageName!=null){
// used for location of image
                                                request.getRequestDispatcher("/WEB-INF/resources/images"+imageName).forward(request, response);

                                }

                                else{

                                                //return blank page here

                                                chain.doFilter(request, response);

                                }

                                }

                                catch(Exception exception)

                                {

                                                exception.printStackTrace();

                                }

                }



                /**

                * @see Filter#init(FilterConfig)

                */

                public void init(FilterConfig fConfig) throws ServletException {

                                // TODO Auto-generated method stub

                }



}

/****************************************************************/



import java.util.StringTokenizer;

/**

*


public  abstract class RequestParser {

              

               
                    /**

                     *

                     * @param URI

                     * @return clear uri from the requested uri, after removing project name

                     */

                    static final String getCleanURI(String URI) {



                        if (isURIOk(URI)) {

                            StringTokenizer tokens = new StringTokenizer(URI, "/");

                            StringBuilder cleanURI = new StringBuilder();

                            boolean first = true;

                            while (tokens.hasMoreElements()) {

                                //leave first token, or apply some other logic here so u can remove first part of uri

                                if (first) {

                                    tokens.nextElement();

                                    first = false;

                                    continue;

                                }

                                cleanURI.append("/");

                                cleanURI.append(tokens.nextElement());

                            }

                            return cleanURI.toString();

                        }

                        return null;

                    }



                    /**

                     *

                     * @param URI

                     * @return

                     * return image name parsing after image url

                     */

                    static final String getImageName(String URI) {

                        return (isURIOk(URI)) ? URI : null;

                    }



                

                    /**

                     *

                     * @param URI

                     * @return

                     * check if uri is ok or not

                     */

                    static final boolean isURIOk(String URI) {

                        return ((URI == null || URI.indexOf(".") == -1 || URI.indexOf("/") == -1)) ? false : true;

                    }



}
/***********************************************************/
 /*into web.xml*/
 <filter>
        <filter-name>ImageFilter</filter-name>
        <filter-class>ImageFilter</filter-class>/* add location of filter class*/
    </filter>
    <filter-mapping>
        <filter-name>ImageFilter</filter-name>
        <url-pattern>*.png</url-pattern>
    </filter-mapping>
   
    <filter-mapping>
        <filter-name>ImageFilter</filter-name>
        <url-pattern>*.jpg</url-pattern>
    </filter-mapping>
   
    /*  add other extension also*/
   

Thursday, October 4, 2012

Executing a task at a particular time interval using Schedular

public void startSchedular()
    {
        Scheduler scheduler = null;
        try
        {
String schedularTime=30 * * * 1-7//This will run after every 30 minutes for all 7 days
            scheduler = new Scheduler();
            scheduler.schedule(schedularTime, new Runnable()
            {
                @Override
                public void run()
                {
                    readEmails();
                }
            });
            scheduler.start();
        } catch (Exception e)
        {
            e.printStackTrace();// TODO: handle exception
            scheduler.stop();
        }
    }


Saturday, September 29, 2012

Upload file example using apache common in servlet and jsp

index.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
      
       
        <form method="POST" action="UploadServlet" enctype="multipart/form-data">
         Upload File   <input type="file" name="file"/>
            <input type="submit" value="Upload"/>
        </form>
           
    </body>
</html>

Reading Email and Attachment Using Java Mail API

Properties properties = System.getProperties();
            Session session = Session.getDefaultInstance(properties, null);
            store = session.getStore(PROTOCOL);
            store.connect(HOST, USERNAME, USERPASSWORD);
            folder = store.getFolder(PROCESSFOLDER);
            if (folder == null && !folder.exists())
            {
                System.out.println("Invalid folder ");
            }
            folder.open(Folder.READ_WRITE);
            Message[] messages = folder.search(new FlagTerm(new Flags(Flags.Flag.SEEN), false));

for (int i = 0; i < messages.length; i++)
            {
                Message msg = messages[i];
                //
                from = InternetAddress.toString(msg.getFrom());
                subject = msg.getSubject();
                to = InternetAddress.toString(msg.getRecipients(Message.RecipientType.TO));
                //
                String contentType = msg.getContentType();
                String textMsg = "";
                if (contentType.contains("text/html") || contentType.contains("text/plain"))
                {
                    textMsg = msg.getContent().toString();
                   
                } else if (contentType.contains("multipart"))
                {
                    Multipart multiPart = (Multipart) msg.getContent();
                    int partCount = multiPart.getCount();
                   
                    for (int j = 0; j < partCount; j++)
                    {
                        BodyPart part = multiPart.getBodyPart(j);
                        String disposition = part.getDisposition();
                        InputStream inputStream = null;
                        if (disposition == null)
                        {
                            // Check if plain
                            MimeBodyPart mbp = (MimeBodyPart) part;
                            if(mbp.getContent() instanceof MimeMultipart)
                            {
                                MimeMultipart mmp = (MimeMultipart) mbp.getContent();
                                System.out.println(mmp.getBodyPart(0).getContent().toString());
                                System.out.println("bodyContent " + bodyContent);
                            }
                            else
                            {
                                String msgText=  multiPart.getBodyPart(0).getContent().toString();
                                System.out.println("Message::::::::::: "+msgText);
                                inputStream=part.getInputStream();
                           
                                return;
                            }
                           
                        } else if (Part.ATTACHMENT.equalsIgnoreCase(part.getDisposition()))
                        {
                            System.out.println("Attachment data::::::: " + part.getContent().toString());
                            MailUtility.saveMail(part.getInputStream(), part.getFileName());
                        } else
                        {
                            textMsg = part.getContent() != null ? part.getContent().toString() : "";
                            System.out.println("Text Msg::::::::: " + textMsg);
                        }
                    }
                }
                   
           
            }
        } catch (Exception ex)
        {
            ex.printStackTrace();
        }

Wednesday, June 27, 2012

Why Runtime Exceptions are Not Checked?

The runtime exception classes (RuntimeException and its subclasses) are
exempted from compile-time checking because, in the judgment of the designers
of the Java programming language, having to declare such exceptions would not
aid significantly in establishing the correctness of programs. Many of the operations and constructs of the Java programming language can result in runtime
exceptions. The information available to a compiler, and the level of analysis the
compiler performs, are usually not sufficient to establish that such run-time exceptions
cannot occur, even though this may be obvious to the programmer. Requiring
such exception classes to be declared would simply be an irritation to
programmers.
For example, certain code might implement a circular data structure that, by
construction, can never involve null references; the programmer can then be
certain that a NullPointerException cannot occur, but it would be difficult for a
compiler to prove it.

Tuesday, June 12, 2012

Alphanumeric validation check using Regex


String value = "Pankaj Singh 1952";
Pattern pattern = Pattern.compile("[a-zA-Z][a-zA-Z0-9 ]*");
Matcher matcher = pattern.matcher(value);
boolean flag = matcher.matches();

if (flag) {
System.out.println("correct value");
} else {
System.out.println("incorrect value");
}

Email Check Using Java Regex


String email = "pankaj.singh@yahoo.co.in";

Pattern p = Pattern
.compile("[a-z][a-z_.0-9]*@[a-z0-9]*[.]{0,1}[a-z0-9]{1,3}.[a-z]{2,3}$");

Matcher m = p.matcher(email);

boolean b = m.matches();
if (b == true) {
System.out.println("Valid Email ID");
} else {
System.out.println("InValid Email ID");
}

Monday, March 19, 2012

More Core Java Interview Question for experienced Developers

Q 1) Does StringBuffer always give better performance then concatenation using + ? In which case StringBuffer will give better performance then concatenation using +?

Q2) How does garbage collector decide which objects are to be removed? Can garbage collector be forced?

Q3) What is the difference between an argument and a parameter?

Q4) What are wrapper classes?

Q5) What is difference between Collections and Collection?

Q6) What is connection pooling and what are the advantages of connection pooling?

Q7) What is Servlet?

Q8) What exactly is “Code once and run anywhere” property of Java? How does Java achieve this behavior?

Q9) What happens when we run this code?
class Test {   public static void main(String args[]) {
    ArrayList alist = new ArrayList();     alist.add(new String("A"));     alist.add(new String("B"));     alist.add(new String("C"));      int i = 0;      for (Iterator it = alist.iterator(); it.hasNext(); ) {       System.out.println(alist.get(i++));     }   } }
Q10) 


Hibernate Questions.

1.) What is difference between Uni-directional and Bi-directional mapping in hibernate and which is more suitable?
2.) Suppose there is one to one relationship between Student and Class entity and lazy loading is enabled and we load the Class entity then what will be the initial value of Student entity?

Thursday, March 15, 2012

Java/J2ee Interview Questions for 2+ experienced developers

Q1) Can we have abstract class without abstract methods? If yes then what is the use of abstract class without abstract methods? Give some practical example from your project where you have used this.

Q2) What is singleton design pattern? How will you make ensure that class is singleton. If singleton class implements serializable interface and we are serializing the class then on deserializing a new object of singleton class will be created (as deserialization process creates new object), in this scenario how will you make sure that deserilazation process will not create a new object of the class?

Q3) What design pattern you see in java collestions?

Q4) What is ConcurrnetModificationException?

Q5) Can static method be abstract?

Q6) Why we can not declare abstract methods as static?

Q7) What is difference between forward and send redirect and which one is faster?

Q8) What is the purpose of serialization in java?

Q8) What is the role of serialVersionUID in serialization process?

Q9) What happens when an object is serialized and then a changes is made in the member variable of the class and later on the earlier serialized object is de-serialized?

Q10) How do you achieve version control in hibernate?

Q11) Why would you use a synchronized block v. synchronized methos?

Q12) What is difference between static block and init block?

Q13) Why static methods cannot access non static variables or methods?

Q14) What modifiers are allowed for methods in an Interface?

Q15) What is difference between iterator access and index access?

Q16) How will you sort a collection of String in case sensitive order?

Q17) Arrange in the order of speed - HashMap, HashTable, Collections.synchronizedMap, ConcurrentHashmap

Q18) What is the purpose of overriding finalize() method?

Q19) What is difference between include and forward?

Q20) What is Servlet Container?

Spring Boot Config Server and Config Client.

 In Spring cloud config we can externalise our configuration files to some repository like GIT HUT, Amazon S3 etc. Benefit of externalising ...