Blog - JServlet.com

To content | To menu | To search

Tuesday 24 March 2009

Object PDFDigitalSign, sign and/or certify a PDF with iText

Needs :

Last API iText 2.1.5 :
http://prdownloads.sourceforge.net/itext/iText-2.1.5.jar

Last API Bouncy Castle :
http://www.bouncycastle.org/latest_releases.html

- bcprov-jdk14-138.jar

Use method setKeyStoreType for set specific KeyStore.

Example, sign and/or certify a PDF :

        try
        {
            // instance object PDFDigitalSign... with default keystore!
            PDFDigitalSign digital_sign = new PDFDigitalSign("D:\\keystore2.ks", "xxxx", "D:\\ouput3.pdf", null, "D:\\ouput3_certfied.pdf");
           
            //digital_sign.setKeyStoreType(String _type);
           
            // for visible digital signature
            //digital_sign.setReason("JServlet.com");
            //digital_sign.setLocation("WWW, Planet Earth");
            //digital_sign.setVisible(true);
           
            // certified pdf
            digital_sign.setCertified(true);
           
            // signed pdf if needed
            digital_sign.sign();
           
            System.out.println("done!");
        }
        catch (Exception e)
        {
            System.out.println("Error PDFDigitalSign : " + e);
            e.printStackTrace();
        }
        finally
        {
            System.exit(0);
        }

Source : PDFDigitalSign.java

Wednesday 25 February 2009

Object MultiForm parse a multipart http request

Another parser for multipart http request that handle multipart/form-data request, object MutiForm accept multiple files and parameters in http request, fully compatible rfc1867, rfc2388 and API Servlet 2.4.

Object MultiForm is fast, robust and elegant to use :

- Use getMaxSize() method to set maximum size of http request

- Use getTempDirectory() method to set directory for temporary file

Example in servlet, upload a simple gif image :

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.jservlet.servlet.multiform.MultiForm;
import com.jservlet.servlet.tool.BServlet;

public class UploadImage extends BServlet
{
 
     /**
      * Méthode appelée lorsque la requête est de type ENCTYPE="multipart/form-data" ...
      */
      public void doMultiForm(MultiForm _request, HttpServletResponse _res)
      throws ServletException, IOException
      {
           // do multiform...
          
        PrintWriter out = _res.getWriter();
   
        // errors...
        String err = "Upload OK !!!";
       
        // get data
        String nom = _request.getParameter("nom");
        String prenom = _request.getParameter("prenom");
       
        int age = -1;
        try { age = (new Integer(_request.getParameter("age")).intValue());}
        catch(Exception e) {}
       
        String photo = _request.getParameter("photo");
        photo = (photo==null) ? "" : photo;
   
        // get photo gif ...
        if (!photo.equals("") && _request.isFile("photo"))
        {
            MultiForm.File a_mf = _request.getFile("photo");
           
            // Test file size
            if (!a_mf.getName().equals("") && a_mf.length()>0)
            {
                if (a_mf.length()<=102400) // 1024 x 100 octets
                {
                    if (a_mf.isGif())  // test type file
                    {
                        // save image on disk           
                        try { a_mf.save("/tmp/photo.gif"); }
                        catch(Exception e) { out.println(e.toString()); }
                       
                    } else err = "Image is not Gif format!";
                } else err = "Image is too big! (100 ko max)";
            } else err = "Image is empty!";
        }
      

        //...
        out.write(err);

    }

   /**
    * Méthode pour indiquer quel répertoire utiliser pour les fichiers temporaires...
    */
    public String getTempDirectory() { return "/tmp/"; }

   /**
    * Méthode pour indiquer quelle est la taille maximale que peut avoir une requête.
    */
    public int getMaxSize() { return 5242880; } // 5 Mo maxi!
     
    /**
     * Méthode appelée lorsque la requête est de type Get.
     */
    public void doGet(HttpServletRequest _request, HttpServletResponse _res)
    throws ServletException, IOException
    {
        // do get...
    }
   
    /**
     * Méthode appelée lorsque la requète est de type Post.
     */
    public void doPost(HttpServletRequest _request, HttpServletResponse _res)
    throws ServletException, IOException
    {
        // do post...
    }
} // end of class


In JSP :

<%@ page import="java.util.*, com.jservlet.servlet.multiform.*" language="java"%>
<%

    // test request if appropriate...  
    MultiForm a_mf = null;
    if (MultiForm.isMultiForm(request))
    {
      String a_dir = "c:\\temp\\";     // dir temp...
      int a_maxSize = 5242880;         // max http request size...
     
      if (a_dir!=null) a_mf = (a_maxSize<0) ? new MultiForm(request,a_dir) : new MultiForm(request,a_dir,a_maxSize);    
      else a_mf = (a_maxSize<0) ? new MultiForm(request) : new MultiForm(request,a_maxSize);
    }

    // error ?
    String err = "Upload OK !!!";
       
    String photo = a_mf.getParameter("photo");
    photo = (photo==null) ? "" : photo;

    // get photo gif ...
    if (!photo.equals("") && a_mf.isFile("photo"))
    {
        MultiForm.File a_f = a_mf.getFile("photo");
       
        // Teste file
        if (!a_f.getName().equals("") && a_f.length()>0)
        {
            if (a_f.length()<=102400) // 1024 x 100 octets
            {
                if (a_f.isGif())  // gif format ?
                {
                    // ok save image on disk       
                    try { a_f.save("C:\\temp\\photo.gif"); }
                    catch(Exception e) { out.println(e.toString()); }
                   
                } else err = "Image is not Gif format!";
            } else err = "Image is too big! (100 ko max)";
        } else err = "Image is empty!";
    }
   

    //...
    out.write(err);
%>


Source : MultiForm.java

Thursday 28 February 2008

Boycott Trend Micro - Call for Action!

Boycott Trend Micro - Call for Action!

http://www.scriptumlibre.org/Boycott_Trend_Micro

Boycott_Trend_Micro_French

Barracuda Networks uses ClamAV anti virus software in their solutions. Anti virus developer Trend Micro accused Barracuda Networks of patent infringement with a bogus patent (as all software patents are). What Trend Micro really does is abusing the patent system and aggressively attacking ClamAV users and developers directly.

Whatever your views on software patents in general, or even the validity of this patent, suing customers is in singularly bad taste and can only damage the marketplace.

This is a dangerous act, and we call upon all software vendors and users to boycott Trend Micro and those who support them, to prevent this abusive behaviour becoming a BAD TREND which will be bad for software business worldwide.

