Monday, June 10, 2013

Send mail using java (Exchange Server)


External jar needs to be added is "mail.jar".
========================================================
package com.myExample.mail;

public class Client {
      public static void main(String[] args) {
            String To = "abc1@xyz.com; abc2@xyz.com ; abc3@xyz.com ";
            String CC = " abc4@xyz.com; abc5@xyz.com ; abc6@xyz.com ";
            String BCC = "abc@xyz.com";
            String From = "myExmp@ddd.com";
            String Subject = "Test subject line.";
            String Body = "Test mail Body.";
            MailExample obj = new MailExample();
            obj.sendAMail(To, CC, BCC, From, Body, Subject);
      }
}

=========================================================
package com.myExample.mail;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMessage.RecipientType;

public class MailExample {
                public void sendAMail(String To, String CC, String BCC, String From,
                                                String Body, String Subject) {
                                try {
                                                Sendmail(To, CC, BCC, From, Body, Subject);
                                } catch (MessagingException ex) {
                                                Logger.getLogger(MailExample.class.getName()).log(Level.SEVERE,
                                                                                null, ex);
                                }
                }

                public void Sendmail(String To, String CC, String BCC, String From,
                                                String Body, String Subject) throws MessagingException {
                                Message message = new MimeMessage(getSession());
                                if (To != null && To.trim().length() > 0) {
                                                //Separate "To" mail address based on ";" separator and set it into mail "To" address.
                                                Iterator<String> ToIterator=this.getAddressList(To).iterator();
                                                while(ToIterator.hasNext()){
                                                                message.addRecipient(RecipientType.TO, new InternetAddress(ToIterator.next()));
                                                }
                                               
                                                if (CC != null && CC.trim().length() > 0){
                                                                //Separate "CC" mail address based on ";" separator and set it into mail "CC" address.
                                                                Iterator<String> CCIterator=this.getAddressList(CC).iterator();
                                                                while(CCIterator.hasNext()){
                                                                                message.addRecipient(RecipientType.CC, new InternetAddress(CCIterator.next()));
                                                                }
                                                }
                                                               
                                                if (BCC != null && BCC.trim().length() > 0){
                                                                //Separate "BCC" mail address based on ";" separator and set it into mail "BCC" address.
                                                                Iterator<String> BCCIterator=this.getAddressList(BCC).iterator();
                                                                while(BCCIterator.hasNext()){
                                                                                message.addRecipient(RecipientType.BCC, new InternetAddress(BCCIterator.next()));
                                                                }
                                                }
                                               
                                                if (From != null && From.trim().length() > 0)
                                                                message.addFrom(new InternetAddress[] { new InternetAddress(
                                                                                                From) });

                                                message.setSubject(Subject);
                                                message.setContent(Body, "text/plain");
                                }
                                System.out.println("Sending mail .............................");
                                Transport.send(message);
                                System.out.println("Mail sent .............................");
                }

                private Session getSession() {
                                Authenticator authenticator = new Authenticator();

                                Properties properties = new Properties();
                                properties.setProperty("mail.smtp.submitter", authenticator
                                                                .getPasswordAuthentication().getUserName());
                                properties.setProperty("mail.smtp.auth", "true");

                                properties.setProperty("mail.smtp.host", "172.16.16.99");
                                properties.setProperty("mail.smtp.port", "25");

                                return Session.getInstance(properties, authenticator);
                }

                private class Authenticator extends javax.mail.Authenticator {
                                private PasswordAuthentication authentication;

                                public Authenticator() {
                                                String username = "username";
                                                String password = password";
                                                authentication = new PasswordAuthentication(username, password);
                                }

                                protected PasswordAuthentication getPasswordAuthentication() {
                                                return authentication;
                                }
                }
               
                //Separate string using ';' separator.
                private List<String> getAddressList(String address){
                                String mailAddress=address;
                                List<String> mailAddressList = null;
                                if(mailAddress != null && mailAddress.trim().length()>0){
                                                mailAddressList = new ArrayList<String>();
                                                if(mailAddress.contains(";")){
                                                                mailAddressList=Arrays.asList(mailAddress.split(";"));
                                                }else{
                                                                mailAddressList.add(mailAddress.trim());
                                                }
                                }
                                return mailAddressList;
                }
}

