Thursday, April 17, 2014

Why it happens?

String s1="hello"; String S2= s1+ " world"; String S3="helloworld"; is (s2==s3)?? if no why,  if yes why?

Saturday, February 15, 2014

Make an option in select box readonly not disabled using jquery.

HTML

//HTML Code
<select name="select1" id="select1">
    <option>No Match</option>
    <option value="1">Test</option>
    <option value="2">Test 2</option>
    <option value="3">Test 3</option>
</select>

<select name="select2" id="select2">
    <option>No Match</option>
    <option value="1">Test</option>
    <option value="2">Test 2</option>
    <option value="3">Test 3</option>
</select>

Jquery Code

//JavaScript Code

$('#select1').change(function() {
    
    var value = $(this).val();
  $('#select2').children('option').each(function() {
        if ( $(this).val() != value ) {
            $(this).attr('disabled', true);   
        }
    });
    
});

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();
        }