IT Certificaions

Google Cloud Platform

Friday, September 30, 2011

finally in Exception Handling in Java

finally block always executes after try block. So finally block will be executed even if an unexpected exception occurs. But finally is useful for more than just exception handling — it allows the programmer to avoid having cleanup code accidentally bypassed by a return, continue, or break
You can put cleanup code in a finally block that is always a good practice, even when no exceptions are anticipated.



public void writeData() {
    PrintWriter out = null;

    try {
        System.out.println("Entering try statement");
        out = new PrintWriter(
                          new FileWriter("myFile.txt"));
            for (int i = 0; i < SIZE; i++)
                out.println("Value at: " + i + " = " 
                             + vector.elementAt(i));
                  
    } catch (ArrayIndexOutOfBoundsException e) {
         System.err.println("ArrayIndexOutOfBoundsException: " 
                     +   e.getMessage());
                                 
    } catch (IOException e) {
         System.err.println("IOException: " 
                             +  e.getMessage());
                                 
    } finally {
         if (out != null) {
             System.out.println("Closing PrintWriter");
             out.close();
                
         } 
         else {
             System.out.println("PrintWriter not open");
         }
     }
}


When finally may not execute
If the JVM exits while the try or catch code is being executed, then the finally block may not execute. For example if a live thread executing the try or catch code is interrupted or killed, the finally block may not execute even though the application as a whole continues because there may be other threads doing some other works..

Multiple catch in Java 7

It's a new flavor of multiple exception hadler catch....

Before Java 7:


try {

// Some code here to access any file like reading/writing....

} catch (FileNotFoundException e) {
    System.err.println("FileNotFoundException: "
                        + e.getMessage());
    throw new SampleException(e);

} catch (IOException e) {
    System.err.println("Caught IOException: "
                        + e.getMessage());
}

Now in java 7:

try {

// Some code here to access any file like reading/writing....

} 
catch (FileNotFoundException |IOException ex) {
    logger.log(ex);
    
}

Thursday, September 29, 2011

Read all recipient mail address from PST outlook file using Java Mail API


