Problem in using java print API

I am facing a problem in using printAll and printComponents API.
The application was developed in java1.1
Now the same application is migrated to java 1.4
But the reports are not being printed in desired format.
The application make use of printAll() API of Component.
Using java1.1 the print output is without the borders for components like textField or TextArea,
whereas for java 1.4 we get border and scrollbar on print which is not the desired output.
Can anybody suggest a solution for the same?
here is the sample code, you can see the difference by executing this code in java1.1 and java 1.4.
import java.awt.*;
import java.util.*;
public class TestPrint extends Frame implements java.awt.event.ActionListener {
PrintJob job = null;
//Frame aFrame = new Frame("Test Frame");
private TextArea txaChangeNotes = null;
private Label lb = null;
private Panel ivjContentsPane = null;
private Button ivjButton1 = null;
TestPrint () {
     super("Test Frame");
     init();
private void init() {
     ivjContentsPane = new java.awt.Panel();
     ivjContentsPane.setName("ContentsPane");
     txaChangeNotes = new java.awt.TextArea("",0,0,java.awt.TextArea.SCROLLBARS_BOTH);
     txaChangeNotes.setText("****\n&&&");
     ivjButton1 = new java.awt.Button();
     ivjButton1.setName("Button1");
     ivjButton1.addActionListener(this);
     ivjContentsPane.add(txaChangeNotes);
     ivjContentsPane.add(lb);
     ivjContentsPane.add(ivjButton1);
     this.add(ivjContentsPane);
     setSize(595, 735);
     show();
public void actionPerformed(java.awt.event.ActionEvent e) {
     Object obj = e.getSource() ;
     if( obj instanceof java.awt.Button ){
          //Button but = e.getSource();
          print();
private void print() {
     System.out.println("In Print");
     job = getPrintJob(this , "Print All Parts");
     //job.setPrintable(this);
     if(job!=null){
          System.out.println("Job not null");     
          /*if (job.printDialog()) {
     try {
               System.out.println("printing");     
     job.print();
     } catch (Exception ex) {
     ex.printStackTrace();
          Graphics pg=job.getGraphics();
          if(pg!=null){
          System.out.println("graphics not null");     
               this.requestFocus();
               //this.printComponents(pg);
               this.printAll(pg);
          }else{
          System.out.println("graphics null");     
               //this.dispose();
               return;
          pg.dispose();
     }else{
          System.out.println("job null");
          //this.dispose();
          return;
     job.end();     
private PrintJob getPrintJob (Frame aFrame,String aString) {
     Properties printprefs = null;
     Toolkit toolkit = java.awt.Toolkit.getDefaultToolkit();
     PrintJob job = toolkit.getPrintJob(aFrame, aString, printprefs);
     /*JobAttributes jab = null;
     jab = new JobAttributes();
     PageAttributes pab = null;
     pab = new PageAttributes();
     pab.setPrinterResolution(70);
     jab.setDialog(JobAttributes.DialogType.COMMON);
PrintJob job = Toolkit.getDefaultToolkit().getPrintJob(aFrame, aString, jab, pab);*/
     return job;
public static void main(String arg[]){
     TestPrint objTestPrintFrame = new TestPrint();
}

You must not have the complete IFS_BASE_CLASSPATH defined in your CLASSPATH environment variable. The easiest way to do this is to type ". ifsenv.sh" on Solaris (or run ifsenv.bat on NT). Then you can invoke java like this:
java -classpath $CLASSPATH:$IFS_BASE_CLASSPATH ...
(your standard JDK classes should already be in the CLASSPATH; append our classpath to it)

Similar Messages

  • How to print a document in reverse order using Java Print API ?

    I need to print a document in reverse order using Java Print API (*Reverse Order Printing*)
    Does Java Print API supports reverse order printing ?
    Thnks.,

    deepak_c3 wrote:
    Thanks for the info.,
    where should the page number n-1-i be returned ?
    Which method implementation of Pageable interface should return the page number ?w.r.t. your first question: don't return that number but return page n-1-i when page i is requested; your document will be printed in reverse order. Your class should implement the entire interface and wrap the original Pageable. (for that number n your class can consult the wrapped interface; read the API for the Pageable interface).
    kind regards,
    Jos

  • Printing a microsoft word doc using Java Print API

    Hi,
    I have to print a microsoft word doc.I am using Java Print API, but the code is printing only Hashcodes instead of the actual document.
    Here is the code. Please let me know whats wrong in it.
    CODE:::
    public String print() throws Exception {
    String realPath = getRealPath("/images/formLibrary/csaAddressContactRequestForm100.doc");
    PrintRequestAttributeSet pras1 = new HashPrintRequestAttributeSet();
    DocFlavor flavor1 = DocFlavor.INPUT_STREAM.AUTOSENSE;
    PrintService defaultService = PrintServiceLookup.lookupDefaultPrintService();
    DocPrintJob job = defaultService.createPrintJob();
    FileInputStream fis1 = new FileInputStream(realPath);
    DocAttributeSet das = new HashDocAttributeSet();
    Doc doc1 = new SimpleDoc(fis1, flavor1, das);
    job.print(doc1, pras1);
    Thread.sleep(10000);
    System.exit(0);
    return "";
    }

    By using an appropriate library. JText, whatever.
    Google, man.I think Rene meant iText!Whatever. :) Never used it, I just remembered there was something named like that. Thanks.

  • How to use java print API???  very very urgent

    Hi
    I fed up with the JAVA print API. If anybody knows how to print a file .txt, please let me know.
    cheers
    shyam

    import javax.swing.*;
    import java.util.*;
    import java.awt.*;
    import java.awt.image.*;
    import java.awt.event.*;
    import java.sql.*;
    import javax.print.*;
    import javax.print.attribute.*;
    import utility.*;
    import java.awt.print.*;
    public class remRunPrint extends JFrame implements ActionListener, Printable {
         static JButton j = new JButton("Print");
         String printer = "IT";
         java.util.Date pDate;
         public void setCopies(int i) {
              copies = i;
         public void setPrinter(String s) {
              if (s.length() > 0) {
                   printer = s;
         public void getInfo(int vid) {
              ResultSet verRS;
              try {
                   Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                   Connection conn = DriverManager.getConnection("jdbc:odbc:SOMEdbnAME");
                   Statement stmt = conn.createStatement();
                   verRS = stmt.executeQuery("SOME SQL QUERY HERE");
                   verRS.next();
                   //SET SOME VARIABLES HERE..
              } catch (Exception e) {
                   System.out.println("getinfo: " + e);
    public void actionPerformed(ActionEvent e) {
    if (e.getSource() instanceof JButton) {  
                   wookie();
         public void wookie() {
              PrinterJob printJob = PrinterJob.getPrinterJob();
              Paper paper = new Paper();
              PageFormat page = new PageFormat();
              paper.setImageableArea(0, 0, 600, 800);     
              page.setPaper(paper);
              printJob.setPrintable(this, page);
              PrintService[] services = PrintServiceLookup.lookupPrintServices(null, new HashPrintRequestAttributeSet());
              PrintService ps = PrintServiceLookup.lookupDefaultPrintService();
              for (int i=0; i<services.length;i++) {
                   if (services.toString().indexOf(printer) > 0) {
                        ps = services[i];     
              try{
                   printJob.setCopies(copies);
                   //printJob.pageDialog(page);
                   printJob.setPrintService(ps);
                   //if (printJob.printDialog()) {
                        printJob.print();
              } catch (Exception e) {
                   System.out.println("wookie1run1" + e);
         public static void main(String[] args) {
              remRunPrint at = new remRunPrint();
              at.getInfo((new Integer(args[0])).intValue());
              at.drawShapes();
              at.wookie();
         public void drawShapes() {
              setBounds(0, 0, 670, 550);
              addWindowListener(new WindowAdapter() {public void windowClosing(WindowEvent e) {System.exit(0);}});
              JLabel l = new JLabel("<html><body><table><tr bgcolor=blue><td><font color=red>Hello EVERYONE</font></td></tr></table></body></html>");
              l.setBounds(20, 20, 120, 20);
              j.setBounds(10, 10, 10, 10);
              j.addActionListener(this);
              getContentPane().setLayout(null);
              getContentPane().add(l);
              getContentPane().add(j);
              show();
         public remRunPrint(){}
         public void paint(Graphics g) {
              g.setFont(new Font("SansSerif", Font.PLAIN, 6));
              g.drawString("PrintDate:", 520, 20);
              g.setFont(new Font("SansSerif", Font.BOLD, 9));
              g.drawString(pDateSTR, 550, 20);
              g.drawString("JOB: ", 23, 37);
              g.drawString("VERSION:", 310, 37);
              g.drawString("#" + vID, 310, 28);
              g.setFont(new Font("SansSerif", Font.BOLD, 18));
              g.drawString(jName, 48, 37);
              g.drawString(vName, 355, 37);
              //HERE ARE A COUPLE LINES OF AWT DRAWING TO A SCREEN THAT WORK ... IF YOU LAUNCH THIS APP FROM THE COMMAND LINE
              //IT WILL SHOW YOU WHAT YOU ARE GOING TO PRINT.. SO YOU CAN FORMAT IT AND BUILD IT FIRST THEN PRINT IT WITH THE
              //BUTTON...
         public int print(Graphics g, PageFormat pf, int pi) throws PrinterException {
    if (pi >= 1) {
    return Printable.NO_SUCH_PAGE;
              paint(g);
    return Printable.PAGE_EXISTS;

  • How do i use java printing api 1.4

    How can i print documents using jdk1.4 api.
    I have used the following program for printing.
    import java.io.*;
    import java.awt.*;
    import java.awt.print.*;
    import javax.print.*;
    import javax.print.attribute.*;
    import javax.print.attribute.standard.*;
    public class Print2DtoStream implements Printable{
    public Print2DtoStream() {
    /* Use the pre-defined flavor for a Printable from an InputStream */
    DocFlavor flavor = DocFlavor.SERVICE_FORMATTED.PRINTABLE;
    /* Specify the type of the output stream */
    String psMimeType = DocFlavor.BYTE_ARRAY.POSTSCRIPT.getMimeType();
    /* Locate factory which can export a GIF image stream as Postscript */
    StreamPrintServiceFactory[] factories =
    StreamPrintServiceFactory.lookupStreamPrintServiceFactories(flavor, psMimeType);
    if (factories.length == 0) {
    System.err.println("No suitable factories");
    System.exit(0);
    try {
    /* Create a file for the exported postscript */
    FileOutputStream fos = new FileOutputStream("out.ps");
    /* Create a Stream printer for Postscript */
    StreamPrintService sps = factories[0].getPrintService(fos);
    /* Create and call a Print Job */
    DocPrintJob pj = sps.createPrintJob();
    PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
    Doc doc = new SimpleDoc(this, flavor, null);
    pj.print(doc, aset);
    fos.close();
    } catch (PrintException pe) {
    System.err.println(pe);
    } catch (IOException ie) {
    System.err.println(ie);
    public int print(Graphics g,PageFormat pf,int pageIndex) {
    if (pageIndex == 0) {
    Graphics2D g2d= (Graphics2D)g;
    g2d.translate(pf.getImageableX(), pf.getImageableY());
    g2d.setColor(Color.black);
    g2d.drawString("example string", 250, 250);
    g2d.fillRect(0, 0, 200, 200);
    return Printable.PAGE_EXISTS;
    } else {
    return Printable.NO_SUCH_PAGE;
    public static void main(String args[]) {
    Print2DtoStream sp = new Print2DtoStream();
    However when i run this program,it prints "example string" as used in g2d.drawString("example string",250,250) method above.
    What if i want to print content from any file.
    So anybody konwing this plz reply

    This is covered pretty well in the Java Print Service API Guide.
    You could start here http://java.sun.com/j2se/1.4.1/docs/guide/jps/spec/printing.fm1.html
    Basically, you have two choices - either you're going to throw a document at the print service, or you're going to print using Graphics2D commands. You also have the choice between printing to a printer, or to a stream. Mix and match for four combinations.
    Whether you can just take a raw document and send it to a printer via the document printing stuff depends on what print services you have installed. For the standard J2SE, it's pretty limited.
    If you're doing it via the Graphics2D approach, however, you can print anything you can draw. That's nice - it means you can use the same code to display stuff on the screen and print it.

  • PrintScreen Functionality using Java Print Api(without Robot)

    Hi Guys
    I have an issue to discuss,can any of you tell me that is it possible to take the screen shot of screen(not printing on paper) in java using Print Api .
    I have done it with robot but i want to do it without using Robot.
    Thanks
    Vipul

    Vipul wrote:
    can u please tell me how to implement it.i want to take the screenshot not printing a java container on paper.
    package test;
    * Screenshot.java
    import java.awt.*;
    import java.awt.print.*;
    import javax.swing.*;
    public class Screenshot extends JPanel {
        private Container container;
        public Screenshot(Container container) {
            this.container = container;
        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            container.print(g);
        //"main" only for Testing:
        public static void main(String[] args) {
            final JFrame f = new JFrame("Frame");
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.setSize(500, 600);
            JPanel panel = new JPanel(new BorderLayout());
            panel.add(new JTextField("Begin"), BorderLayout.NORTH);
            panel.add(new JColorChooser());
            panel.add(new JTextField("End"), BorderLayout.SOUTH);
            f.add(panel);
            f.setVisible(true);
            new Thread(new Runnable() {
                public void run() {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException ex) {
                    JDialog d = new JDialog(f, "Screenshot of Frame");
                    d.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
                    d.setSize(f.getSize());
                    d.setLocationRelativeTo(null);
                    d.add(new Screenshot(f.getContentPane()));
                    d.setVisible(true);
            }).start();
    }

  • How to print PDF files using java print API

    Hi,
    I was goign throw lot of discusion and reading lot of forums related to print pdf files using java api. but nothing seems to be working for me. Can any one tell me how to print pdf files using java api.
    Thanks in advance

    Mike,
    Can't seem to get hold of the example described in your reply below. If you could let us have the URL to get then it would be great.
    My GUI application creates a pdf document which I need to print. I want to achieve this using the standard Java class PrinterJob (no 3rd party APIs I'm afraid, commercial restraints etc ..). I had a stab at it using the following code. When executed I get the pretty printer dialog then when I click ok to print, nothing happens!
    boolean showPrintDialog=true;
    PrinterJob printJob = PrinterJob.getPrinterJob ();
    printJob.setJobName ("Contract.pdf");
    try {
    if (showPrintDialog) {
    if (printJob.printDialog()) {
    printJob.print();
    else
    printJob.print ();
    } catch (Exception PrintException) {
                   PrintException.printStackTrace();
    Thank you and a happy new year.
    Cheers,
    Chris

  • Print .PDT,.DOC,.XLS files using java print API

    Hi,
    I need to print different types of documents like pdf, word, excel files etc.
    Please let me know how to proceed on this.
    I tried using the following code, but it is printing all junk/html tags on the paper.
    Please let me know how to resolve this.
    Thanks in advance
    import java.io.File;
    import java.io.IOException;
    import javax.print.DocFlavor;
    import javax.print.DocPrintJob;
    import javax.print.PrintException;
    import javax.print.PrintService;
    import javax.print.PrintServiceLookup;
    import javax.print.SimpleDoc;
    public class PrintDocument {
      static public void main(String args[]) throws Exception {
        try {
             PrintService defaultPrintService = PrintServiceLookup.lookupDefaultPrintService();
            DocPrintJob printerJob = defaultPrintService.createPrintJob();
            File pdfFile = new File("C:\\temp\\sample.doc");
            SimpleDoc simpleDoc = new SimpleDoc(pdfFile.toURL(), DocFlavor.URL.AUTOSENSE, null);
            printerJob.print(simpleDoc, null);
        } catch (IOException ie) {
          ie.printStackTrace();
        } catch (PrintException pe) {
          pe.printStackTrace();
    }

    Hi
    I would like to see if it was possible.  I thought it would be easy, as
    there is a standard batch processing sequence (Print 1st page of all) using
    Java that comes with Acrobat 7.  This allows you to print the first page of
    a number of files that you select when the sequence is run.  Its code is:
    /* Print 1st Page */
    /* This sequence prints the first page of
       each document selected to the default printer.
    this.print
    To my uninformed mind it seemed logical that the same code, slightly
    modified to print all pages, should work from within a form.
    Anyway, if there is a way to choose individual files, I would appreciate
    that.
    Thanks
    Rob

  • How to  print pdf file by using java print API ? I am trying with this code

    import java.io.FileInputStream;
    import java.io.InputStream;
    import javax.print.Doc;
    import javax.print.DocFlavor;
    import javax.print.DocPrintJob;
    import javax.print.PrintException;
    import javax.print.PrintService;
    import javax.print.PrintServiceLookup;
    import javax.print.SimpleDoc;
    import javax.print.attribute.HashPrintRequestAttributeSet;
    import javax.print.attribute.PrintRequestAttributeSet;
    import javax.print.attribute.standard.Copies;
    import javax.print.attribute.standard.MediaSizeName;
    public class PDFPrint {
    static public void print(InputStream inputStream, PrintService printService) throws PrintException {
    Doc doc = new SimpleDoc(inputStream, DocFlavor.INPUT_STREAM.AUTOSENSE, null);
    PrintRequestAttributeSet attributes = new HashPrintRequestAttributeSet();
    attributes.add(MediaSizeName.ISO_A4);
    attributes.add(new Copies(1));
    print(doc, attributes, printService);
    }//print()
    static public void print(Doc doc, PrintRequestAttributeSet attributes, PrintService printService) throws PrintException {
    if (printService == null) {
    printService = PrintServiceLookup.lookupDefaultPrintService();
    System.out.println("The Printer Name is :"+printService.getName());
    DocPrintJob docPrintJob = printService.createPrintJob();
    System.out.println("Before Print Start()");
    docPrintJob.print(doc, attributes);
    }//print()
    public static void main(String args[])
    PrintService defaultPrintService = PrintServiceLookup.lookupDefaultPrintService();
    String file="c:/BackUp/file.pdf";
    FileInputStream fis=new FileInputStream(file);
    System.out.println("Before Print() called ..");
    print(fis,defaultPrintService);
    System.out.println("After Printing....");
    I am using this code to print pdf file. But when I try this one automatically the printer starting with print ascii codes with infinite loop.
    I am using jdk1.4,Acrobat 8.0, Windows environment.
    Can u help me in this regard'
    Thank u
    grani

    import java.io.FileInputStream;
    import java.io.InputStream;
    import javax.print.Doc;
    import javax.print.DocFlavor;
    import javax.print.DocPrintJob;
    import javax.print.PrintException;
    import javax.print.PrintService;
    import javax.print.PrintServiceLookup;
    import javax.print.SimpleDoc;
    import javax.print.attribute.HashPrintRequestAttributeSet;
    import javax.print.attribute.PrintRequestAttributeSet;
    import javax.print.attribute.standard.Copies;
    import javax.print.attribute.standard.MediaSizeName;
    public class PDFPrint {
    static public void print(InputStream inputStream, PrintService printService) throws PrintException {
    Doc doc = new SimpleDoc(inputStream, DocFlavor.INPUT_STREAM.AUTOSENSE, null);
    PrintRequestAttributeSet attributes = new HashPrintRequestAttributeSet();
    attributes.add(MediaSizeName.ISO_A4);
    attributes.add(new Copies(1));
    print(doc, attributes, printService);
    }//print()
    static public void print(Doc doc, PrintRequestAttributeSet attributes, PrintService printService) throws PrintException {
    if (printService == null) {
    printService = PrintServiceLookup.lookupDefaultPrintService();
    System.out.println("The Printer Name is :"+printService.getName());
    DocPrintJob docPrintJob = printService.createPrintJob();
    System.out.println("Before Print Start()");
    docPrintJob.print(doc, attributes);
    }//print()
    public static void main(String args[])
    PrintService defaultPrintService = PrintServiceLookup.lookupDefaultPrintService();
    String file="c:/BackUp/file.pdf";
    FileInputStream fis=new FileInputStream(file);
    System.out.println("Before Print() called ..");
    print(fis,defaultPrintService);
    System.out.println("After Printing....");
    I am using this code to print pdf file. But when I try this one automatically the printer starting with print ascii codes with infinite loop.
    I am using jdk1.4,Acrobat 8.0, Windows environment.
    Can u help me in this regard'
    Thank u
    grani

  • Problem using Java Mail API with WLS 7.0

    Hi All,
    I am trying to use the Java Mail API provided by WLS 7.0. I have made the
    settings metioned in the WLS 7.0 docs. However when I try to run the program I
    am getting the following error:
    javax.naming.NoInitialContextException: Need to specify class name in environment
    or system property, or as an applet parameter, or in an application resource file:
    java.naming.factory.initial
    at javax.naming.spi.NamingManager.getInitialContext(NamingManager.java:6
    46)
    at javax.naming.InitialContext.getDefaultInitCtx(InitialContext.java:246
    at javax.naming.InitialContext.getURLOrDefaultInitCtx(InitialContext.jav
    a:283)
    at javax.naming.InitialContext.lookup(InitialContext.java:350)
    The code that I have written is as follows
    import java.util.*;
    import javax.activation.*;
    import javax.mail.*;
    import javax.mail.internet.*;
    import javax.naming.*;
    import java.io.*;
    import java.net.InetAddress;
    import java.util.Properties;
    import java.util.Date;
    public class MailTo {
         public static void main(String args[])
              try
                   //Context ic = getInitialContext();
                   InitialContext ic = new InitialContext();
    /* My jndi name is "testSession" */
                   Session session = (Session) ic.lookup("testSession"); /* THE PROBLEM IS SHOWN
    IN THIS LINE */
                   Properties props = new Properties();
                   props.put("mail.transport.protocol", "smtp");
                   props.put("mail.smtp.host", "XX.XX.XX.XX");
    /* For security reasons I have written the ip add in this format */
                   props.put("mail.from", "[email protected]"); /* for security reasons i have
    changed the mail address */
                   Session session2 = session.getInstance(props);
                   Message msg = new MimeMessage(session2);
                   msg.setFrom();
                   msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse("[email protected]",
    false));
                   msg.setSubject("Test Message");
                   msg.setSentDate(new Date());
                   MimeBodyPart mbp = new MimeBodyPart();
                   mbp.setText("This is a mail sent to you using JAVA Mail API and Weblogic Server");
                   Multipart mp = new MimeMultipart();
                   mp.addBodyPart(mbp);
                   msg.setContent(mp);
                   Transport.send(msg);
              catch(Exception e)
                   e.printStackTrace();
         }//end of main
    public static Context getInitialContext()
         throws NamingException
              Properties p = new Properties();
              p.put(Context.INITIAL_CONTEXT_FACTORY, "weblogic.jndi.WLInitialContextFactory");
              p.put(Context.PROVIDER_URL, "t3://localhost:7501/testWebApp");
                   p.put(Context.SECURITY_PRINCIPAL, "weblogic");
                   p.put(Context.SECURITY_CREDENTIALS, "weblogic");
              return new InitialContext(p);
    }//end of class
    Can anyone please tell me what is the problem. I thought that we cannot directly
    do
    InitialContext ic = new InitialContext();
    So I had written a method getInitialContext() as shown in the above piece of code,
    but that too did not work.
    Eagerly awaiting a response.
    Jimmy Shah

    You can use InitialContext ic = new InitialContext() only if you are using a startup class, servlet or a JSP i.e
    server side code.
    If you are using a java client you need to use Context ic = getInitialContext();
    Try this code
    import java.util.*;
    import javax.activation.*;
    import javax.mail.*;
    import javax.mail.internet.*;
    import javax.naming.*;
    import java.io.*;
    import java.net.InetAddress;
    import java.util.Properties;
    import java.util.Date;
    public class MailTo {
    public static void main(String args[])
    try {
    Properties h = new Properties();
    h.put(Context.INITIAL_CONTEXT_FACTORY,"weblogic.jndi.WLInitialContextFactory");
    h.put(Context.PROVIDER_URL, "t3://localhost:7001");
    Context ic = new InitialContext(h);
    Session session = (Session) ic.lookup("testSession");
    Properties props = new Properties();
    props.put("mail.transport.protocol", "smtp");
    props.put("mail.smtp.host", "XX.XX.XX.XX");
    props.put("mail.from", "[email protected]");
    Session session2 = session.getInstance(props);
    Message msg = new MimeMessage(session2);
    msg.setFrom();
    msg.setRecipients(Message.RecipientType.TO,InternetAddress.parse("[email protected]",false));
    msg.setSubject("Test Message");
    msg.setSentDate(new Date());
    MimeBodyPart mbp = new MimeBodyPart();
    mbp.setText("This is a mail sent to you using JAVA Mail API and Weblogic Server");
    Multipart mp = new MimeMultipart();
    mp.addBodyPart(mbp);
    msg.setContent(mp);
    Transport.send(msg);
    catch(Exception e)
    e.printStackTrace();
    }//end of main
    }//end of class
    We have shipped a javamail example in the samples\server\src\examples\javamail folder.
    Jimmy Shah wrote:
    Hi All,
    I am trying to use the Java Mail API provided by WLS 7.0. I have made the
    settings metioned in the WLS 7.0 docs. However when I try to run the program I
    am getting the following error:
    javax.naming.NoInitialContextException: Need to specify class name in environment
    or system property, or as an applet parameter, or in an application resource file:
    java.naming.factory.initial
    at javax.naming.spi.NamingManager.getInitialContext(NamingManager.java:6
    46)
    at javax.naming.InitialContext.getDefaultInitCtx(InitialContext.java:246
    at javax.naming.InitialContext.getURLOrDefaultInitCtx(InitialContext.jav
    a:283)
    at javax.naming.InitialContext.lookup(InitialContext.java:350)
    The code that I have written is as follows
    import java.util.*;
    import javax.activation.*;
    import javax.mail.*;
    import javax.mail.internet.*;
    import javax.naming.*;
    import java.io.*;
    import java.net.InetAddress;
    import java.util.Properties;
    import java.util.Date;
    public class MailTo {
    public static void main(String args[])
    try
    //Context ic = getInitialContext();
    InitialContext ic = new InitialContext();
    /* My jndi name is "testSession" */
    Session session = (Session) ic.lookup("testSession"); /* THE PROBLEM IS SHOWN
    IN THIS LINE */
    Properties props = new Properties();
    props.put("mail.transport.protocol", "smtp");
    props.put("mail.smtp.host", "XX.XX.XX.XX");
    /* For security reasons I have written the ip add in this format */
    props.put("mail.from", "[email protected]"); /* for security reasons i have
    changed the mail address */
    Session session2 = session.getInstance(props);
    Message msg = new MimeMessage(session2);
    msg.setFrom();
    msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse("[email protected]",
    false));
    msg.setSubject("Test Message");
    msg.setSentDate(new Date());
    MimeBodyPart mbp = new MimeBodyPart();
    mbp.setText("This is a mail sent to you using JAVA Mail API and Weblogic Server");
    Multipart mp = new MimeMultipart();
    mp.addBodyPart(mbp);
    msg.setContent(mp);
    Transport.send(msg);
    catch(Exception e)
    e.printStackTrace();
    }//end of main
    public static Context getInitialContext()
    throws NamingException
    Properties p = new Properties();
    p.put(Context.INITIAL_CONTEXT_FACTORY, "weblogic.jndi.WLInitialContextFactory");
    p.put(Context.PROVIDER_URL, "t3://localhost:7501/testWebApp");
    p.put(Context.SECURITY_PRINCIPAL, "weblogic");
    p.put(Context.SECURITY_CREDENTIALS, "weblogic");
    return new InitialContext(p);
    }//end of class
    Can anyone please tell me what is the problem. I thought that we cannot directly
    do
    InitialContext ic = new InitialContext();
    So I had written a method getInitialContext() as shown in the above piece of code,
    but that too did not work.
    Eagerly awaiting a response.
    Jimmy Shah--
    Rajesh Mirchandani
    Developer Relations Engineer
    BEA Support

  • Java Print API - Pages per sheet

    Hello
    I made a java application to print a file.
    Everything works fine.
    Now, I would like to be able to indicate that I want to print 2 pages per sheet.
    How can I do that?

    Thanks
    So I tried using 2 different ways: using javax.print API and using java.awt.print.PrinterJob
    Here is the code and result with the javax.print API:
    Result: the file is printed correctly but the properties I filled on the printer dialog selection, no properties has been taken: I choose monochrome, the file has been printed in colors, I choose 2 pages per sheet and 1 page has been printed each sheet.
    Code:
    import java.io.FileInputStream;
    import javax.print.Doc;
    import javax.print.DocFlavor;
    import javax.print.DocPrintJob;
    import javax.print.PrintService;
    import javax.print.PrintServiceLookup;
    import javax.print.ServiceUI;
    import javax.print.SimpleDoc;
    import javax.print.attribute.Attribute;
    import javax.print.attribute.AttributeSet;
    import javax.print.attribute.HashAttributeSet;
    import javax.print.attribute.PrintRequestAttributeSet;
    import javax.print.attribute.HashPrintRequestAttributeSet;
    import javax.print.attribute.PrintServiceAttributeSet;
    import javax.print.attribute.standard.JobName;
    import javax.print.attribute.standard.Sides;
    public class Tst4 {
         public static void main(String[] args) {
              FileInputStream fis = null;
              try {
                   PrintService[] services = PrintServiceLookup.lookupPrintServices(
                         null, null);
                   AttributeSet attributes = new HashPrintRequestAttributeSet();
                   PrintService service =  ServiceUI.printDialog(null, 50, 50,
                                            services, null, null,
                                            (HashPrintRequestAttributeSet)attributes);
                   if (service != null) {
                        fis = new FileInputStream("D:/Temp/coms/test/1.pdf");
                        Doc myDoc = new SimpleDoc(fis, DocFlavor.INPUT_STREAM.AUTOSENSE, null);
                        DocPrintJob job = service.createPrintJob();
                        try {
                             System.out.println("Printing");
                             PrintRequestAttributeSet attr_set = new HashPrintRequestAttributeSet();
                             attr_set.add(new JobName("tst.pdf", null));
                             job.print(myDoc, attr_set);
                        } catch (Exception pe) {
                           pe.printStackTrace();
              } catch(Exception e) {
                   e.printStackTrace();
              } finally {
                   try {
                        fis.close();
                   } catch(Exception ee) {}
    }Here is the code and result with the java.awt.print API:
    Result: the file has been printed correctly, the properties I choose on the printer dialog were well taken. The only problem is the printing seems to be slower.
    import java.awt.print.Book;
    import java.awt.print.PageFormat;
    import java.awt.print.PrinterJob;
    import java.io.File;
    import java.io.FileInputStream;
    import java.nio.ByteBuffer;
    import java.nio.channels.FileChannel;
    import com.sun.pdfview.PDFFile;
    import com.sun.pdfview.PDFPrintPage;
    public class Tst6 {
         public static void main(String[] args) {
              System.out.println("Begin");
              FileInputStream psStream = null;
              try {
                   File f = new File("D:/Temp/coms/test/1.pdf");
                   psStream = new FileInputStream(f);
                   FileChannel fc = psStream.getChannel();
                   ByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size());
                   PDFFile pdfFile = new PDFFile(bb);
                   PDFPrintPage pages = new PDFPrintPage(pdfFile);
                   PrinterJob pj = PrinterJob.getPrinterJob();
                   PageFormat pf = PrinterJob.getPrinterJob().defaultPage();
                   pj.setJobName(f.getName());
                   Book book = new Book();
                   book.append(pages, pf, pdfFile.getNumPages());
                   pj.setPageable(book);
                   if (pj.printDialog()) {
                        System.out.println("Printing");
                        pj.print();
              } catch(Exception e) {
                   e.printStackTrace();
              } finally {
                   try {
                        psStream.close();
                   } catch(Exception se) {}
              System.out.println("End");
    }What can I do to have the same result using both approached (I want to have the result of printing using java.awt libraries but using javax.print API - I want the properties on printer dialog to be taken when using javax.print API)
    Thanks
    Regards.
    Edited by: pjmorce on Feb 18, 2009 1:13 AM
    Edited by: pjmorce on Feb 18, 2009 5:51 AM

  • Any one knows if java print api can drive kitchen or bar printers

    Any one has experience about java on control kitchen or bar printers?
    I am developping a program used by POS. I need to control those printers which located
    in kitchen, cashier places. I want to print order info to kitchen, and print check to customers.
    I am not sure if java print api can easily control those printers.
    any can have experience on it?

    Not an elegant solution, but it works.
    (When I wrote this program I had 3 problems:
    1. I didnt know the java printing system
    2. I can't install the POSprinter under linux and windows
    3. I didnt have time
    so I printed directly to the port)
    boolean isLinux=true;
    File ifile = new File ("/dev/lp0");
    if (!ifile.canWrite()) { // Windows
    ifile = new File ("blokk.txt");
    isLinux=false;}
    try {
    FileWriter fw = new FileWriter(ifile);
    fw.write(".....\r\n");
    fw.write(".....\r\n");
    fw.close();
    } catch (Exception ex) { ex.printStackTrace();}
    if (!isLinux) {
    try {Runtime.getRuntime().exec("blokkprint.bat");}catch (Exception ex) { ex.printStackTrace();}}
    /* blokkprint.bat contains: copy blokk.txt lpt1*/

  • Java Printing API - Unable to print on HP LaserJet

    Hi,
    I'm trying to use Java's printing API to print a PDF file onto a network/local printer.
    My code works fine when I try printing onto Canon printers but the behavior is erratic on HP LaserJet printers.
    I've tried using two different models of HP LaserJet (4050 Series and 1020 Series )
    1. On HP LaserJet 4050 Series PS the print job is processed, but the printer outputs junk/ascii characters instead of the actual pdf
    2. On HP LaserJet 1020 Series the print job reaches the queue but stays there indefinitely with the status message 'Printing'.
    After this the only way to bring the printer back alive is to shut it down and restart it again.
    In both these cases printing from any other application works fine, I run into these issues while using the printing API.
    Here's a code snippet that demonstrates the way my client code is written.
      PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();
      pras.add(new Copies(1));
      pras.add(MediaSizeName.ISO_A4);
      DocFlavor flavor = DocFlavor.INPUT_STREAM.AUTOSENSE; 
      ByteArrayInputStream bytesinputStream =  new ByteArrayInputStream(myPDFfileContent);
      //'printJob' was obtained by iterating over PrintServiceLookup.lookupPrintServices(null, pras);
      DocPrintJob job = printJob.getPrintService().createPrintJob();
      doc = new SimpleDoc(bytesinputStream, flavor, new HashDocAttributeSet());
      job.print(doc, pras);I'm hoping that someone has experienced this issue before and can help me with this..
    Thank you....

    plz try to download the following set of drivers from the link below :::\
    http://gimp-print.sourceforge.net/MacOSX.php3
    This is a new set of default drivers and mayhelp u in resolving the issue.
    Plz do run disk first aid after installing the driver....might suggest even before installaing.
    Thanx !! for trying.

  • Using Java Mail API from Tomcat

    Hello,
    Purely as an academic exercise I have written a JSP page which, upon being requested from the client's browser, should send me a default email using Java Mail Api.
    here is the code :
    import java.util.*;
    import java.io.*;
    import javax.mail.*;
    import javax.mail.internet.*;
    import javax.activation.*;
    public class TestMail {
        static String msgText1 = "success this time 12";
        static String msgText2 = "This is the text in the message attachment.";
        public String sendIt() {
            String to = "<my email";
            String from = "<anything>";
            String host = "<my ip address of smtp server>";
            boolean debug = false;
            Properties props = new Properties();
            props.put("mail.smtp.host", host);
            Session session = Session.getInstance(props, null);
    .....The code works fine as a stand alone app but when called from JSP page it hangs on the Session.getInstance line. I can only guess that this might be a security issue with the container not allowing access to the smtp server ?
    Can anyone give me a clue ???

    Your Tomcat log files should spell out the problem for you.
    My Tomcat installation does not come with the Java Mail API. I had to add the mail and activation jar files to the server/common.lib directory (or the server's shared/lib or the WEB-INF/lib of your application.)
    HTH.

  • How to calculate call duration using java card API

    Hi,
    I am developing an application using Java card API. I want to calculate duration of otgoing calls in it. I am trying to start timer at the beginning of call in Call Control event. Can someone kindly check following code of Call control event? Here timerManagement function is sending proactive command for starting timer for 3 hours. Here I am asuming that maximum call will be of 3 hours. In callDisconnect event i can get current value of timer and use it to calculate duration of call. But this scenario is also not working.
    Problem is that during code execution program stuck at send command (proHdlr.send();) of timmerManagement function. I am sending postAsBERTLV command before starting timer so may be reason is that it is not possible to send proactive command while phone is busy.
    But I also cannot send postAsBERTLV after timerManagement function. Because it is mention in specification that "The EnvelopeResponseHandler content must be posted before the first invocation of a ProactiveHandler.send method or before the termination of the processToolkit, so that the GSM applet can offer these data to the ME (eg 9Fxx/9Exx/91xx). After the first invocation of the ProactiveHandler.send method the EnvelopeResponseHandler is no more available"
    Take a look at following code
                     * Method illustrating the use of the Call Control event.
                    private void callControlService() {
                                    /** @todo: Replace following sample code with your implementation */
                                    ProactiveHandler proHdlr = ProactiveHandler.getTheHandler();
                                    EnvelopeHandler envHdlr = EnvelopeHandler.getTheHandler();
                                    ProactiveResponseHandler rspHdlr = ProactiveResponseHandler
                                                                    .getTheHandler();
                                    EnvelopeResponseHandler envRspHdlr = EnvelopeResponseHandler
                                                                    .getTheHandler();
                                    durationCount = 0;
                                     // allow call with no modifications
                                    envRspHdlr.postAsBERTLV((byte)0x9F, (byte)0x00);
                                    // start clock using timer
                                    timerManagement(proHdlr, rspHdlr, (byte) 0x0, timer_id, tempBuffer);
                                    return;
                    }Please help me in this regard
    Thanks
    Yasir

    I am also unable to start timer in call connected event. I cannot send any proactive command while phone is busy. I am using Gemalto development Suite and there simulators (Simulation 2G chain).
    Is it limitation of simulator that you cannot send any proactive command while phone is busy?
    Is there any other work around for getting call duration?

Maybe you are looking for

  • Error while deleting recipe

    Hi Experts, I am getting the following error "Task list 50000159 01 (type 50000159) is still used in inspection lots" while deleting a master recipe using t code C298. Please note I am note getting any inspection lot where this recipe group is used (

  • JBoss cluster - call to a specific node

    Hi! is it possible to send a remotecall only to a specific node in the cluster? Simple example: I have three nodes in my cluster (A, B, C) and i want to send a call only to an object on node C. Node A and B shouldn't be involved in this call. Best Re

  • Photoshop CS5 missing features???

    OK I downloaded the trial of CS5 and installed it.  The install went fine.  But when I try to open some of my Canon RAW files some strange things I notice. I opened an old Canon 400D RAW file and it opened fine in Adobe camera RAW.  But none of the n

  • Revaluation is being booked to the main GL account

    Hello All.. I have set up two new open item General Ledger accounts and also set up the revaluation accounts in OBA1. But at the month end while doing foreign currency revaluation, the system booked the revaluation to the main account rather than the

  • Will I mess up my configuration on my BlackBerry 8830 if I load the User Tools CD?

    I noticed I could not charge my BlackBerry from the USB and somewhere in the docs read that it would work if you load the User Tools CD.  My question is that my BB has been set up by our IT section, and when I started to run the User Tools CD it aske