Like SCO, Trend Micro has exceeded the boundary of decent and respectable commerce, it has become a pariah and should be punished.


Sunday 27 January 2008

Object SMS - send and receive SMS from GSM card SIM with JAVA Communication API

Send and receive SMS (Short Message Service), read PhoneBook from GSM card SIM, handle communication with Serial Port (RS-232 hardware) with Java Communication Api :

- Send SMS and Receive SMS / encode and decode binary PDU format
- List, read, write and delete SMS in specific memory  (SIM or Phone)
- List, read, write and delete PhoneBook in specific memory (SIM or Phone)

Accept commands 3GPP 27.007 and recommandations 27.005 GSM.

Needs :

Download and install in your classpath Java Comm API  :
http://java.sun.com/products/javacomm/ (Sun decided to not continue on this way...)
or same spec (LGPL license) :
http://www.rxtx.org/
or here :
javaSerial

Install javax.comm.properties file in classpath of your application :

#
# Drivers loaded by the Java Communications API standard extension
# at initialization time
#
# Format:
#    Each line must contain ONE driver definition only
#    Each line must be of the form:
#            driver=<ClassName>
#        No spaces or tabs in the line.
#        ClassName must implement the interface javax.comm.CommDriver
#            example: driver=Win32Serial
#   
#
# The hash(#) character indicates comment till end of line.
#
# Windows Serial Driver
Driver=com.sun.comm.Win32Driver
# end file

Install win32com.dll for Win32 only in your JRE (for me \j2sdk1.4.x_xx\jre\bin\)
See for linux : http://wass.homelinux.net/howtos/Comm_How-To.shtml

Now we can communicate with SIM via the Serial Port of GSM Phone :
- Use virtual Serial Port BlueTooth Device of you GSM, use a Bluetooth Adapter to communicate with your GSM.
(Pairing communication between PC to GSM before use this program...)
- Or use IRDA with virtual COM port : http://www.ircomm2k.de/
- Or use a cable...


Example :

        // Config serial port parameters!
        SerialParameters params = new SerialParameters();
        params.setPortName("COM6"); // default COM1
        params.setBaudRate(115200); // default 115200
        params.setFlowControlIn(SerialPort.FLOWCONTROL_NONE); // default none flowcontrol
        params.setFlowControlOut(SerialPort.FLOWCONTROL_NONE); // default none flowcontrol
        params.setDatabits(SerialPort.DATABITS_8); // default data bits 8
        params.setStopbits(SerialPort.STOPBITS_1); // default stop bits 1
        params.setParity(SerialPort.PARITY_NONE); // default none parity bits 1
        
        // object sms client
        Sms sms = new Sms(params);
        
        // give time for the modem to warm up
        //try { Thread.sleep(5000); }
        //catch(InterruptedException ie){}
        
        System.out.println("Driver loading... " + sms.initializeWinDrivers());
        try
        {
            //lets use a single SerialComm object to initialize everything
            String[] portArray = sms.listPorts();
            System.out.println("Number of ports detected: " + portArray.length);
            for (int i = 0; i < portArray.length; i++)
            {
                System.out.println("OPEN serial Port : " + portArray[i]);
            }
            System.out.println();
        
            // open connection serial port
            sms.openConnection("COM6");//, "1111"); // COM1, optional pin code
            
            // Send a SMS with short message service center (french smsc by example...)
            // Bouygues Telecom         smsc = 33660003000
            // Orange                   smsc = 33689004000
            // SFR                      smsc = 33609001390

            //sms.SendMessage("3361xxxxxxx", "33660003000", "Testing Network connection");
            //sms.SendMessage("xxxxx", "33660003000", "CONTACT"); // call sms+ french service
            
            // store sms on SIM memory! (SM)
            //sms.WriteTextMessage("336xxxxxxxx", "33660003000", "coucou");
            
            // store sms on SIM memory! (ME) (simulated receive sms unread in test!)
            //sms.WriteTextUnReadMessage("336xxxxxxxx", "33660003000", "test1");
            
            // last message status ?
            //if (sms.getPortStatus() == ERROR) System.out.println("----> Error : SMS not SEND !");
            //else if (sms.getPortStatus() == OK) System.out.println("----> Ok : SMS SEND - check folder on SIM!");
            
            // init write memory sms "\"ME\",\"SM\",\"MT\"
            boolean initMemSms =  sms.initializeSmsMemory("\"SM\"");
            System.out.println("Init Sms Memory  : "+initMemSms);
                
            // get size sms storage
            int len_sms = sms.getSizeListSMS();
            System.out.println("Size stored SMS  : "+len_sms);
        
            // start index is 1 !?
            int index_sms = sms.getIndexMemory();
            for(int i=index_sms; i<=len_sms; i++)
            {
                // read sms
                sms.ReadSMS(i);

                // test if last message is a error  
                if (sms.getPortStatusMsg().startsWith("+CMS ERROR")) break;
                    
                // get incoming sms
                IncomingSms in_sms = sms.getRxMS();

                if (in_sms != null)
                {
                    System.out.println("\nSMS received : "+in_sms.toString());
                    //sms.DeleteSMS(i);
                }
                else System.out.println("\nProblem SMS received !!!");
            }
            
            // Get current memory used for book!
            String memoryBook = sms.getPhoneBookMemory();
            System.out.println("PhoneBook memory  : "+memoryBook);
            
            boolean initMemBook =  sms.initializePhoneBookMemory("\"SM\"");
            System.out.println("Init PhoneBook Memory  : "+initMemBook);
            
            int len_book = sms.getSizeListPhoneBook();
            System.out.println("Size stored PhoneBook : "+len_book);
                        
            // get index of current memory
            int index_book = sms.getIndexMemory();
            String book_old = "";
            for(int i=index_book; i<=len_book; i++)
            {
                 // read phone book
                 String book = sms.getPhoneBook(i);
                
                 if (book_old.equals(book)) break; // same response each time!
                else book_old = book;
                
                System.out.println("Phone Book : '"+book+"'");
            }
            
            // index , phone number, type, name
            //sms.WritePhoneBookMessage(8, "0xxxxxxxx", 129, "test one");
            //sms.DeletePhoneBook(8);

        }
        catch (IOException e)
        {
            System.err.println("Communication problem :" + e);
            e.printStackTrace();
        }
        finally
        {
            // close connection to serial port / modem
            try { sms.close(); } catch (NullPointerException ex) {}
        }


Source : Sms.java (see other attachments)

Thursday 3 January 2008

How to use Javamail-Crypto with S/MIME provider

How to use Javamail-Crypto with S/MIME provider :