public void getOriginalMailRecipientAddresses(PSTMessage email){
ORIGINAL_MAIL_TO="";
ORIGINAL_MAIL_CC="";
ORIGINAL_MAIL_BCC="";
   try {
for(int i=0;i<email.getNumberOfRecipients();i++){
if(email.getRecipient(i).getEmailAddress().contains("@") && email.getRecipient(i).getRecipientType()==1){
ORIGINAL_MAIL_TO+=email.getRecipient(i).getEmailAddress()+", ";
}
else if(email.getRecipient(i).getEmailAddress().contains("@") && email.getRecipient(i).getRecipientType()==2){
ORIGINAL_MAIL_CC+=email.getRecipient(i).getEmailAddress()+", ";
}
else if(email.getRecipient(i).getEmailAddress().contains("@") && email.getRecipient(i).getRecipientType()==3){
ORIGINAL_MAIL_BCC+=email.getRecipient(i).getEmailAddress()+", ";
}else{
System.out.println("Not a valid recipient:not found@");
ORIGINAL_MAIL_TO="<none>";
}
}
if(ORIGINAL_MAIL_TO != null && ORIGINAL_MAIL_TO.trim().length()>0){
ORIGINAL_MAIL_TO=ORIGINAL_MAIL_TO.substring(0,ORIGINAL_MAIL_TO.lastIndexOf(','));
}
if(ORIGINAL_MAIL_CC != null && ORIGINAL_MAIL_CC.trim().length()>0){
ORIGINAL_MAIL_CC=ORIGINAL_MAIL_CC.substring(0,ORIGINAL_MAIL_CC.lastIndexOf(','));
}
if(ORIGINAL_MAIL_BCC != null && ORIGINAL_MAIL_BCC.trim().length()>0){
ORIGINAL_MAIL_BCC=ORIGINAL_MAIL_BCC.substring(0,ORIGINAL_MAIL_BCC.lastIndexOf(','));
}
System.out.println("ORIGINAL_MAIL_TO:"+ORIGINAL_MAIL_TO);
System.out.println("ORIGINAL_MAIL_CC:"+ORIGINAL_MAIL_CC);
System.out.println("ORIGINAL_MAIL_BCC:"+ORIGINAL_MAIL_BCC);

} catch (PSTException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
---------------------------------------------------------------------------------------------
This is the code snippet which will help you if you are reading mails from pst file. You can refer the example   from our blog http://knowledge-serve.blogspot.com/2011/09/how-to-read-mail-from-outlook-pst-file.html

Tuesday, September 27, 2011

javax.mail.internet.AddressException: Local address contains control or whitespace in string

Problem:

javax.mail.internet.AddressException: Local address contains control or whitespace in string 

at javax.mail.internet.InternetAddress.<init>(InternetAddress.java:114)
at example.Test2.processFolder(Test2.java:151)
at example.Test2.processFolder(Test2.java:64)
at example.Test2.processFolder(Test2.java:64)
at example.Test2.processFolder(Test2.java:64)
at example.Test2.<init>(Test2.java:43)
at example.Test2.main(Test2.java:33)



Solution: 
**************************************Code Snippet**********************
InternetAddress[] address_old = unicodifyAddresses(toMail);
msg.setRecipients(Message.RecipientType.CC, unicodifyAddresses(email.getDisplayCC()));


// Here is the function which will remove white space



InternetAddress[] unicodifyAddresses(String addresses) throws AddressException {
    InternetAddress[] recipent = InternetAddress.parse(addresses, false);
    for(int i=0; i<recipent.length; i++) {
        try {
            recipent[i] = new InternetAddress(recipent[i].getAddress(), recipent[i].getPersonal(), "utf-8");
        } catch(UnsupportedEncodingException uee) {
            throw new RuntimeException("utf-8 not valid encoding?", uee);
        }
    }
    return recipent;
}
************************************************************************

Please visit http://stackoverflow.com/questions/2656478/send-javax-mail-internet-mimemessage-to-a-recipient-with-non-ascii-name
------Referneced  from www.stackoverflow.com-----------


javax.mail.internet.AddressException: Illegal semicolon, not in group in string

Problem: 
javax.mail.internet.AddressException: Illegal semicolon, not in group in string

at javax.mail.internet.InternetAddress.parse(InternetAddress.java:921)
at javax.mail.internet.InternetAddress.parse(InternetAddress.java:633)
at example.Test2.processFolder(Test2.java:139)
at example.Test2.processFolder(Test2.java:64)
at example.Test2.processFolder(Test2.java:64)
at example.Test2.<init>(Test2.java:43)
at example.Test2.main(Test2.java:33)
Please give any solution.......

Solution: Please replace all semicolon with colon(,) and then try it.
String emailTO=email.getDisplayTo();


InternetAddress[] address_old = InternetAddress.parse(emailTO.replace(';' , ',') , true);

javax.mail.internet.AddressException: Illegal address in string ``''

javax.mail.internet.AddressException: Illegal address in string ``''

at javax.mail.internet.InternetAddress.<init>(InternetAddress.java:114)
at example.Test2.processFolder(Test2.java:150)
at example.Test2.processFolder(Test2.java:64)
at example.Test2.<init>(Test2.java:43)
at example.Test2.main(Test2.java:33)

Solution:
  InternetAddress[] address_old = {new InternetAddress(TO_MAIL)};

If you are using above line for addressing , you need parsing like given below....where TO_MAIL contains the all mail ids where you have to send email seperated by semi colomn(;) ......


 InternetAddress[] address_old = InternetAddress.parse(TO_MAIL,true);

Thursday, September 22, 2011

How to create mail message in FRC822 format

Here is the RFC822 message sample format...which is accepted by archive mail server.
---------------------------------------------------------------------------------------
Date: Fri, 23 Sep 2011 11:33:37 +0530 (GMT+05:30)
From:sender@gmail.com
To:  archive@.............archive.psmtp.com
Cc:  archive@.............archive.psmtp.com
Message-ID: <18916478.4.1316757817734.JavaMail.user@NIC-TestUser>
Subject: Test E-Mail through Java
MIME-Version: 1.0
Content-Type: multipart/mixed;
    boundary="----=_Part_3_16554308.1316757817718"

------=_Part_3_16554308.1316757817718
Content-Type: text/plain; charset=us-ascii
Content-Transfer-Encoding: 7bit

This is part one of a test multipart e-mail.The second part is file as an attachment
------=_Part_3_16554308.1316757817718
Content-Type: text/plain; charset=us-ascii; name=testfile.txt
Content-Transfer-Encoding: 7bit
Content-Disposition: attachment; filename=testfile.txt



Hi,

This is a test file.
------=_Part_3_16554308.1316757817718--
----------------------------------------------------------------------------------------
How will you create this actual message format so that it can be send using java mail API ?

Wednesday, September 21, 2011

Read mail from pst outlook file and then send all on some e-mail account using Java

This program will first read all e-mails in pst file and then send one by one to the mail account where you want to send them.
----------------------------------------------------------------

package example;


import com.pff.*;
import java.util.*;
import java.io.*;
import java.net.UnknownHostException;
import javax.mail.*;
import javax.mail.Flags.Flag;
import javax.mail.internet.*;
import javax.activation.*;
import com.sun.mail.smtp.SMTPMessage;


public class Test {
public static final String host="smtp.gmail.com";
public static final String FROM_ADDRESS = "//enter sender's mail";
public static final String TO_ADDRESS ="//enter recipent mail";
public static final String MAIL_SERVER = "smtp.gmail.com";
public static final String USERNAME ="//Sende email address";
public static final String PASSWORD = "//enter your password";
    public String BODY; 
    public String Sender;
public String Recipient;
public String DestHost;
public String DestAddr;

Properties properties = new Properties();
 
public static void main(String[] args){
new Test("C:/NewWorkSpace/outlook.pst");
}


public Test(String filename) {
try {
System.out.println("File to be read:"+filename);
PSTFile pstFile = new PSTFile(filename);
System.out.println(pstFile.getMessageStore().getDisplayName());
processFolder(pstFile.getRootFolder());
} catch (Exception err) {
err.printStackTrace();
}
}


int depth = -1;
public void processFolder(PSTFolder folder)
throws PSTException, java.io.IOException
{
depth++;
// the root folder doesn't have a display name
if (depth > 0) {
printDepth();
System.out.println("--Folder Display Name--"+folder.getDisplayName());
}


// go through the folders...
if (folder.hasSubfolders()) {
Vector<PSTFolder> childFolders = folder.getSubFolders();
for (PSTFolder childFolder : childFolders) {
processFolder(childFolder);
}
}
        
// and now the emails for this folder
if (folder.getContentCount() > 0) {
boolean flag=true;
depth++;
PSTMessage email = (PSTMessage)folder.getNextChild();
properties.put("mail.smtp.host", MAIL_SERVER);
           properties.put("mail.transport.protocol", "smtp");
           
            Session session = Session.getInstance(properties);
while (email != null) {
printDepth();
System.out.println("From: "+email.getSenderEmailAddress());
System.out.println("\t-To: "+email.getDisplayTo());
System.out.println("\t-CC: "+email.getDisplayCC());
System.out.println("\t-BCC: "+email.getDisplayBCC());
System.out.println("\t-Subject: "+email.getSubject());
System.out.println("\t-Message: "+email.getBody());
Sender=email.getSenderEmailAddress();
Recipient=email.getDisplayTo();
try{
InternetAddress[] address = {new InternetAddress(USERNAME)};
            Message msg = new MimeMessage(session);
            msg.setFrom(new InternetAddress(TO_ADDRESS));
                msg.setRecipients(Message.RecipientType.TO, address);
             
                msg.setRecipients(Message.RecipientType.CC,
                InternetAddress.parse(email.getDisplayCC(), true));
                msg.setRecipients(Message.RecipientType.BCC,
                               InternetAddress.parse(email.getDisplayBCC(), true));
                MimeBodyPart p1 = new MimeBodyPart();
               
                BODY=email.getBody();
                System.out.println("====================================================");
                System.out.println("Body::  "+BODY);
                p1.setText(newMessage());
                System.out.println("Body with enevelope::"+newMessage());
                
                System.out.println("====================================================");
                
                Multipart mp = new MimeMultipart();
                mp.addBodyPart(p1);
                msg.setContent(mp,"text/html; charset=UTF-8");
                int numberOfAttachments = email.getNumberOfAttachments();
                if(email.hasAttachments()){
                     PSTAttachment pstAttach = email.getAttachment(0);
                String file =pstAttach.getLongFilename();
                pstAttach.getAttachmentContentDisposition();
                MimeBodyPart p2 = new MimeBodyPart();
                FileDataSource fds = new FileDataSource(file);
                     p2.setDataHandler(new DataHandler(fds));
                     p2.setFileName(fds.getName());
                     Multipart mp1 = new MimeMultipart();
                     mp1.addBodyPart(p2);
                     msg.setContent(mp1,"text/html; charset=UTF-8");                                
                String file1=pstAttach.getPathname();
                System.out.println("Attacment and File name"+numberOfAttachments+""+file+"PathName"+file1);
                  }
                  msg.setSubject(email.getSubject());
                  msg.setFlag(Flag.ANSWERED, email.hasReplied());
                  msg.setFlag(Flag.FLAGGED, email.isFlagged());
                  msg.setFlag(Flag.SEEN, email.isRead());
                  msg.saveChanges();  
           
                 
                  Transport transport = session.getTransport("smtps");
             transport.connect(MAIL_SERVER, USERNAME, PASSWORD);
             transport.sendMessage(msg, address);
             transport.close();
                
             //Transport.send(msg,address);
             System.out.println("Mesaage Successfully sent");
                
}catch (MessagingException mex) {                
                    mex.printStackTrace();                 
                    while (mex.getNextException() != null) {                       
                        Exception ex = mex.getNextException();
                        ex.printStackTrace();
                        if (!(ex instanceof MessagingException)) break;
                        else mex = (MessagingException)ex;
                    }
                }
email = (PSTMessage)folder.getNextChild();
}
depth--;
}else{
System.out.println("===No email==");
}
depth--;
}
public void printDepth() {
for (int x = 0; x < depth-1; x++) {
System.out.print(" | ");
}
System.out.print(" |- ");
}

public String newMessage() {
String res = "Sender: " + Sender + '\n';
res += "Recipient: " + Recipient + '\n';
res += "MX-host: " + DestHost + ", address: " + DestAddr + '\n';
res += "Message:" + '\n';
res += BODY.toString();
return res;
   }

}
-------------------------------------------------------------------------------------------
****Note: Please download required jar and add into your lib or classpath (if you are using eclipse then add these into Java build path-->Liberary-->add external jar)
1) java-libpst.0.7.jar
2) mail.jar 
3) jpst.jar
4) activation-1.1-sources.jar

