Sunday, August 21, 2011

Java Mail session from a servlet

package org.best.example;

import java.io.IOException;
import java.io.PrintWriter;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * configure a resource reference within the web.xml file
 * that is a container managed javamail session object
 *
 <web-app>
 ...
 <resource-ref>
 <description>smtp mail out</description>
 <res-ref-name>mail/smtp</res-ref-name>
 <res-type>javax.mail.Session</res-type>
 <res-auth>CONTAINER</res-auth>
 </resource-ref>
 </web-app>
 *
 * and use your vendor specific xml file to map the
 * resource name to the jndi name, eg for weblogic
 *
 <weblogic-web-app>
 ...
 <reference-descriptor>
 <resource-description>
 <res-ref-name>mail/smtp</res-ref-name>
 <jndi-name>mail/dailyplanet</jndi-name>
 </resource-description>
 ...
 </reference-descriptor>
 </weblogic-web-app>
 *
 *
 */

public class AccessingAJavaMailSessionFromAServlet extends HttpServlet {
  public void doGet( HttpServletRequest req, HttpServletResponse res )
      throws ServletException, IOException {
    res.setContentType( "text/html" );
    PrintWriter pw = res.getWriter();

    try {
      // get hold of the JavaMail session
      Context ctx = new InitialContext();
      Session mailSession = (Session) ctx.lookup( "java:comp/env/mail/smtp" );

      // create a message
      Message msg = new MimeMessage( mailSession );
      msg.setSubject( "a servlet test email" );
      msg.setSentDate( new java.util.Date( System.currentTimeMillis() ) );
      msg.setText( "<h1>Hello You</h1>" );
      msg.addHeader( "Content-Type", "text/html" );
      msg.setFrom( new InternetAddress( "x@xxx" ) );
      msg.setRecipient( Message.RecipientType.TO,
                        new InternetAddress( "cleve" ) );

      // send it
      Transport.send( msg );

      // and provide feedback to the use
      pw.println( "message sent!" );
    }
    catch( Exception ex ) {
      // if we get a problem, log it
      log( "problem sending message", ex );

      // and send an error back to the client
      res.sendError( res.SC_INTERNAL_SERVER_ERROR, ex.getMessage() );
    }
  }
}

Java Interview Questions - 49

Q: Explain ServletContext.
A: ServletContext interface is a window for a servlet to view it's environment. A servlet can use this interface to get information such as initialization parameters for the web applicationor servlet container's version. Every web application has one and only one ServletContext and is accessible to all active resource of that application.

Saturday, August 20, 2011

Java Interview Questions - 48

Q: What are the common mechanisms used for session tracking?
A: Cookies
SSL sessions
URL- rewriting

Java Servlet Buffering responses

package org.best.example;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
  */
public class BufferingServletResponses extends HttpServlet {
  public void doGet( HttpServletRequest req, HttpServletResponse res )
      throws ServletException, IOException {
    res.setContentType( "text/html" );
    PrintWriter pw = res.getWriter();

    // create 32K buffer
    res.setBufferSize( 32 * 1024 );

    pw.println( "everything we send now is buffered " );
    pw.println( "at the server until we reach the " );
    pw.println( "buffer size limit or we do a flush!" );

    // check to see if anything has been sent to the client
    if( res.isCommitted() ) {
      pw.println( "<br>damned, something has been sent" );
    }
    else {
      // clear the buffer, so what has gone before is lost
      res.resetBuffer();

      pw.println( "we are going to clear this as well" );

      // clears buffer, status codes and headers
      res.reset();

      // we've blanked the ContentType header so lets add it back
      res.setContentType( "text/html" );

      pw.println( "<br>but we are going to see this" );
    }

    // send what we have now
    res.flushBuffer();

    pw.println( "<br>and this will get flushed at the end of the method" );
    pw.println( "<br>current response buffer size is: " + res.getBufferSize() );
  }
}

Friday, August 19, 2011

Java Questions - 47

Q: Explain the directory structure of a web application.
A: The directory structure of a web application consists of two parts.
A private directory called WEB-INF
A public resource directory which contains public resource folder.

WEB-INF folder consists of
1. web.xml
2. classes directory
3. lib directory

Servlet Basic Authentication

package org.best.example;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Securing a web application with basic HTTP authentication
 * has been reduced to a configuration within web.xml
 *
 * to test: http://localhost/ack/servlet/protected/footie/get_time
 *
 <web-app>
 <servlet>
 <servlet-name>footie_time</servlet-name>
 <servlet-class>com.ack.web.servlet.BasicAuthenticationWebResource</servlet-class>
 </servlet>
 <servlet-mapping>
 <servlet-name>footie_time</servlet-name>
 <url-pattern>/protected/footie/get_time</url-pattern>
 </servlet-mapping>
 <security-constraint>
 <web-resource-collection>
 <web-resource-name>protected_zone</web-resource-name>
 <url-pattern>/protected/footie/*</url-pattern>
 <http-method>GET</http-method>
 <http-method>POST</http-method>
 <http-method>PUT</http-method>
 <http-method>DELETE</http-method>
 <http-method>HEAD</http-method>
 <http-method>OPTIONS</http-method>
 <http-method>TRACE</http-method>
 </web-resource-collection>
 <auth-constraint>
 <role-name>footie</role-name>
 </auth-constraint>
 <user-data-constraint>
 <transport-guarantee>NONE</transport-guarantee>
 </user-data-constraint>
 </security-constraint>
 <login-config>
 <auth-method>BASIC</auth-method>
 <realm-name>pure genius football club</realm-name>
 </login-config>
 <security-role>
 <description>the footie guys</description>
 <role-name>footie</role-name>
 </security-role>
 </web-app>
 *
 * finally we need to map from the 'footie' role name to the
 * security principal with the application server, in weblogic
 * we do the following within the supporting weblogic.xml file:
 *
 *
 <weblogic-web-app>
 <security-role-assignment>
 <role-name>footie</role-name>
 <principal-name>cleve</principal-name>
 </security-role-assignment>
 </weblogic-web-app>
 */
public class BasicAuthenticationWebResource extends HttpServlet {
  public void doGet( HttpServletRequest req, HttpServletResponse res )
      throws ServletException, IOException {
    res.setContentType( "text/html" );
    PrintWriter pw = res.getWriter();

    pw.println( "<strong>21:00 @ The Wandle Centre, Wandsworth</strong>" );
    pw.println( "<br>don't be late!" );

  }
}

Thursday, August 18, 2011

Java Questions - 46

Q: What is the difference between the getRequestDispatcher(String path) method of javax.servlet.ServletRequest interface and javax.servlet.ServletContext interface?
A: The getRequestDispatcher(String path) method of javax.servlet.ServletRequest interface accepts parameter the path to the resource to be included or forwarded to, which can be relative to the request of the calling servlet. If the path begins with a "/" it is interpreted as relative to the current context root.

The getRequestDispatcher(String path) method of javax.servlet.ServletContext interface cannot accepts relative paths. All path must sart with a "/" and are interpreted as relative to curent context root.