Friday, August 24, 2012

Print a file using java

/**
 * @author KushalP
 * www.sanjaal.com/java
 * Last Modified On 2009-05-19
 */


import java.awt.*;
import java.awt.font.*;
import java.awt.geom.*;
import java.awt.print.*;
import java.io.BufferedReader;
import java.io.FileReader;
import java.text.*;

/**
 * Using JAVA to print simple <span class="IL_AD" id="IL_AD3">text file</span> to a printer
 */

public class PrintFileToPrinter implements Printable {

    static AttributedString myStyledText = null;

    public static void main(String args[]) {
        /**Location of a file to print**/
        String fileName = "C:\\temp\\abc.txt";

        /**Read the text content from this location **/
        String mText = readContentFromFileToPrint(fileName);

        /**Create an AttributedString object from the text read*/
        myStyledText = new AttributedString(mText);

        printToPrinter();

    }

    /**
     * This method reads the content of a text file.
     * The location of the file is provided in the parameter
     */
    private static String readContentFromFileToPrint(String fileName) {
        String dataToPrint = "";

        try {
            BufferedReader input = new BufferedReader(new FileReader(fileName));
            String line = "";
            /**Read the file and populate the data**/
            while ((line = input.readLine()) != null) {
                dataToPrint += line + "\n";
            }
        } catch (Exception e) {
            return dataToPrint;
        }
        return dataToPrint;
    }

    /**
     * Printing the data to a printer.
     * Initialization done in this method.
     */
    public static void printToPrinter() {
        /**
         * Get a Printer Job
         */
        PrinterJob printerJob = PrinterJob.getPrinterJob();

        /**
         * <span class="IL_AD" id="IL_AD5">Create a book</span>. A book contains a pair of page painters
         * called <span class="IL_AD" id="IL_AD6">printables</span>. Also you have different pageformats.
         */
        Book book = new Book();
        /**
         * Append the Printable Object (this one itself, as it
         * implements a printable interface) and the page format.
         */
        book.append(new PrintFileToPrinter(), new PageFormat());
        /**
         * Set the object to be printed (the Book) into the PrinterJob. Doing this
         * before bringing up the print dialog allows the print dialog to correctly
         * display the page range to be printed and to dissallow any print settings not
         * appropriate for the pages to be printed.
         */
        printerJob.setPageable(book);

        /**
         * Calling the printDialog will pop up the Printing Dialog.
         * If you want to print without user <span class="IL_AD" id="IL_AD7">confirmation</span>, you can directly call printerJob.print()
         *
         * doPrint will be false, if the user cancels the print operation.
         */
        boolean doPrint = printerJob.printDialog();

        if (doPrint) {
            try {
                printerJob.print();
            } catch (PrinterException ex) {
                System.err.println("Error occurred while trying to Print: "
                        + ex);
            }
        }
    }

    /**
     * This method comes from the Printable interface.
     * The method implementation in this class
     * prints a page of text.
     */
    public int print(Graphics g, PageFormat format, int pageIndex) {

        Graphics2D graphics2d = (Graphics2D) g;
        /**
         * Move the origin from the corner of the Paper to the corner of the imageable
         * area.
         */
        graphics2d.translate(format.getImageableX(), format.getImageableY());

        /** Setting the text color**/
        graphics2d.setPaint(Color.black);
        /**
         * Use a LineBreakMeasurer instance to break our text into lines that fit the
         * imageable area of the page.
         */
        Point2D.Float pen = new Point2D.Float();
        AttributedCharacterIterator charIterator = myStyledText.getIterator();
        LineBreakMeasurer measurer = new LineBreakMeasurer(charIterator,
                graphics2d.getFontRenderContext());
        float wrappingWidth = (float) format.getImageableWidth();
        while (measurer.getPosition() < charIterator.getEndIndex()) {
            TextLayout layout = measurer.nextLayout(wrappingWidth);
            pen.y += layout.getAscent();
            float dx = layout.isLeftToRight() ? 0 : (wrappingWidth - layout
                    .getAdvance());
            layout.draw(graphics2d, pen.x + dx, pen.y);
            pen.y += layout.getDescent() + layout.getLeading();
        }
        return Printable.PAGE_EXISTS;
    }

}

Tuesday, January 31, 2012