How to read mail from outlook pst file using java

This is program which will read all e-mail from .pst file (outlook file).
-------------------------------------------------------------------------------

package com.pack.eml;
import com.pff.*;
import java.util.*;


public class ReadMail {  
public static void main(String[] args) {
new ReadMail("D:/NewWorkSpace/outlook.pst");  
               // Enter the path of pst file from which you want to read mail....
}
  public ReadMail(String filename) {
try {
System.out.println("File to be read:"+filename);
PSTFile pstFile = new PSTFile(filename);
System.out.println(pstFile.getMessageStore().getDisplayName());
  processFolder(pstFile.getRootFolder());
} catch (Exception err) {
err.printStackTrace();
}
  }
  int depth = -1;
  public void processFolder(PSTFolder folder) throws PSTException, java.io.IOException {
depth++;
// the root folder doesn't have a display name
if (depth > 0) {
printDepth();
System.out.println("--Folder Display Name--"+folder.getDisplayName());
}


  // go through the folders...
if (folder.hasSubfolders()) {
Vector<PSTFolder> childFolders = folder.getSubFolders();
for (PSTFolder childFolder : childFolders) {
processFolder(childFolder);
}
}
        
// and now the emails for this folder
if (folder.getContentCount() > 0) {
boolean flag=true;
depth++;
PSTMessage email = (PSTMessage)folder.getNextChild();
while (email != null) {
printDepth();
System.out.println("From: "+email.getSenderEmailAddress());
System.out.println("\t-To: "+email.getDisplayTo());
System.out.println("\t-CC: "+email.getDisplayCC());
System.out.println("\t-BCC: "+email.getDisplayBCC());
System.out.println("\t-Subject: "+email.getSubject());
System.out.println("\t-Message: "+email.getBody());
                       int numberOfAttachments = email.getNumberOfAttachments();
                      if(email.hasAttachments()){
                         PSTAttachment pstAttach = email.getAttachment(0);
                String file =pstAttach.getLongFilename();
                pstAttach.getAttachmentContentDisposition();              
                 String file1=pstAttach.getPathname();
               System.out.println("Attacment and File name"+numberOfAttachments+""+file+"PathName"+file1);
                        }
                      System.out.println("==========================================");
                     email = (PSTMessage)folder.getNextChild();
  }
depth--;
}else{
System.out.println("===No email==");
}
depth--;
}


public void printDepth() {
for (int x = 0; x < depth-1; x++) {
System.out.print(" | ");
}
System.out.print(" |- ");
}
}