Needs :

Lasted Api Javamail-Crypto :
http://javamail-crypto.sourceforge.net/

- javamail-crypto_060622.jar
- javamail-crypto-bouncycastle-smime_060622.jar

Install this Jars in Classpath of your application.

There are currently two providers available : one for S/MIME using the BouncyCastle provider,
and one for OpenPGP based on the Cryptix provider.

----

Lasted Api Bouncy Castle (for me Jdk1.4) :
http://www.bouncycastle.org/latest_releases.html

- bcmail-jdk14-138.jar
- bcprov-jdk14-138.jar

Install this Jars in your Classpath of your application.

----

WARNING:

If you have a exception like : java.lang.SecurityException: Unsupported keysize or algorithm parameters,
You need lasted Api Java Cryptography Extension (JCE) with Unlimited Strength Jurisdiction Policy Files (for me Jsdk1.4) :
http://java.sun.com/j2se/1.4.2/download.html (see end of page "Other Downloads")

Due to import control restrictions, the version of JCE policy files that
are bundled in the J2SDK, v 1.4.2 environment allow "strong" but
limited cryptography to be used. This download bundle provides "unlimited strength"
policy files which contain no restrictions on cryptographic strengths.

Install Jars file in jce_policy-1_4_2.zip inside the JRE (for me \j2sdk1.4.x_xx\jre\lib\security), two Jars :
- local_policy.jar
- US_export_policy.jar

----

We need to import (test validity) your certificate .p12 in your JRE :
(here certificate come from "Thawte Personal Freemail Issuing CA")

$>keytool -v -list -keystore personnal.p12 -storetype pkcs12
Enter keystore password:  *******

Keystore type: pkcs12
Keystore provider: SunJSSE

Your keystore contains 1 entry

Alias name: thawte freemail member's thawte consulting (pty) ltd. id
Creation date: 02-Jan-2008
Entry type: keyEntry
Certificate chain length: 3
Certificate[1]:
Owner: EMAILADDRESS=xxx@xxx.fr, CN=Thawte Freemail Member
Issuer: CN=Thawte Personal Freemail Issuing CA, O=Thawte Consulting (Pty) Ltd., C=ZA
Serial number: ce845
Valid from: Sun Aug 22 11:54:25 CEST 2004 until: Mon Aug 22 11:54:25 CEST 2005
Certificate fingerprints:
         MD5:  F0:E6:03:8F:3A:E6:40:26:CE:A8:3D:EE:FB:2E:3F:4D
         SHA1: 04:B4:B4:E1:24:DE:39:14:74:D1:15:45:51:7F:DD:9F:56:05:BE:AE
Certificate[2]:
Owner: CN=Thawte Personal Freemail Issuing CA, O=Thawte Consulting (Pty) Ltd., C=ZA
Issuer: EMAILADDRESS=personal-freemail@thawte.com, CN=Thawte Personal Freemail CA, OU=Certification Services Division, O
=Thawte Consulting, L=Cape Town, ST=Western Cape, C=ZA
Serial number: d
Valid from: Thu Jul 17 02:00:00 CEST 2003 until: Wed Jul 17 01:59:59 CEST 2013
Certificate fingerprints:
         MD5:  7C:B3:90:05:05:EF:D7:BB:DC:BF:30:32:F9:5E:D3:F0
         SHA1: BC:F0:3A:B1:BD:9A:08:9B:EB:46:8D:AF:99:47:5E:83:18:39:99:0F
Certificate[3]:
Owner: EMAILADDRESS=personal-freemail@thawte.com, CN=Thawte Personal Freemail CA, OU=Certification Services Division, O=
Thawte Consulting, L=Cape Town, ST=Western Cape, C=ZA
Issuer: EMAILADDRESS=personal-freemail@thawte.com, CN=Thawte Personal Freemail CA, OU=Certification Services Division, O
=Thawte Consulting, L=Cape Town, ST=Western Cape, C=ZA
Serial number: 0
Valid from: Mon Jan 01 01:00:00 CET 1996 until: Fri Jan 01 00:59:59 CET 2021
Certificate fingerprints:
         MD5:  1E:74:C3:86:3C:0C:35:C5:3E:C2:7F:EF:3C:AA:3C:D9
         SHA1: 20:99:00:B6:3D:95:57:28:14:0C:D1:36:22:D8:C6:87:A4:EB:00:85

----
    
Here simple example of encrypted mail with pk12 public key (see Object Pop3.java & EMail.java) :
    
[...]

import net.suberic.crypto.EncryptionKeyManager;
import net.suberic.crypto.EncryptionManager;
import net.suberic.crypto.EncryptionUtils;

[...]

/**
 * Méthode sendEncryptedMail, envoie un mail simple encrypté par une clé public.
 *
 * @param _from         Adresse de départ
 * @param _to             Adresse du destinataire
 * @param _subject         Sujet du mail
 * @param _msg             Corps du message (simple texte)
 * @param _filepk12     Objet File .p12
 * @param _smimePw         keystore password
 * @param _alias         Nom convivial du certificat (Alias name)
 *
 * @exception            Exception Si une erreur survient.
 */