JDBC example


private static Connection connectToDatabaseOrDie()
{
Connection conn = null;
try
{
Class.forName("org.postgresql.Driver");
String url = "jdbc:postgresql://localhost/abc";
conn = DriverManager.getConnection(url, "userName", "password");
}
catch (ClassNotFoundException e)
{
e.printStackTrace();
System.exit(1);
}
catch (SQLException e)
{
e.printStackTrace();
System.exit(2);
}
return conn;
}


Tuesday, January 10, 2012

SimpleDateFormat.......list

http://docs.oracle.com/javase/1.3/docs/api/java/text/SimpleDateFormat.html

Symbol Meaning Presentation Example
------ ------- ------------ -------

G era designator (Text) AD
y year (Number) 1996
M month in year (Text & Number) July & 07
d day in month (Number) 10
h hour in am/pm (1~12) (Number) 12
H hour in day (0~23) (Number) 0
m minute in hour (Number) 30
s second in minute (Number) 55
S millisecond (Number) 978
E day in week (Text) Tuesday
D day in year (Number) 189
F day of week in month (Number) 2 (2nd Wed in July)
w week in year (Number) 27
W week in month (Number) 2
a am/pm marker (Text) PM
k hour in day (1~24) (Number) 24
K hour in am/pm (0~11) (Number) 0
z time zone (Text) Pacific Standard Time
' escape for text (Delimiter)
'' single quote (Literal) '

Monday, January 9, 2012

Date Format example in JAVA


//Program to use date format …………………
package Time;

import java.text.SimpleDateFormat;
import java.util.Date;

public class DateTimeExample
{
public static void main(String[] args)
{
Date date = new Date();
System.out.println("Date is (with out using any date formate ==================> "+date);

SimpleDateFormat simpleDateFormate = new SimpleDateFormat("E dd.MM.yyyy 'at' hh:mm:ssa zzz");
System.out.println("SimpleDateFormat1 is (\"E dd.MM.yyyy 'at' hh:mm:ssa zzz\")===> "+simpleDateFormate.format(date));

simpleDateFormate = new SimpleDateFormat("E d.MM.y 'at' hh:mm:ssa zzz");
System.out.println("SimpleDateFormat2 is (\"E d.MM.y 'at' hh:mm:ssa zzz\") ======> "+simpleDateFormate.format(date));

simpleDateFormate = new SimpleDateFormat("EEEE dd.MMMM.yyyy 'at' hh:mm:ssa");
System.out.println("SimpleDateFormat3 is (\"EEEE dd.MMMM.yyyy 'at' hh:mm:ssa\") => "+simpleDateFormate.format(date));
}
}

OUTPUT =>
Date is (with out using any date formate ==================> Tue Jan 10 13:13:10 IST 2012
SimpleDateFormat1 is ("E dd.MM.yyyy 'at' hh:mm:ssa zzz")===> Tue 10.01.2012 at 01:13:10PM IST
SimpleDateFormat2 is ("E d.MM.y 'at' hh:mm:ssa zzz") ======> Tue 10.01.12 at 01:13:10PM IST
SimpleDateFormat3 is ("EEEE dd.MMMM.yyyy 'at' hh:mm:ssa") => Tuesday 10.January.2012 at 01:13:10PM

Wednesday, January 4, 2012

Monday, October 10, 2011

Conditional Operator Example in java.


package ConditionalOperatorExample;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class ConditionalOperatorExample
{
public static void main(String[] arun) throws IOException
{
String s1,s2,s3;
int i1,i2,i3,Max,Min;

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

System.out.println("Enter first number; ");
s1 = br.readLine();

System.out.println("Enter second number: ");
s2 = br.readLine();

System.out.println("Enter third number: ");
s3 = br.readLine();

i1 = Integer.valueOf(s1).intValue();
i2 = Integer.valueOf(s2).intValue();
i3 = Integer.valueOf(s3).intValue();

Max = (i1>i2)?((i1>i3)?i1:i3):((i2>i3)?i2:i3);
System.out.println("Maximum number is "+Max);

Min = (i1 System.out.println("Minimum number is "+Min);
}
}


Output =>
Enter first number;
25
Enter second number:
3
Enter third number:
64
Maximum number is 64
Minimum number is 3