-------------------------------------------------------------------------------------------

Download required jar file from the site: http://code.google.com/p/java-libpst/downloads/list

Tuesday, September 20, 2011

Google plus+ : A new Social networking to beat Facebook

Finally, Google launched openly for all the new social networking Google Plus + to compete Facebook. It's fast and easy transition of pictures from Piccassa to your profile. Some good features like make circles of your friends type and Hangout for video chat.



Explore it and send your feedback. Go www.google.com

new classes and interface in Collection in jdk 6

  • Java 6 introduced (among others) two new interfaces: java.util.NavigableSet and java.util.NavigableMap. Here TreeSet class implements NavigableSet interface and TreeMap implements NavigableMap interface.
  • PrirorityQueue is the new class added which implements Queue interface which extends Collection interface.
Here are the methods provided by these Navigable.... interfaces.

TreeSet.ceiling(e)                     Returns the lowest element >= e
TreeMap.ceilingKey(key)       Returns the lowest key >= key
TreeSet.higher(e)                     Returns the lowest element > e
TreeMap.higherKey(key)       Returns the lowest key > key
TreeSet.floor(e)                       Returns the highest element <= e
TreeMap.floorKey(key)         Returns the highest key <= key
TreeSet.lower(e)                      Returns the highest element < e
TreeMap.lowerKey(key)        Returns the highest key < key
TreeSet.pollFirst()                   Returns and removes the first entry
TreeMap.pollFirstEntry()        Returns and removes the first key-value pair
TreeSet.pollLast()                    Returns and removes the last entry
TreeMap.pollLastEntry()        Returns and removes the last key-value pair
TreeSet.descendingSet()         Returns a NavigableSet in reverse order
TreeMap.descendingMap()    Returns a NavigableMap in reverse order