public void sendEncryptedMail(String _from, String _to, String _subject, String _msg, File _filepk12, String _smimePw, String _alias)
throws Exception
{
    // Get session
    session = Session.getInstance((Properties) getSessionProperties(), null);

    // debug ?
    session.setDebug(debug);

    // Define message
    MimeMessage message = new MimeMessage(session);

    try
    {
        
        StringTokenizer b_stk = new StringTokenizer(_from, ",;");
        while (b_stk.hasMoreTokens())
        {
            message.setFrom(new InternetAddress(b_stk.nextToken()));
            break;
        }

        StringTokenizer a_stk = new StringTokenizer(_to, ",;");
        while (a_stk.hasMoreTokens())
        {
            addToAddress(a_stk.nextToken());
        }
        //message.addRecipient(Message.RecipientType.TO, new InternetAddress(_to));

        for (int i = 0; i < a_destinationTO.size(); i++)
            message.addRecipient(Message.RecipientType.TO, (Address) a_destinationTO.elementAt(i));
        for (int i = 0; i < a_destinationCC.size(); i++)
            message.addRecipient(Message.RecipientType.CC, (Address) a_destinationCC.elementAt(i));
        for (int i = 0; i < a_destinationBCC.size(); i++)
            message.addRecipient(Message.RecipientType.BCC, (Address) a_destinationBCC.elementAt(i));
        if (m_addressReply != null)
            message.setReplyTo(m_addressReply);

        message.addHeaderLine("X-Priority: " + s_priorities[m_Priority]);
        Calendar c = Calendar.getInstance(Locale.FRANCE);
        message.setSentDate(c.getTime());
        message.setSubject(_subject, charset);
        message.setText(_msg, charset);

        message.saveChanges(); // don't forget this
        
        // get the S/MIME EncryptionUtilities
        EncryptionUtils smimeUtils = EncryptionManager.getEncryptionUtils(EncryptionManager.SMIME);
          
        // load the S/MIME keystore from the given file.
        char[] smimePw = new String(_smimePw).toCharArray();
        EncryptionKeyManager smimeKeyMgr = smimeUtils.createKeyManager();
        smimeKeyMgr.loadPublicKeystore(new FileInputStream(_filepk12), smimePw);
        
        // get the S/MIME public key for encryption
        java.security.Key smimeKey = smimeKeyMgr.getPublicKey(_alias);
        
        // encrypt the message
        MimeMessage smimeEncryptedMsg = smimeUtils.encryptMessage(session, message, smimeKey);
        
        if (user != null && pass != null)
        {
            // Send message with authentification!
            Transport tr = session.getTransport("smtp");
            tr.connect(MailHost, user, pass);
            smimeEncryptedMsg.saveChanges(); // don't forget this
            tr.sendMessage(smimeEncryptedMsg, smimeEncryptedMsg.getAllRecipients());
            tr.close();
        }
        else
        {
            // Send message
            Transport.send(smimeEncryptedMsg);
        }
    }
    catch (AddressException ae)
    {
        throw new Exception("EMail.sendEncryptedMail Error : " + ae);
        //System.out.println(ae);
    }
    catch (MessagingException me)
    {
        throw new Exception("EMail.sendEncryptedMail Error : " + me);
        //System.out.println(me);
    }
}

----

Here simple example for decrypt mail with pk12 private key :

/**
* Méthode ReadEncryptedMessage, récupère un S/MIME Encrypted Message
*
* @param pop_message         Objet MimeMessage à décoder...
* @param _filepk12             Objet File .p12
* @param _smimePw             keystore password
* @param _alias                 Nom convivial du certificat (Alias name)
* @return MimeMessage        Retourne un MimeMessage décrypté
*/
public static MimeMessage ReadEncryptedMessage(MimeMessage pop_message, File _filepk12, String _smimePw, String _alias)
throws Exception
{
    String cryptotype = EncryptionManager.checkEncryptionType(pop_message);
    EncryptionUtils cryptoUtils = EncryptionManager.getEncryptionUtils(cryptotype);
    
    EncryptionKeyManager keyMgr = cryptoUtils.createKeyManager();
    char[] smimePw = new String(_smimePw).toCharArray();
        
    keyMgr.loadPrivateKeystore(new FileInputStream(_filepk12), smimePw);
    
    MimeMessage decryptedMsg = null;
      
    Key privateKey = keyMgr.getPrivateKey(_alias, smimePw);
    try
    {
        decryptedMsg = cryptoUtils.decryptMessage(null, pop_message, privateKey);
    }
    catch (Exception e)
    {
        Object o = pop_message.getContent();
        System.err.println("msg.getContent() = " + o + ", a " + o.getClass().getName());
        System.err.println("error decrypting message with key " + privateKey + ":  " + e);
        e.printStackTrace();
    }

    return decryptedMsg;
}

----

Here simple example for signed mail with pk12 private key :

/**
 * Méthode sendSignedMail, envoie un mail simple signé par une clé privée.
 *
 * @param _from         Adresse de départ
 * @param _to             Adresse du destinataire
 * @param _subject         Sujet du mail
 * @param _msg             Corps du message (simple texte)
 * @param _filepk12     Objet File .p12
 * @param _smimePw         keystore password
 * @param _alias         Nom convivial du certificat (Alias name)
 * @exception            Exception Si une erreur survient.
 */
public void sendSignedMail(String _from, String _to, String _subject, String _msg, File _filepk12, String _smimePw, String _alias)
throws Exception
{
    // Get session
    session = Session.getInstance((Properties) getSessionProperties(), null);

    // debug ?
    session.setDebug(debug);

    // Define message
    MimeMessage message = new MimeMessage(session);

    try
    {
        
        StringTokenizer b_stk = new StringTokenizer(_from, ",;");
        while (b_stk.hasMoreTokens())
        {
            message.setFrom(new InternetAddress(b_stk.nextToken()));
            break;
        }

        StringTokenizer a_stk = new StringTokenizer(_to, ",;");
        while (a_stk.hasMoreTokens())
        {
            addToAddress(a_stk.nextToken());
        }
        //message.addRecipient(Message.RecipientType.TO, new InternetAddress(_to));

        for (int i = 0; i < a_destinationTO.size(); i++)
            message.addRecipient(Message.RecipientType.TO, (Address) a_destinationTO.elementAt(i));
        for (int i = 0; i < a_destinationCC.size(); i++)
            message.addRecipient(Message.RecipientType.CC, (Address) a_destinationCC.elementAt(i));
        for (int i = 0; i < a_destinationBCC.size(); i++)
            message.addRecipient(Message.RecipientType.BCC, (Address) a_destinationBCC.elementAt(i));
        if (m_addressReply != null)
            message.setReplyTo(m_addressReply);

        message.addHeaderLine("X-Priority: " + s_priorities[m_Priority]);
        Calendar c = Calendar.getInstance(Locale.FRANCE);
        message.setSentDate(c.getTime());
        message.setSubject(_subject, charset);
        message.setText(_msg, charset);

        message.saveChanges(); // don't forget this
        
        // get the S/MIME EncryptionUtilities
        EncryptionUtils smimeUtils = EncryptionManager.getEncryptionUtils(EncryptionManager.SMIME);
          
        // load the S/MIME keystore from the given file.
        char[] smimePw = new String(_smimePw).toCharArray();
        EncryptionKeyManager smimeKeyMgr = smimeUtils.createKeyManager();
        smimeKeyMgr.loadPrivateKeystore(new FileInputStream(_filepk12), smimePw);
        
        // get our keys.
        java.security.Key smimeKey = smimeKeyMgr.getPrivateKey(_alias, smimePw);
        
        // write smime message.
        MimeMessage smimeSignedMsg = smimeUtils.signMessage(session, message, smimeKey);
       
        if (user != null && pass != null)
        {
            // Send message with authentification!
            Transport tr = session.getTransport("smtp");
            tr.connect(MailHost, user, pass);
            smimeSignedMsg.saveChanges(); // don't forget this
            tr.sendMessage(smimeSignedMsg, smimeSignedMsg.getAllRecipients());
            tr.close();
        }
        else
        {
            // Send message
            Transport.send(smimeSignedMsg);
        }
    }
    catch (AddressException ae)
    {
        throw new Exception("EMail.sendSignedMail Error : " + ae);
        //System.out.println(ae);
    }
    catch (MessagingException me)
    {
        throw new Exception("EMail.sendSignedMail Error : " + me);
        //System.out.println(me);
    }
}


