Posts

Showing posts from September, 2011

finally in Exception Handling in Java

finally block always executes aftertry block. Sofinally 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()); …

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

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().leng…

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()…

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

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--
------------------…

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…

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...
i…

Google plus+ : A new Social networking to beat Facebook

Image
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

Image
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 implementsQueue 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.pollFirst…

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) // l…

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.apkhas been removed or not.

C:\Android\android-sdk\tools>adb s…

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.

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.

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


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

                }
              }