Priority Queue in Collection in Java 6


Priority Queue:

  • This class has been added in Java 5. Since the LinkedList class has been enhanced to implement the Queue interface, basic queues can be handled with a LinkedList. 
  • The purpose of a PriorityQueue is to create a "priority-in, priority out" not just a typical FIFO queue. 
  • A PriorityQueue's elements are ordered either by natural ordering (in which case the elements that are sorted first will be accessed first) or according to a Comparator. In either case, the elements' ordering represents their relative priority.
See Example: 

import java.util.*;

class PriorityQueueTest{
   static class PQsort implements Comparator<Integer> { // inverse sort

      public int compare(Integer one, Integer two) {
         return two - one; // unboxing
      }

   }

   public static void main(String[] args) {
       int[] ia = {1,5,3,7,6,9,8 }; // unordered data

       PriorityQueue<Integer> pq1 =new PriorityQueue<Integer>(); // use natural order

       for(int x : ia) // load queue
    pq1.offer(x);
       
  System.out.print("\n====Priority queue<Integer> after using offer()===== \n");
       for(int x : ia) // review queue
          System.out.print(pq1.poll() + " ");  // The poll() method returns top head of Queue as well as delete it from queue.

  // Now Queue is empty

      System.out.print("\n===================================================== ");
       System.out.println("");
       PQsort pqs = new PQsort(); // get a Comparator

       PriorityQueue<Integer> pq2 =new PriorityQueue<Integer>(10,pqs); // use Comparator ::  Creates a PriorityQueue with the specified initial capacity 10 that orders its elements according to the specified comparator.
       for(int x : ia) // load queue
         pq2.offer(x);

  // Now pq2 ::  9 8 7 6 5 3 1
 
       System.out.println("\n size " + pq2.size());
       System.out.println(" peek " + pq2.peek());    // The peek() method returns top head of Queue not delete it as poll() do both (return head and delete).
       System.out.println(" size " + pq2.size());
       System.out.println(" poll " + pq2.poll());   // poll(): Retrieves and removes the head of this queue, or returns null if this queue is empty.
       System.out.println(" size " + pq2.size());
       for(int x : ia) // review queue
         System.out.print(pq2.poll() + " ");
    }
}