----

Here simple example for check signed mail with pk12 public key :

/**
* Méthode CheckSignedMessage, check un S/MIME Signed Message
*
* @param pop_message         Objet MimeMessage a décodé...
* @param _filepk12             Objet File .p12
* @param _smimePw             keystore password
* @param _alias                 Nom convivial du certificat (Alias name)
* @return boolean            Retourne true si la signature est ok!
* @exception                    Si par exemple le certificat n'est plus valide...
*/
public static boolean CheckSignedMessage(MimeMessage pop_message, File _filepk12, String _smimePw, String _alias)
throws Exception
{
    String cryptotype = EncryptionManager.checkEncryptionType(pop_message);
    EncryptionUtils cryptoUtils = EncryptionManager.getEncryptionUtils(cryptotype);
      
    EncryptionKeyManager keyMgr = cryptoUtils.createKeyManager();
    char[] smimePw = new String(_smimePw).toCharArray();
        
    keyMgr.loadPublicKeystore(new FileInputStream(_filepk12), smimePw);
    
    // good or not ?
    boolean goodSignature = false;
    
    Key publicKey = keyMgr.getPublicKey(_alias);
    cryptoUtils.checkSignature(pop_message, publicKey);
    
    try
    {
        goodSignature = cryptoUtils.checkSignature(pop_message, publicKey);
    }
    catch (Exception e)
    {
        Object o = pop_message.getContent();
        System.err.println("msg.getContent() = " + o + ", a " + o.getClass().getName());
        System.err.println("error decrypting message with key " + publicKey + ":  " + e);
        e.printStackTrace();
    }
    
    return goodSignature;
}

          
(Mmmh... Strange world, we need to hash code for feel free!)

Sunday 14 October 2007

Mapping session servlet

Mapping & tracking session servlet :



Create abstract servlet BServletSession, all your servlet need to extend BServletSession for mapping specific component servlet session :

package com.jservlet.servlet.monitor;
[...]
public abstract class BServletSession extends HttpServlet
{

   /**
    * Override
method service for monitored object Session of specific User
    *
    * @exception ServletException  If a exception
    * @exception IOException       If a I/O exception
    */
    protected void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
    {
        // session
        HttpSession session = req.getSession();

        if (session !=null)
        {
            String ip_client = session.getAttribute("USER") + "@" + req.getRemoteHost() + " (" + req.getRemoteAddr() + ")";
            session.setAttribute("CLIENT_IDENTIFICATION", ip_client);

            // object singleton monitor session...
            MonitorSession.getInstance().monitorSession((String) session.getId(), session);

        }
      
        // call super service
        super.service(req, res);
    }
} //  end BServletSession...

Now you can see all objects in session (complet ip client come from User identification client, extends this servlet...), make introspection of specific object in session of servlet engine is now easy. See servlet monitor session and object monitor session for more details :

ServletMonitorSession.java
MonitorSession.java


Sunday 23 September 2007

Glue Java web engine servlet

Glue servlet engine, what is a glue web ?

Glue is a master servlet front end service that glue in parallel all resources coming from server group in cluster architecture.

Glue allow you to make fast and easily dynamic web site (in jsp/servlet, php, cgi or all that can be call by url), cobranding existing web application, make a bridge to web application or create simply your web portal, all that with the robustness of cluster architecture.

Glue accept http or https, interaction with Html form and cookie.

Use external Api HTTPClient Version 0.3-3 under LGPL V2.1
http://www.innovation.ch/java/HTTPClient/

See cluster architecture with Glue :

Call easily a component servlet engine in JSP :


<%@ page language="java" session="false" autoFlush="false" buffer="96kb" contentType="text/html;charset=iso-8859-1"%>
<%@ page extends="com.jservlet.servlet.JspUtils"%>
<%-- call internal method in jsp... --%>
<%@ include file="portefeuille_m.jsp" %>

<%-- Bean porperties, config client --%>
<jsp:useBean id="client_URL_PAGES" class="java.util.Properties" scope="application" />

<%
    // prepare to call component URL
    getCompPortefeuille(request, response, out, client_URL_PAGES, true, false);
%>

<div id="service">
    <script src="js/ptf.js"></script>
    <%=getCompPortefeuille(request, response, out, client_URL_PAGES, false, false)%>
</div>


Call method to servlet engine component URL (include jsp) :


<%@ page import="java.util.*"%>
<%@ page import="com.jservlet.stream.server.ComponentCallAsync" %>

<%!

    // Method getCompPortefeuille
    private String getCompPortefeuille(HttpServletRequest request, HttpServletResponse response, JspWriter out, Properties property, boolean bCallOnly, boolean bDebug)
    {
        // uri
        String urlAction = "?pageid=portefeuille";
       
        // url call ?
        String urlcall = (String) request.getParameter("urlcall");
        urlcall = (urlcall == null) ? "" : urlcall;
       
        String url            = property.getProperty("jportefeuille_client");           
        String urlServeur     = property.getProperty("jportefeuille");
       

        // hash others parameters
        Hashtable hash_param = getParametresStandard(request);
        hash_param.put("urlAction", urlAction);
        hash_param.put("urlcall", urlcall);
       
        // build final url
        String call_service = buildUrl(url, urlServeur, urlAction, hash_param);
       
        System.out.println("call_service : "+call_service);
        System.out.println("parametres : "+getParametresStandard(request));
              
        // objet call component           
        ComponentCallAsync comp = new ComponentCallAsync( call_service, "", request, response, out , false, false, true );
       
        // debug mode ?
        try { comp.setDebug(bDebug); }
        catch (Exception e) { }
       
        // get html
        if (!bCallOnly) return comp.getHTML();
        else return "";
    }
   
%>


Build easily web information system in JSP (master.jsp, menu.jsp, header.jsp, footer.jsp)  :


<%@ page language="java" %>
<%@ page session="false"%>
<%@ page import="java.util.*"%>
<%@ page autoFlush ="false" %>
<%@ page buffer = "96kb" %>

