Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

14 May 2015

Adding HTTP headers using Java HTTP web filters

A filter dynamically intercepts requests and responses to transform or use the information contained in the requests or responses. Filters typically do not themselves create responses, but instead provide universal functions that can be "attached" to any type of servlet or JSP page.
filters can be used to transform the response from a servlet or a JSP page.

The filter API is defined by the Filter, FilterChain, and FilterConfig interfaces in the javax.servlet package. You define a filter by implementing the Filter interface. A filter chain, passed to a filter by the container, provides a mechanism for invoking a series of filters. A filter config contains initialization data.
The most important method in the Filter interface is the doFilter method, which is the heart of the filter. Filers are header for :
  • Examines the request headers
  • Customizes the request object if it wishes to modify request headers or data or block the request entirely
  • Customizes the response object if it wishes to modify response headers or data
Response Header Filter:
This filter will add the configured list headers to response for mapped URLS.

Configuration file: WEB-INF\response-headers.xml

<?xml version="1.0" encoding="UTF-8" ?>
<response-header-mapper>
 <!-- generic rule for all html requests -->

 <mapping url="(.*).html">
  <header key="X-ServerName" value="MyServer" />
  <header key="Content-Type" value="text/html" />       
  <!-- cache all the html pages for one hour -->
  <header key="Cache-Control" value="private, max-age=3600" />
 </mapping>
 

 <!-- generic rule for all js requests -->
 <mapping url="(.*).js">
  <header key="X-ServerName" value="MyServer2" />
  <header key="Content-Type" value="text/javascript" />       
  <!-- cache all the js pages for 2 hour -->
  <header key="Cache-Control" value="private, max-age=7200" />
 </mapping>
</response-header-mapper>


In above configuration files we have applied header 'X-ServerName', 'Content-Type', 'Cache-Control' to URLS containing '(.*).html' pattern. So filter will add all these headers to html files

ResponseHeaderFilter.java

import java.io.*;
import java.util.*;
import java.util.regex.*;
import java.util.Map.Entry;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.xml.parsers.*;

import org.w3c.dom.*;
public class ResponseHeaderFilter implements Filter {
 HashMap<Pattern, LinkedHashMap<String, String>> headerPatternRules;

 /**
  * Create URL rules to Header mapping
  * It will create map with URL pattern as key
  * and value will be list of headers to apply
  *  
  * @param xmlFile relative path XML configuration file
  *
  * @return Rule to Header Mapping
  */
 public static HashMap<Pattern, LinkedHashMap<String, String>> getRules( String xmlFile) {
  HashMap<String, LinkedHashMap<String, String>> rules =
    new HashMap<String, LinkedHashMap<String, String>>();
  try {
   DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
   DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
   Document doc = dBuilder.parse(xmlFile);
   doc.getDocumentElement().normalize();
 
   NodeList mappings = doc.getElementsByTagName("mapping");
   for (int i = 0; i < mappings.getLength(); i++) {
    Node mapping = mappings.item(i);
    String urlPattern = mapping.getAttributes().getNamedItem("url").getNodeValue();
    NodeList headers = mapping.getChildNodes();
    LinkedHashMap<String, String> rule = rules.get(urlPattern);
    if (rule == null) {
     rule = new LinkedHashMap<String, String>();
    }
    for (int j = 0; j < headers.getLength(); j++) {
     Node header = headers.item(j);
     if (header.getNodeType() == Node.ELEMENT_NODE) {
      String headerName = header.getAttributes()
        .getNamedItem("key").getNodeValue();
      String headerValue = header.getAttributes()
        .getNamedItem("value").getNodeValue();
      rule.put(headerName, headerValue);
     }
    }
    rules.put(urlPattern, rule);
   }

   System.out.println("*** Rules: " + rules);
   return toRulePattern(rules);
  } catch (Exception e) {
   e.printStackTrace();
  }
  return null;
 }

 /**
  * Compile all the URL patterns
  *
  * @param rules Map of URL pattern and associated List of headers 
  *
  * @return Map of compiled URL pattern and associated List of
  * headers to add
  */
 public static HashMap<Pattern, LinkedHashMap<String, String>> toRulePattern(
   HashMap<String, LinkedHashMap<String, String>> rules) {
  HashMap<Pattern, LinkedHashMap<String, String>> patterRules =
    new HashMap<Pattern, LinkedHashMap<String, String>>();
  for (Entry<String, LinkedHashMap<String, String>> e : rules.entrySet()) {
   patterRules.put(Pattern.compile(e.getKey()), e.getValue());
  }
  return patterRules;
 }