Monday, September 19, 2011

Knowledge Sharing Information: Displaying Location Specific Ads

Knowledge Sharing Information: Displaying Location Specific Ads: Google and Apple take another step in displaying ads. They are tracking user location to serve them specific advertisements about the th...

How to un-install .apk file from Windows

Uninstalling apk file from Windows for Android SDK

First we hope you have already updated the path environment variable by adding the Android SDK/tools path into it.

Now first see how many apk are there in your android emulator. Give the following command...


C:\Android\android-sdk\tools> adb shell ls data/app
ApiDemos.apk
GestureBuilder.apk
SoftKeyboard.apk
CubeLiveWallpapers.apk
com.example.test.apk
com.example.gridviewTest.apk
com.example.android.apis.graphics.apk
com.rcreations.send2printer.apk
**Note: Here as you already know that Android is a Linux based OS, so you need  to use ls command to see all .apk files in app directory under data directory.
--------------------------------------------------------------------------------
Now remove the app whatever you want, use this command...
C:\Android\android-sdk\tools> adb shell  rm  data/app/com.rcreations.send2printer.apk

Now see whether your file com.rcreations.send2printer.apk has been removed or not.
 
C:\Android\android-sdk\tools> adb shell ls data/app
ApiDemos.apk
GestureBuilder.apk
SoftKeyboard.apk
CubeLiveWallpapers.apk
com.example.test.apk
com.example.gridviewTest.apk
com.example.android.apis.graphics.apk

Freeware Lovers Blog: How to Install APK Files on Android Device Emulato...

Freeware Lovers Blog: How to Install APK Files on Android Device Emulato...: In this tutorial we want to explain how to install APK-files to an Android device emulator. Thus you will be able to test already now all ne...

Google Cloud Print

Google launched new service 'Google Cloud Print'. Here you can install your printer to Google Cloud  and then you can access it from anywhere in this world by using a computer or smart phone.

What you need to do just activate Google Cloud Print Connector in Google Chrome and then your printer will install automatically.

Sunday, September 18, 2011

How to install apk file in Android device ?

Just connect your android device directly and select USB debugging option in the device.

The eclipse Id will find your android device itself and now you can run the code.

Second option: Just paste your apk file in android sdk tools folder and then use command prompt install like given here.

C://Android/......../tools>adb install filetoInstall.apk

Note:  If somebody have a different idea, he can reply.

Monday, September 12, 2011

Struts2: Session Problem (after reverse proxy) on Apache Server

Session parameters are stored in a Struts2 session map in action using the SessionAware interface. 
Application's context path is  /MyApp
Use Apache server with an inverse proxy redirect that makes the URL http://www.appdomain.com/ point to local tomcat on localhost:8080/MyApp, Struts2 session handling doesn't work.

 Solution:
Set your ProxyPassReverseCookie path properly":
        ProxyPass / http://localhost:8080/VicWalks/
        ProxyPassReverse / http://localhost:8080/VicWalks/
        ProxyPassReverseCookiePath /VicWalks /
 For more info:
ProxyPassReverseCookiePath directives. See:
http://httpd.apache.org/docs/2.2/mod/mod_proxy.html#proxypassreversecookiedomain

      

Monday, September 5, 2011

List all files in a directory using java

=======List all file with their names in a existing directory  on your hard disk=====
        String walkImageDir="C://MyDirectory//imageFiles";
         File dir = new File(imageDir);
         System.out.println("===dir.isDirectory()====="+dir.isDirectory());
          
           if(dir.isDirectory()){
                File[] imgFiles = dir.listFiles();
                System.out.println("===file dir size:"+imgFiles.length);
                for(File image: imgFiles){
                     System.out.println("====images are :"+image.getName());
                   
                }
              }