<%
    // détermine le type de sortie.
    response.setContentType("text/html;charset=iso-8859-1");

    // option pas de cache !
    response.setHeader("Pragma", "no-cache");
    response.setHeader("Cache-Control", "no-cache");
    response.setDateHeader("Expires", 0);
   
    // page jsp appelée
    String jspPage = (String) request.getAttribute("jspPage");
    jspPage = (jspPage == null) ? "main" : jspPage;
   
%>

<html>
<head>
    <title>My web portal</title>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
    <link rel="stylesheet" href="styles/client.css" type="text/css">
</head>

<body>

<table width="100%" border="1">
  <tr>
    <td colspan="2"><jsp:include page="header.jsp" /></td>
  </tr>
  <tr>
    <td width="10%" valign="top">
        <jsp:include page="menu.jsp" flush="false">
              <jsp:param name="jspPage" value="<%=jspPage%>"/>
        </jsp:include>
    </td>
    <td width="90%">
        <jsp:include page="<%= jspPage+".jsp" %>" flush="false">
            <jsp:param name="jspPage" value="<%=jspPage%>"/>
        </jsp:include>
    </td>
  </tr>
  <tr>
    <td colspan="2"><jsp:include page="footer.jsp" /></td>
  </tr>
</table>

</body>
</html>

Config client :

#
# Fichier global de description de la configuration du client
#

http_root=http://client.jservlet.com/

# url java & graph
java_url=http://blaster.jservlet.grp:83/
graph_url=http://blaster.jservlet.grp:84/

# local service
java_root=http://localhost:83/
graph_root=http://localhost:84/

# nom du client
service_client=client

# url portefeuille
jportefeuille=http://blaster.jservlet.grp:83/portefeuille
jportefeuille_client=http://blaster.jservlet.grp:83/portefeuille/PortefeuilleClient


Interested by my java Glue write me a comment...


Tuesday 3 July 2007

Object HTMLForm - method post and get URL


Object HTMLForm, accept method post and get URL :
    - Map of parameters
    - Past ACL (Access Control List)
    - Get Cookie

Use external API JCookie :
http://jcookie.sourceforge.net/

Example :

        HTMLForm form = null;
   
        HashMap map = new HashMap();
   
        String url = "https://altern.org/";
              
        // url & method
        map.put("url", url);
        map.put("method", "get");
   
        // ACL conf
        //map.put("user", "user");
        //map.put("password", "password");
       
        // others parameters..
        //map.put("what", "hi!");
       
        try
        {
            form = new HTMLForm(false); // cookie ?
   
            form.setFollowRedirects(true); // redirect ?
            form.setKeepAlive(true);
           
            System.err.println("check : "+HTMLForm.checkURL(map));
            form.setParametersMap(map);
   
            BufferedReader in = new BufferedReader(new InputStreamReader(form.sendFormMessage()));
            System.out.println("HTMLForm : invoking URL "+ url);
   
            StringBuffer page = new StringBuffer();
            String line = null;
            
            while((line = in.readLine()) != null) page.append(line).append("\n");
           
            System.err.println(page.toString());
            System.err.println(">End of line");
           
            CookieJar cookies = form.getCookieJar();
           
            if (cookies != null)
            {
                 System.out.println("cookie size : "+ cookies.size());
               
                Iterator iter = cookies.iterator();
                while(iter.hasNext())
                {
                    Object cookie = iter.next();
                    System.out.println("cookie : "+ cookie);
                }
            }
        }
        catch (Exception e)
        {
            System.out.println(e);
            System.out.println("Pile : ");
            e.printStackTrace();
        }
        finally
        {
            if (form!=null) form.disconnect();
        }

Source : HTMLForm.java
               


Monday 2 July 2007

Object FTP - download and upload file


Object FTP, download and upload file under FTP protocol, accept passive or active mode, SSL communication in test (java 1.5 ssl class)

Compatible with some FTP server  Unix, Windows, JScape server...

UFS format only (Unix File System).

Many people do not make the difference between FTP, FTPS and SFTP, here:
    - FTP  : transfert FTP with basic socket
    - FTPS : transfert FTP with SSL certificat
    - SFTP : transfert with SSH (use command SCP can transfert file like FTP)

Socks proxy parameters :
java -DsocksProxyPort=1080 -DsocksProxyHost=socks.foo.com -Djava.net.socks.username=user01 -Djava.net.socks.password=pass1234 ...

Command FTP allowed :
 ABOR ACCT ALLO CDUP CWD DELE HELP LIST MDTM MKD
 MODE NOOP PASS PASV PORT PWD QUIT REIN REST RETR
 RMD RNFR RNTO SITE SIZE SMNT STAT STOR STRU SYST
 TYPE USER FEAT
 
Command none implemented (not use):
APPE NLST STOU

Port used :
Port 21  --> FTP command port
Port 20 data port
Port 990  --> FTPS command port over TLS/SSL
Port 989 data port

Example :

    FTP m_client = null;
   
    try
    {
        m_client = new FTP("192.168.1.66", 21, System.out); // ftps in test 990
        m_client.setSocketTimeout(5000);                    // set timeout 5s
       
        m_client.setNetworkInterface("eth0");                     // defaut eth0
        m_client.setPassivMode(true);                         // defaut true
        //m_client.setSecureFTP(true);                         // defaut false
       
        // on démarre la session vers le serveur FTP
        m_client.session("test", "test");                
       
        //m_client.mode('S');                            // mode de transfert defaut 'S'
        //m_client.stru('F');                            // structure des fichiers defaut 'F'
       
        System.err.println("*** "+m_client.getWelcome());
        //m_client.cwd("/upload");                        // change dir
       
        // nom du répertoire courant
        System.err.println("---> "+m_client.pwd());
       
        //m_client.help();
        //m_client.system();
        //m_client.stat();
        //m_client.features();
       
        // liste les fichiers dans le répertoire courant ou nommé list("/upload");
        FtpFile a_fl[] = m_client.list();
        for (int i=0; i<a_fl.length; i++)
            System.err.println(((a_fl[i].isFile())? a_fl[i].getName()+" "+(a_fl[i].i_size+" ") : "<"+a_fl[i].getName()+">"));
           
   
        /*
        // début du test   
        try { m_client.dele("testx.pdf"); }
        catch (Exception dele) { }
       
        System.err.println("*** allocate 6000 bytes : "+m_client.allo(6000));

        // ATTENTION taille originale du fichier testx.pdf : 3434 bytes
        m_client.upLoad("D:\\temp\\testx.pdf");
        //m_client.upLoad("D:\\temp\\testx.pdf", 2456);
       
        System.err.println("date modif : "+m_client.modtime("testx.pdf"));
        System.err.println("size : "+m_client.size("testx.pdf"));
       
        m_client.downLoad("testx.pdf", "c:\\temp\\testx.pdf");
        //m_client.downLoad("testx.pdf", "c:\\temp\\testx.pdf", new File("c:\\temp\\testx.pdf").length());
        //m_client.downLoad("testx.pdf", "c:\\temp\\testx.pdf", 2456);
       
        // création répertoire test
        m_client.mkd("test");
        m_client.cwd("/upload/test");   
       
        m_client.upLoad("d:\\temp\\testx.pdf");
       
        // liste des fichiers dans test
        FtpFile b_fl[] = m_client.list();
        for (int i=0; i<b_fl.length; i++)
            System.err.println(((b_fl[i].isFile())? b_fl[i].getName()+" "+b_fl[i].i_size : "<"+b_fl[i].getName()+">"));
       
        // effacement du fichier testx.pdf et répertoire test ...
        m_client.dele("testx.pdf");
        m_client.cwd("/upload");
        //m_client.toParentDir();
        System.err.println("---> "+m_client.pwd());
        m_client.rmd("test");
        */
    }
    catch (Exception e)
    {
        System.err.println("FTP error : "+ e.toString());
        e.printStackTrace();
    }
    finally
    {
        // ferme la connexion au serveur FTP
        m_client.close();
       
        // exit
        System.exit(0);
    }