 /**
  * Read configuration file and build the URL pattern to Header Map 
  *
  */
 public void init(FilterConfig fc) throws ServletException {
  String confFile = fc.getInitParameter("response-header-file").trim();
  String fullConfigFilePath = fc.getServletContext().getRealPath("/WEB-INF/" + confFile);
  System.out.println("** ResponseHeaderFilter: Loading configuration from: "
      + fullConfigFilePath);
  headerPatternRules = getRules(fullConfigFilePath);
 }

 /**
  * Filter method
  *
  * Checks request URL against Set of Patters from the list of URL pattern Map and
  * applies the headers associated.
  * 
  */
 public void doFilter(ServletRequest req, ServletResponse res, FilterChain fc)
   throws IOException, ServletException {
  HttpServletResponse response = (HttpServletResponse) res;
  String requestURL = ((HttpServletRequest) req).getRequestURI();

  for (Entry<Pattern, LinkedHashMap<String, String>> rule : headerPatternRules.entrySet()) {
         Matcher matcher = rule.getKey().matcher(requestURL);
         if (matcher.matches()) {
          LinkedHashMap<String, String> headers = rule.getValue();
    for (Entry<String, String> entry : headers.entrySet()) {
     response.setHeader(entry.getKey(), entry.getValue());
    }
         }
  }
  fc.doFilter(req, res);
 }

 public void destroy() {
 }
}


In init() method we read the configuration file (file name is defined in web.xml init-param of filter), then generates rules Map. Key of map is URL pattern and value is list of headers to apply.
In doFilter() method request URI is checked agaist all the rules defined in the configuration for matching of pattern. If match is found the list of header associated with pattern are added to response.
compile this java file and copy it in WEB-INF\classes folder

Modify WEB-INF\web.xml add Filter declaration and Mapping.

<filter>
 <filter-name>ResponseHeaderFilter</filter-name>
 <filter-class>ResponseHeaderFilter</filter-class>
 <init-param>
  <param-name>response-header-file</param-name>
  <param-value>response-headers.xml</param-value>
 </init-param>
</filter>

<filter-mapping>
 <filter-name>ResponseHeaderFilter</filter-name>
 <url-pattern>*</url-pattern>
</filter-mapping>

 

15 March 2011

Executing DB2 stored procedure using Java JDBC

   
Accesing and executing DB2 stored procedure using Java JDBC
Example : Inserting data into COUNTRY table:
Table Schema:

COUNTRY
----------------------------
COUNTRY_CODE    VARCHAR(20)
COUNTRY_NAME    VARCHAR(30)


1. Crating a db2 stored procedure for inserting data in COUNTRY table:

CREATE PROCEDURE INSERT_CITY_MAS
(IN countryCode VARCHAR(20), IN countryName VARCHAR(30))
LANGUAGE SQL
BEGIN
    insert into COUNTRY values(countryCode, countryName);
END


This procedure takes to params country name and country code as input
and inserts it into COUNTRY table.