Source : FTP.java


Sunday 1 July 2007

Object Pop3 - receive mail message with JavaMail API


Object Pop3, receive mail message with JavaMail API, accept protocol POP3, IMAP over SSL.

Sun JavaMail API 1.4 (under GPL v2) : http://java.sun.com/products/javamail/ 
 - mail.jar 1.4 (pop3.jar, smtp.jar, imap.jar, mailapi.jar, dsn.jar)
JAF :  http://java.sun.com/javase/technologies/desktop/javabeans/jaf/index.jsp 
- activation.jar

Some inner class in Pop3 object :

Pop3.Tools : class with useful's methods to parse multipart message 
    - get body / body in html
    - save File
    - File Handle Multipart
    - etc ...

Pop3.FileBinary : class with useful's methods to find extension of file attachment in message
    - file zip, pdf, images...
    - and file like Microsoft Office... word, excel!

SSL explain and example :
We need to put SSL certificat in key store manager inside JRE...

Well see URL : https://altern.org/ with your browser.
And export SSL certificate of site web in file ex : altern.cer

Now import SSL certificate in key store manager :
go in path \j2sdk1.4.x_xx\jre\lib\security\
and use keytool with some options :
$> keytool -import -keystore cacerts -file altern.cer

The password by default of global key store manager is : 'changeit'

Now we can communicate with the domain in POP or SMTP over SSL...