2. Accessing the Stored procedure from Java class:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.*;
public class TestSQLProcedure
{
    public static void main(String[] args)
    {
        if (args.length < 1)  {
            System.out.println("Usage: ");
        }
        try
        {
            // load the DB2 Driver
            Class.forName("com.ibm.db2.jcc.DB2Driver");
            // establish a connection to DB2
            Connection db2Conn = DriverManager.getConnection("jdbc:db2://HOSTNAME:PORTNO/DB_NAME","DB_USER_NAME","PASSWORD");

            // use a statement to gather data from the database
            CallableStatement cs = db2Conn.prepareCall("{call INSERT_CITY_MAS(?, ?)}");
            // Set the value for the IN parameter
            cs.setString(1, args[0]);
            cs.setString(2, args[1]);
            // Execute the stored procedure
            cs.execute();
        cs.close();
            db2Conn.close();

        } catch (ClassNotFoundException cnfe) {
            cnfe.printStackTrace();
        } catch (SQLException sqle) {
            sqle.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}


3. Compile Above class and Add db2jcc.jar file in $CLASSPATH (use [ $export $CLASSPATH="$CLASSPATH:db2jcc.jar" ] command)

4. Execute above class it will insert the argument provided at command line to database using above stored procedure.

10 March 2011

DB2 Connection Pooling in tomcat 6


The Context element represents a web application, which is run within a particular virtual host. Each web application is based on a Web Application Archive (WAR) file, or a corresponding directory containing the corresponding unpacked contents.


The web application used to process each HTTP request is selected by Catalina based on matching the longest possible prefix of the Request URI against the context path of each defined Context. Once selected, that Context will select an appropriate servlet to process the incoming request, according to the servlet mappings defined in the web application deployment descriptor file (which MUST be located at /WEB-INF/web.xml within the web app's directory hierarchy).


You may define as many Context elements as you wish. Each such Context MUST have a unique context path. In addition, a Context must be present with a context path equal to a zero-length string. This Context becomes the default web application for this virtual host, and is used to process all requests that do not match any other Context's context path.


Sample context.xml ($CONTEXT_PATH/MET-INF/context.xml):


<Context path="/CONTEXT_PATH" docBase="DOC_BASE" crossContext="true" reloadable="true" debug="1">
   <Resource name="jdbc/RESOURCE_NAME" auth="Container" type="javax.sql.DataSource" driverClassName="com.ibm.db2.jcc.DB2Driver" url="jdbc:db2://HOST_NAME:PORT_NUMBER/DATABASE_NAME" u
sername="USER_NAME" password="PASSWORD" maxActive="10" maxIdle="5" maxWait="100000" removeAbandoned="true">
  
      <parameter>
  
      <name>factory</name>
         <value>org.apache.commons.dbcp.BasicDataSourceFactory</value>
  
   </parameter>
   </Resource>
</Context>


Note:

CONTEXT_PATH - The context path of this web application, which is matched against the beginning of each request URI to select the appropriate web application for processing. All of the context paths within a particular Host must be unique. If you specify a context path of an empty string (""), you are defining the default web application for this Host, which will process all requests not assigned to other Contexts. The value of this field must not be set except when statically defining a Context in server.xml, as it will be inferred from the filenames used for either the .xml context file or the docBase.

DOC_BASE - The Document Base (also known as the Context Root) directory for this web application, or the pathname to the web application archive file (if this web application is being executed directly from the WAR file). You may specify an absolute pathname for this directory or WAR file, or a pathname that is relative to the appBase directory of the owning Host. The value of this field must not be set when the Context is configured using a META-INF/context.xml file as it will be inferred by the automatic deployment process. If a symbolic link is used for docBase then changes to the symbolic link will only be effective after a Tomcat restart or by undeploying and redeploying the context. A context reload is not sufficient.

RESOUCE_NAME - Name of the resource (JNDI name)

HOST_NAME - Host name where the DB2 database is running

PORT_NUMBER - Post number on which DB2 instance is running

DATABASE_NAME - Name of database where the table is located

USER_NAME - Dabatabase user name

PASSWORD - Database user password

Other Parameter Specification:
maxActive - Maximum number of dB connections in pool. Make sure you configure your mysqld max_connections large enough to handle all of your db connections. Set to 0 for no limit.

maxIdle - Maximum number of idle dB connections to retain in pool. Set to -1 for no limit. See also the DBCP documentation on this and the minEvictableIdleTimeMillis configuration parameter.

maxWait - Maximum time to wait for a dB connection to become available in ms, in this example 10 seconds. An Exception is thrown if this timeout is exceeded. Set to -1 to wait indefinitely.

driverClassName - JDBC Class name for Connector/J.

url - The JDBC connection url for connecting to your dB. The autoReconnect=true argument to the url makes sure that the JDBC Driver will automatically reconnect
if db closed the connection.



Put dc2jcc.jar in $CATALINA_HOME/lib directory

Getting Database connection in HttpServlet sample code:



import java.io.*;
import java.sql.*;
import javax.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.naming.*;

public class TestDBCP extends HttpServlet
{
     public void doPost(HttpServletRequest request, HttpServletResponse response)
     throws ServletException,IOException     {

          PrintWriter out = response.getWriter();
          Connection con = null;
    
     PreparedStatement pstmt = null;
    
     ResultSet rs = null;
          String username = "TestUSER";
    
     String password = "TESTPWD";

          try {
              InitialContext context = new InitialContext();

              // Look up the data source
              DataSource dataSource =
              (javax.sql.DataSource)context.lookup("java:comp/env/jdbc/RESOURCE_NAME");


              // Get a connection from the pool
              con = dataSource.getConnection();

              String query = "select fullname from user where username = ? and password = ? ";
              // ...Use the connection...
    
         pstmt = con.prepareStatement(query);
              pstmt.setString(1, userName);
    
         pstmt.setString(2, password);
              rs = pstmt.executeQuery();
    
         String result = null;

    
         if (rs.next()) {
                  String result = rs.getString("fullname");              }

              if (result != null) {
                  out.println("Welcome : " + result);

              } else {

                  out.println("Not a valid user, please try again");

    
         }
    
      } catch (Exception e) {
              out.println("ERROR : " + e.getMessage());

    
      } finally {
              try {
    
             if (rs != null) rs.close();
    
             if (pstmt != null) pstmt.close();

    
          } catch (Exception e) {

    
          } finally {
    
             try {

    
              if (con != null) con.close();

    
             } catch (e) { }

    
           }
           }
      }
}

09 March 2011

Accessing DB2 database using JDBC

1. Accessing DB2 database using Java:

Sample code:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class TestSQL
{
    public static void main(String[] args)
    {
         try {           
             // load the DB2 Driver

            Class.forName("com.ibm.db2.jcc.DB2Driver");            // establish a connection to DB2
   
        Connection db2Conn = DriverManager.getConnection("jdbc:db2://HOST_NAME:PORT_NUMBER/DATABASE_NAME","USER_NAME","USER_PASSWORD");
   
        // use a statement to gather data from the database
   
        Statement st = db2Conn.createStatement();
   
        String myQuery = "SELECT * FROM COUNTRY";
   
        // execute the query
 
            ResultSet resultSet = st.executeQuery(myQuery);
   
        // cycle through the resulSet and display what was grabbed
  
        System.out.println("COUNTRY_CODE\tCOUNTRY_NAME");
            while (resultSet.next())            {
   
            String id = resultSet.getString("COUNTRY_CODE");
   
            String name = resultSet.getString("COUNTRY_NAME");
   
            System.out.println("-------------------------------");
   
            System.out.println(id + "\t" + name);
  
        }
   
        // clean up resources
   
        resultSet.close();
   
        st.close();
   
        db2Conn.close();
   
    } catch (ClassNotFoundException cnfe) {
   
        cnfe.printStackTrace();
   
    } catch (SQLException sqle) {
   
        sqle.printStackTrace();
   
    } 
    }
}


Note:
HOST_NAME: specifies the hostname or ipaddress if the system on which DB2 database is running. 
PORT_NUMBER: Port number on which db2 instance is running.
DATABASE_NAME: Name of the database in which tables resides.


2. Change above params in Sample code, compile java file.

3. Add db2jcc.jar in classpath
    $export CLASSPATH="$CLASSPATH:db2jcc.jar"

4. Run the Sample code

24 January 2011

Validating FQDN, URL, E-Mail, Hostname using java regular expression

Using java Pattern class to validate the FQDN, URL, E-Mail address hostname


import java.io.*;
import java.util.regex.Matcher; 
import java.util.regex.Pattern; 
 

public class Validator 
{
    private static final Pattern emailPattern = Pattern.compile("^[\\w\\-]([\\.\\w])+[\\w]+@([\\w\\-]+\\.)+[A-Z]{2,4}$", Pattern.CASE_INSENSITIVE);


    private static final Pattern fqdnPattern = Pattern.compile("(?=^.{1,254}$)(^(?:(?!\\d+\\.|-)[a-zA-Z0-9_\\-]{1,63}(?<!-)\\.?)+(?:[a-zA-Z]{2,})$)", Pattern.CASE_INSENSITIVE);

     private static final Pattern hostPattern = Pattern.compile("^(([a-zA-Z]|[a-zA-Z][a-zA-Z0-9\\-]*[a-zA-Z0-9])\\.)*([A-Za-z]|[A-Za-z][A-Za-z0-9\\-]*[A-Za-z0-9])$", Pattern.CASE_INSENSITIVE);

    private static final Pattern urlPattern = Pattern.compile("[^(http\\:\\/\\/[a-zA-Z0-9_\\-]+(?:\\.[a-zA-Z0-9_\\-]+)*\\.[a-zA-Z]{2,4}(?:\\/[a-zA-Z0-9_]+)*(?:\\/[a-zA-Z0-9_]+\\.[a-zA-Z]{2,4}(?:\\?[a-zA-Z0-9_]+\\=[a-zA-Z0-9_]+)?)?(?:\\&[a-zA-Z0-9_]+\\=[a-zA-Z0-9_]+)*)$]", Pattern.CASE_INSENSITIVE);


    public static boolean isInteger(String intVal)
    {
        try {
            int i = new Integer(intVal);
            return true;
        } catch (Exception e) {
        }
        return false;
    }

    public static boolean isBoolean(String boolVal)
    {
        try {
            boolean b = new Boolean(boolVal);
            return true;
        } catch (Exception e) {
        }
        return false;
    }

    public static boolean isFloat(String floatVal)
    {
        try {
            float f = new Float(floatVal);
            return true;
        } catch (Exception e) {
        }
        return false;
    }

    public static boolean isLong(String logVal)
    {
        try {
            long l = new Long(logVal);
            return true;
        } catch(Exception e) {
        }
        return false;
    }

    public static boolean isFQDN(String fqdnVal)
    {
        try {
                   Matcher matcher = fqdnPattern.matcher(fqdnVal); 
                return matcher.matches(); 
        } catch (Exception e){
        }
        return false;


    }

    public static boolean isURL(String url)
    {
        try {
                   Matcher matcher = urlPattern.matcher(url); 
                return matcher.matches(); 
        } catch (Exception e){
        }
        return false;

    }

    public static boolean isEmailAddr(String emailAddr)
    {
        try {
                   Matcher matcher = emailPattern.matcher(emailAddr); 
                return matcher.matches(); 
        } catch (Exception e){
        }
        return false;
    }

    public static boolean isHost (String hostname)
    {
        try {
                   Matcher matcher = hostPattern.matcher(hostname); 
                return matcher.matches(); 
        } catch (Exception e){
        }
        return false;
    }

    public static void main(String args[])
    {
        try {
            String action = args[0];
            String input = args[1];
            boolean result = false;
            if (action.equals("email")) {
                result = isEmailAddr(input);   
            } else if (action.equals("host")) {
                result = isHost(input);
            } else if(action.equals("url")) {
                result = isURL(input);
            } else if(action.equals("fqdn")) {
                result = isFQDN(input);
            }
            System.out.println("RESULT : " + result);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

17 January 2011

Reading property file in java

Reads a property list (key and element pairs) from the input stream. The stream is assumed to be using the ISO 8859-1 character encoding; that is each byte is one Latin1 character. Characters not in Latin1, and certain special characters, can be represented in keys and elements using escape sequences similar to those used for character and string literals. The differences from the character escape sequences used for characters and strings are:
  • Octal escapes are not recognized.
  • The character sequence \b does not represent a backspace character.
  • The method does not treat a backslash character, \, before a non-valid escape character as an error; the backslash is silently dropped. For example, in a Java string the sequence "\z" would cause a compile time error. In contrast, this method silently drops the backslash. Therefore, this method treats the two character sequence "\b" as equivalent to the single character 'b'.
  • Escapes are not necessary for single and double quotes; however, by the rule above, single and double quote characters preceded by a backslash still yield single and double quote characters, respectively.
An IllegalArgumentException is thrown if a malformed Unicode escape appears in the input.

Java API : java.utils.Properties

Reading properties from Property file:

1. Load the property file

Properties props = new Properties();
try {
       props.load(new FileInputStream("property file path"));
} catch (Exception e) {
    e.printStackTrace();
}


2. Getting properties
String valueForProp = props.getProperty("attribute");



3. Sample property file:
# This is sample attribute comment attr1 = value1

# Attribute having multiple line string
attr2 = this is multi line \
             value for attribute attr2


! you can add comment like this or
# like this

27 December 2010

ant: Java application build tool

Apache Ant is a Java library and command-line tool who's mission is to drive processes described in build files as targets and extension points dependent upon each other. The main known usage of Ant is the build of Java applications. Ant supplies a number of built-in tasks allowing to compile, assemble, test and run Java applications.

Installing ant:
  1. Download the binaries from http://jakarta.apache.org/ant/index.html, unzip them to a suitable directory.

  2. Append /path/to/ant/bin to the PATH environment variable.

  3. Append the .jar files in /path/to/ant/lib/ to the CLASSPATH environment variable. Set JAVA_HOME to point to the location of the JDK installation on the machine that the software is being installed on. Append /path/to/jdk/lib/* to the CLASSPATH environment variable.

Writing a sample build script

Sample Directory Structure:
`Application
|--- bin = Compiled byte code directory all the compiled file will be placed here
|--- src = Java application source files
|--- lib = External library files (eg. jar files )
|--- build.xml = build description file

Sample build.xml
<project name="Project Name" default="test" basedir=".">
<description> Project description </description>
<target name="clean">
<delete dir="bin"/>
</target>

<!-- Create the build directory structure used by compile -->
<target name="init" depends="clean">
<!-- Create the time stamp -->
<tstamp/>
<mkdir dir="bin"/>
</target>

<path id="compile.classpath">
<fileset dir="lib/">
<include name="**/*.jar"/>
</fileset>
<pathelement path ="bin/;${classpath}"/>
</path>

<!-- Compile the java code from ${src} into ${build} -->
<target name="compile" depends="init" description="compile the source">
<javac srcdir="src/" destdir="bin/">
<classpath refid="compile.classpath"/>
</javac>
</target>

<target name="test" depends="compile" description="Execute class">
<java classname="JavaTestClassName" fork="true" failonerror="true" >
<classpath refid="compile.classpath"/>
</java>
</target>
</project>

25 December 2010

Adding document to Solr Using Solr4j

Requirement:
commons-codec-1.3.jar
commons-io-1.4.jar
commons-httpclient-3.1.jar
wstx-asl-3.2.7.jar
slf4j-api-1.5.5.jar
jcl-over-slf4j-1.5.5.jar
geronimo-stax-api_1.0_spec-1.0.1.jar
apache-solr-solrj-1.4.1.jar

Sample Java Code:




import java.io.IOException;
import java.io.StringWriter;
import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.apache.solr.client.solrj.impl.CommonsHttpSolrServer;
import org.apache.solr.client.solrj.request.*;
import org.apache.solr.client.solrj.response.*;
import org.apache.solr.client.solrj.util.ClientUtils;
import org.apache.solr.common.SolrInputDocument;
import org.apache.solr.common.util.XML;
import org.apache.solr.common.util.NamedList;
import org.apache.solr.common.params.FacetParams;

public class TestSolrClient
{
public static void main(String args[])
{
try {
String url = "http://localhost:8983/solr";
CommonsHttpSolrServer server = new CommonsHttpSolrServer(url);

SolrInputDocument doc = new SolrInputDocument();
doc.addField("field", "value", 1.0f );
UpdateResponse upres = server.add( doc );
upres = server.commit( true, true );
System.out.println( "COMMIT:"+upres.getResponse() );

upres = server.optimize( true, true );
System.out.println( "OPTIMIZE:"+upres.getResponse() );
} catch(Exception e) {
e.printStackTrace();
}
}
}

23 December 2010

Fetch Mails From IMAP server using Java Mail API

Requisite:
  • The JavaMail API supports JDK 1.4 or higher
  • JavaMail API 1.4.3 release
  • Please see the FAQ



import java.util.*;
import java.io.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;

/*
* Application for Fetching mails from IMAP server
*
* @author Prashant A. Gadekar
*/

public class MerceIndexer
{

public static void main(String argv[])
{
String url = null;
String protocol = "imap";
String host = "localhost";
String user = "user";
String password = "passowrd";

try {
// Get a Properties object
Properties props = System.getProperties();

// Get a Session object
Session session = Session.getInstance(props, null);

// Get a Store object
Store store = null;
if (url != null) {
URLName urln = new URLName(url);
store = session.getStore(urln);
store.connect();
} else {
if (protocol != null)
store = session.getStore(protocol);
else
store = session.getStore();

// Connect
if (host != null || user != null || password != null)
store.connect(host, user, password);
else
store.connect();
}

// Open the Folder
String mbox = "INBOX";
Folder folder = store.getDefaultFolder();
if (folder == null) {
System.out.println("No default folder");
System.exit(1);
}

folder = folder.getFolder(mbox);
if (!folder.exists()) {
System.out.println(mbox + " does not exist");
System.exit(1);
}

if (!(folder instanceof UIDFolder)) {
System.out.println(
"This Provider or this folder does not support UIDs");
System.exit(1);
}

UIDFolder ufolder = (UIDFolder)folder;

folder.open(Folder.READ_WRITE);
int totalMessages = folder.getMessageCount();

if (totalMessages == 0) {
System.out.println("Empty folder");
folder.close(false);
store.close();
System.exit(1);
}

// Attributes & Flags for ALL messages ..
Message[] msgs = ufolder.getMessagesByUID(1, UIDFolder.LASTUID);
// Use a suitable FetchProfile
FetchProfile fp = new FetchProfile();
fp.add(FetchProfile.Item.ENVELOPE);
fp.add(FetchProfile.Item.FLAGS);
folder.fetch(msgs, fp);

for (int i = 0; i < msgs.length; i++) {
System.out.println("--------------------------");
System.out.println("MESSAGE UID #" +
ufolder.getUID(msgs[i]) + ":");
dumpPart(msgs[i]);
}

folder.close(false);
store.close();
} catch (Exception ex) {
System.out.println("Oops, got exception! " + ex.getMessage());
ex.printStackTrace();
System.exit(1);
}
}

public static void dumpPart(Part p) throws Exception
{
if (p instanceof Message) {
dumpEnvelope((Message)p);
}
System.out.println("CONTENT-TYPE: " + p.getContentType());

Object o = p.getContent();
if (o instanceof String) {
System.out.println("This is a String");
System.out.println("---------------------------");
System.out.println((String)o);
} else if (o instanceof Multipart) {
System.out.println("This is a Multipart");
System.out.println("---------------------------");
Multipart mp = (Multipart)o;
int count = mp.getCount();
for (int i = 0; i < count; i++)
dumpPart(mp.getBodyPart(i));
} else if (o instanceof Message) {
System.out.println("This is a Nested Message");
System.out.println("---------------------------");
dumpPart((Part)o);
} else if (o instanceof InputStream) {
InputStream is = (InputStream)o;
int c;
while ((c = is.read()) != -1) {
System.out.write(c);
}
}

}

public static void dumpEnvelope(Message m) throws Exception
{
System.out.println("This is the message envelope");
System.out.println("---------------------------");
Address[] a;
// FROM
if ((a = m.getFrom()) != null) {
for (int j = 0; j < a.length; j++)
System.out.println("FROM: " + a[j].toString());
}

// TO
if ((a = m.getRecipients(Message.RecipientType.TO)) != null) {
for (int j = 0; j < a.length; j++)
System.out.println("TO: " + a[j].toString());
}

// SUBJECT
System.out.println("SUBJECT: " + m.getSubject());

// DATE
Date d = m.getSentDate();
System.out.println("SendDate: " +
(d != null ? d.toString() : "UNKNOWN"));

// SIZE
System.out.println("Size: " + m.getSize());
}
}

22 July 2010

Java: Get JVM Memory details



public class TestJVM {

public static void main(String args[]) {

Runtime r = Runtime.getRuntime();

// amount of unallocated memory
long free = r.freeMemory();

// total amount of memory available allocated and unallocated.
long total = r.totalMemory();

// total amount of allocated memory
long inuse = r.totalMemory() - r.freeMemory();

// max memory JVM will attempt to use
long max = r.maxMemory();
System.out.println("******************************************");
System.out.println("Java Virtual Machin SUMMARY ");
System.out.println("Total Memory : " + total/1024.00);
System.out.println("Free : " + free /1024.00);
System.out.println("inuse : " + inuse/1024.00 );
System.out.println("Available Processors: " + r.availableProcessors());
System.out.println("******************************************");
// suggest now would be a good time for garbage collection
System.gc();
}
}