Example :

    //Pop3 pop = new Pop3("c:\\temp", "pop.xxx.fr", "xxxx", "xxxx"); // default pop3!
    Pop3 pop = new Pop3("c:\\temp", "xxxx.org", "xxxx", "xxxx", POPS_PORT, POP);

    pop.setSecurePOP3(true);
    pop.setDebug(true);
    pop.setSocketTimeout(5000);

    try
    {
      System.err.println("Start Job --- Pop3");

      // read eml file (txt)
      /*
      MimeMessage mime_mess = Pop3.Tools.getMimeMessage("c:\\temp\\002b01c7xxxa36c95f0$bb64668a@unixxxip85.eml");

      System.out.println("\tFrom : " + mime_mess.getFrom()[0]);
      System.out.println("\tSubject : " + mime_mess.getSubject());
      System.out.println("\tDate : " + mime_mess.getSentDate());
      Address[] address = mime_mess.getReplyTo();
      System.out.println("\tReplyTo : " + MimeUtility.decodeText(address[0].toString()));

      Vector vec_file_mess = Pop3.Tools.getFile(mime_mess);
      if (!vec_file_mess.isEmpty())
      {
        for (int j=0; j<vec_file_mess.size(); j++)
        {
          String a_file = (String) vec_file_mess.elementAt(j);

          // copier les fichiers hors du dossier temporaire!!!
          System.out.println("\tPathFileName : " + a_file);
        }
      }
      else System.out.println("\tPas de fichier en attachement!");

      // le body
      try
      {
          String body = Pop3.Tools.getBody(mime_mess);
          System.out.println("\n\tBody : " + body);
      }
      catch(Exception e) { System.out.println("\n\tBody : " + e); }

      // body html pour les mail au format html uniquement...
      try
      {
          String bodyhtml = Pop3.Tools.getBodyHtml(mime_mess);
          System.out.println("\n\tBodyHtml: " + bodyhtml);
      }
      catch(Exception e) { System.out.println("\n\tBodyHtml : " + e); }
     */
      // fin lecture d'un fichier eml (texte)

      // POP3 mode : INBOX par defaut
      // IMAP4 mode : INBOX par defaut, dispo normalement : Drafts, Sent, Trash
      Message[] pop_message = pop.getMail(true); //  dossier courant "INBOX", true debug

      /*
      // IMAP4 liste tous les dossiers du folder courant
      //UIDFolder ufolder = (UIDFolder) pop.getFolder();
      //System.err.println("MESSAGE UID :" + ufolder.getUID(pop_message[i]));

      Folder[] xfolders = pop.getRootFolders();
      if (xfolders ==null || xfolders.length == 0) System.err.println("***  IMAP Root Folder : ?? ");
      else
      {
          System.err.println("**** IMAP Root Folder : ");
          for (int i=0, n=xfolders.length; i<n; i++)
              System.err.println("\tFolder : -"+i+" "+xfolders[i].getName());
      }

      // dossier courant
      xfolders = pop.getFolders();
      if (xfolders ==null || xfolders.length == 0) System.err.println("***  NO Folder in current folder!");
      else
      {
          System.err.println("**** Folder : ");
          for (int i=0, n=xfolders.length; i<n; i++)
              System.err.println("\tFolder : -"+i+" "+xfolders[i].getName());
      }

      // change de dossier...
      //pop_message = pop.getMail("Test"+pop.getSep()+"SubTest", true); //  dossier courant "INBOX", true debug
      pop_message = pop.getMail("Test", true); //  dossier courant "INBOX", true debug

      xfolders = pop.getRootFolders();
      if (xfolders ==null || xfolders.length == 0) System.err.println("***  IMAP Root Folder : ?? ");
      else
      {
          System.err.println("**** IMAP Root Folder : ");
          for (int i=0, n=xfolders.length; i<n; i++)
              System.err.println("\tFolder : -"+i+" "+xfolders[i].getName());
      }

      // dossier courant
      xfolders = pop.getFolders();
      if (xfolders ==null || xfolders.length == 0) System.err.println("***  NO Folder in current folder!");
      else
      {
          System.err.println("**** Folder : ");
          for (int i=0, n=xfolders.length; i<n; i++)
              System.err.println("\tFolder : -"+i+" "+xfolders[i].getName());
      }

      Folder[] subcr_folder = pop.getSubscribedFolder();
      if (subcr_folder == null || subcr_folder.length == 0) System.err.println("*** NO Folder Subcribe in current folder!");
      else
      {
          for (int i=0, n=subcr_folder.length; i<n; i++)
              System.err.println("************ Folder Subcribe : -"+i+" "+xfolders[i].getName());
      }

      Folder[] unsubcr_folder = pop.getUnSubscribedFolder();
      if (unsubcr_folder == null || unsubcr_folder.length == 0) System.err.println("*** NO Folder UnSubcribe in current folder!");
      else
      {
          for (int i=0, n=unsubcr_folder.length; i<n; i++)
              System.err.println("************ Folder UnSubcribe : -"+i+" "+xfolders[i].getName());
      }
      */

      // IMAP4 création, copie & destruction (PERMANENT) de dossier
      /*
      System.out.println("*** DELETE FOLDER : "+ pop.deleteFolder("Test"));
      System.out.println("*** CREATE FOLDER : "+ pop.createFolder("Test"));
      System.out.println("*** COPY FOLDER : "+ pop.copyFolderMessages("Trash", "Test"));
      */

      //System.out.println("*** SUBCRIBE/UNSUBCRIBE FOLDER : "+ pop.setSubscribed("Test", false));
      //System.out.println("*** RENAME FOLDER : "+  pop.renameFolder("Test", "Testy"));
      //System.out.println("*** DELETE FOLDER : "+ pop.deleteFolder("Testy"));
      //System.out.println("*** COPY FOLDER : "+ pop.copyFolderMessages("Test", "SubTest"));

      // IMAP4 liste tous les dossiers de Test
      //pop_message = pop.getMail("Test", true); // on change de dossier courant pour root
      //System.out.println("*** CREATE FOLDER : "+ pop.createFolder("Test.SubTest"));
      //System.out.println("*** SUBCRIBE/UNSUBCRIBE FOLDER : "+ pop.setSubscribed("Test.SubTest", true));
      //System.out.println("*** DELETE FOLDER : "+ pop.deleteFolder("Test.SubTest"));


      for (int i=0, n=pop_message.length; i<n; i++)
      {
        //pop_message[i].writeTo(System.out);

          System.err.println("\tFrom : " + pop_message[i].getFrom()[0]);
        System.err.println("\tSubject : " + pop_message[i].getSubject());
        System.err.println("\tDate : " + pop_message[i].getSentDate());
        Address[] add = pop_message[i].getReplyTo();
        System.err.println("\tReplyTo : " + add[0].toString());
        /*
        MimeMessage mess = (MimeMessage) pop_message[i];

        String[] strTo = mess.getHeader("To");
        if (strTo !=null) // ?
          for (int j=0, m=strTo.length; j<m; j++)
            System.out.println("\tTo : " + strTo[j]);

        String[] strReceived = mess.getHeader("Received");
        if (strReceived !=null) // impossible
          for (int j=0, m=strReceived.length; j<m; j++)
            System.out.println("\tReceived : " + strReceived[j]);

        System.out.println("\tMessage-ID : " + mess.getMessageID());


        //Enumeration e = mess.getAllHeaders();
        //while (e.hasMoreElements())
        //{
        //        Header header = (Header) e.nextElement();
        //        System.out.println(header.getName() +" : "+header.getValue());
        //}


        // le body
        try
        {
            String body = Pop3.Tools.getBody(pop_message[i]);
            System.out.println("\n\tBody : " + body);
        }
        catch(Exception e) { System.out.println("\n\tBody : " + e); }


        // body html pour les mail au format html uniquement...
        try
        {
            String bodyhtml = Pop3.Tools.getBodyHtml(pop_message[i]);
            System.out.println("\n\tBodyHtml: " + bodyhtml);
        }
        catch(Exception e) { System.out.println("\n\tBodyHtml : " + e); }

        // les fichiers en attachement..
        Vector vec_file = Pop3.Tools.getFile(pop_message[i]);
        if (!vec_file.isEmpty())
        {
          for (int j=0; j<vec_file.size(); j++)
          {
            String a_file = (String) vec_file.elementAt(j);

            // copier les fichiers hors du dossier temporaire!!!
            System.out.println("\tPathFileName : " + a_file);

            Pop3.FileBinary fb = new Pop3.FileBinary(a_file);
            System.out.println("\t isPdf : " + fb.isPdf());
             System.out.println("\t isMSOffice : " + fb.isMSOffice());

          }
        }
        else System.out.println("\tPas de fichier en attachement!");

        // les fichiers embarqués (dans l'html ou autre...)
        Vector vec_file_embed = Pop3.Tools.getFileEmbed(pop_message[i], "image/jpeg");
        if (!vec_file_embed.isEmpty())
        {
          for (int j=0; j<vec_file_embed.size(); j++)
          {
            String a_file = (String) vec_file_embed.elementAt(j);
            // copier les fichiers hors du dossier temporaire!!!
            System.out.println("\tPathFileName Embed: " + a_file);
          }
        }
        else System.out.println("\tPas de fichier embarqué!");

        System.out.println();

        // lecture des Flags IMAP4
        System.out.println("Count read : "+pop.countMessageRead());
        System.out.println("isNew : "+pop.isNew(i));
        System.out.println("isRead : "+pop.isRead(i));

        // sauve le message dans un répertoire dédié...
        //Pop3.Tools.saveELM(mess, new File("c:\\temp"));

        System.out.println("isConnected : " + pop.store.isConnected()); // Noop

        // on se prepare à effacer les mails!
        //pop_message[i].setFlag(Flags.Flag.DELETED, false); // true
        */

        System.out.println();
        System.out.println();

      }

      System.out.println("End Job --- Pop3");
    }
    catch(Exception e)
    {
      System.out.println(e);
      System.out.println("Pile : ");
      e.printStackTrace();
    }
    finally
    {
      // ferme la session pop3 et efface les messages flagger 'DELETED' !
      try { pop.close(true); } catch (MessagingException me) { }
    }
  }

Source : Pop3.java


- page 1 of 2