Generating Attachments At Runtime/Add IO Streams in Java Mail

I’ve recently come across a requirement where i had to create some reports at runtime while sending the mail in Java. I expect Every One to have prior knowledge of how to send a mail in java else you go through my previous post

Lets take an example where we have set of encrypted reports in a directory so that none who is having access to system be able to open the report. And We want to decrypt an encrypted report while sending a mail ( As our system is authorized/ or knows the process of decrypting it).

Here is how we perform such an operation using Java Mail.

Java Mail Uses Activation Framework which Contains a Class called  javax.activation.FileDataSource.

All we need to do is to Extend this class and Override its getInputStream() Method. Here is How it is done

    /*
     * (non-Javadoc)
     * 
     * @see javax.activation.FileDataSource#getInputStream()
     */
    public InputStream getInputStream() throws IOException {
        File fileInvoice = new File(strInvoice);
        if (!fileInvoice.exists()) {
            try {
                throw new Exception("File " + encryptedFileName
                        + " does not exist");
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        // Output file
        OutputStream os = null;
        byte[] bytes = null;

        try {
            os = new ByteArrayOutputStream();
            RSACryptographer rsaCryptoGrapher = new RSACryptographer();
            bytes = rsaCryptoGrapher.crypt(fileInvoice, Cipher.DECRYPT_MODE);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new ByteArrayInputStream(bytes);
    }

The above code snippet give you an overview of how to create/modify some document at runtime while sending mail from java. Now here is how we attach this DataSource To Message

messageBodyPart = new MimeBodyPart();
DataSource source = new EncryptedDocumentDataSource(directoryName,encryptedFileName);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(encrypted);
multipart.addBodyPart(messageBodyPart);

Advertisements

Sending Mail In Java

Many people find it difficult sending mail from a program. This code shows how simple it is to send a mail from java Program.

package com.webaging.utils;

import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

/**
* @author Ashwin
*
*/
public class MailClient {

public void sendMail(String mailServer, String from, String to,
String subject, String messageBody, String[] attachments)
throws MessagingException, AddressException {
// Setup mail server
Properties props = System.getProperties();
props.put(“mail.smtp.host”, mailServer);

// Get a mail session
Session session = Session.getDefaultInstance(props, null);

// Define a new mail message
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
message.setSubject(subject);

// Create a message part to represent the body text
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setText(messageBody);

// use a MimeMultipart as we need to handle the file attachments
Multipart multipart = new MimeMultipart();

// add the message body to the mime message
multipart.addBodyPart(messageBodyPart);

// add any file attachments to the message
addAtachments(attachments, multipart);

// Put all message parts in the message
message.setContent(multipart);

// Send the message
Transport.send(message);

}

protected void addAtachments(String[] attachments, Multipart multipart)
throws MessagingException, AddressException {
for (int i = 0; i <= attachments.length – 1; i++) {
String filename = attachments[i];
MimeBodyPart attachmentBodyPart = new MimeBodyPart();

// use a JAF FileDataSource as it does MIME type detection
DataSource source = new FileDataSource(filename);
attachmentBodyPart.setDataHandler(new DataHandler(source));

// assume that the filename you want to send is the same as the
// actual file name – could alter this to remove the file path
attachmentBodyPart.setFileName(filename);

// add the attachment
multipart.addBodyPart(attachmentBodyPart);
}
}

public static void main(String[] args) {
try {
MailClient client = new MailClient();
String server = “pop3.mydomain.com”;
String from = “myname@mydomain.com”;
String to = “someuser@somewhere.com”;
String subject = “Test”;
String message = “Testing”;
String[] filenames = { “c:\\somefile.txt” };

client.sendMail(server, from, to, subject, message, filenames);
} catch (Exception e) {
e.printStackTrace(System.out);
}

}
}

Courtesy: http://www.osix.net/modules/article/?id=39

Apache POI And HyperLinks

I recently came across a requirement where i had to add hyperlink in excel Generated By Apache POI in Java. I have gone through the API and Found out that there is no API which Supports this and there is also no cell type which define something like this HSSFCell.CELL_TYPE_HYPERLINK.  I tried a lot and Finally Found a hack for this. To our rescue came the Office which has a function called HYPERLINK. I made my life easy and Immediately i had set Formula for that Column.

Here is the snippet for adding HyperLink

cell.setCellType(HSSFCell.CELL_TYPE_FORMULA);
cell.setCellFormula(“HYPERLINK(\”” + linkValue+ “\”,\”” + actualValue + “\”)”);

Here LinkValue refers Hyperlink and actualValue refers to the value which is to be hyperlinked.

Xquery(Query Language For Web)

Recently i came across an application where i need to parse as webpage and some xml’s i get from a webservice to fill up my database.  I used to do this long back in 2002 but then there was no such standard for parsing such stuff. But this time my life has become easy and we have a Saviour (XQUERY)  as i dont need to parse the whole crap manually. We have a friend in form of XQUERY and it helped me. As a Java programmer I tried to find out Java API which can use Query and found out SAXON

Here are snippets of Code how you use Query to get Data from an XML.

Here is sample which we want to parse

<?xml version=”1.0″ encoding=”UTF-8″?>
<result>
<video_template>
<title/>
<genre>
<choice>action</choice>
……………………………

<choice>special</choice>
</genre>
<rating>
<choice>G</choice>
…………………………………
<choice>NC-17</choice>
</rating>
<user_rating>
<choice>1</choice>
…………………………..
<choice>5</choice>
</user_rating>
<summary/>
<details/>
<year/>
<director/>
<studio/>
<runtime/>
<vhs/>
<vhs_stock/>
<dvd/>
<dvd_stock/>
<beta/>
<beta_stock/>
<laserdisk/>
<laserdisk_stock/>
</video_template>
<actors>
<actor id=”0000000c”>Hackman, Gene</actor>
<actor id=”0000003f”>Hamill, Mark</actor>
<actor id=”00000027″>Heames, Darin</actor>
<actor id=”0000001e”>Heche, Anne</actor>
<actor id=”00000009″>Smith, Will</actor>
<actor id=”0000001b” class=”testserws”>Spoonhauer, Lisa</actor>
<actor id=”00000036″ class=”ashwin”>Sylvester, William</actor>
<actor id=”0000002a”>Todd, Antonio</actor>
<actor id=”00000012″>Voight, John</actor>
<actor id=”0000004b”>Woods, James</actor>
<actor id=”1784027567″>Lewis, Daniel</actor>
<actor id=”2096814035″>Manesse, Gaspard</actor>
<actor id=”325442748″>Feito, Raphael</actor>
<actor id=”4231919377″>Morier, Philippe</actor>
<actor id=”2142583927″>Racette, Francine</actor>
</actors>
<videos>
<video id=”id1235AA0″>
<title>The Fugitive</title>

………………………………………….

Now here is XQuery     .//actors/actor[@class = ‘ashwin’]  to get actor element whose class is ashwin

Here is how you write snippet in java

package xml.tutorial.xquery;

//Java
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;

import javax.xml.transform.OutputKeys;
import javax.xml.transform.sax.SAXSource;
import javax.xml.transform.stream.StreamResult;

import net.sf.saxon.Configuration;
import net.sf.saxon.om.DocumentInfo;
import net.sf.saxon.query.DynamicQueryContext;
import net.sf.saxon.query.StaticQueryContext;
import net.sf.saxon.query.XQueryExpression;

import org.xml.sax.InputSource;

public class XQueryExample {

public static void main(String[] args) {

// the Q.xquery file
InputStream queryStream = null;
String queryFileName = “getMajors.xql”;

// documentul XML ce va fi interogat este reprezentat de
// fisierul AircraftDealer.xml
File XMLStream = null;
String xmlFileName = “student_collection.xml”;

// Filename to parse
xmlFileName = “videos.xml”;

// File name which contains the Query
queryFileName = “getActors.xql”;

// print the result to the console
OutputStream destStream = System.out;

// compile the XQuery expression
XQueryExpression exp = null;

// create a Configuration object
Configuration C = new Configuration();

// static and dynamic context
StaticQueryContext SQC = new StaticQueryContext(C);
DynamicQueryContext DQC = new DynamicQueryContext(C);

// indentation
Properties props = new Properties();
props.setProperty(OutputKeys.METHOD, “xml”);
props.setProperty(OutputKeys.INDENT, “yes”);

try {
queryStream = new FileInputStream(queryFileName);
SQC.setBaseURI(new File(queryFileName).toURI().toString());

/*
* Compile here and this actually finds if there is any problem in
* Query Formation
*/

exp = SQC.compileQuery(queryStream, null);
SQC = exp.getStaticContext().getUserQueryContext();
} catch (net.sf.saxon.trans.XPathException e) {
System.err.println(e.getMessage());
} catch (java.io.IOException e) {
System.err.println(e.getMessage());
}

// get the XML ready
try {
XMLStream = new File(xmlFileName);
InputSource XMLSource = new InputSource(XMLStream.toURI()
.toString());
SAXSource SAXs = new SAXSource(XMLSource);
DocumentInfo DI = SQC.buildDocument(SAXs);
DQC.setContextNode(DI);

// Here is where you evaluate the Query and Post to Standard Output
exp.run(DQC, new StreamResult(destStream), props);
destStream.close();
} catch (net.sf.saxon.trans.XPathException e) {
System.err.println(e.getMessage());
} catch (java.io.IOException e) {
System.err.println(e.getMessage());
}

}

}

And you will get the following output

<actor id=”00000036″ class=”ashwin”>Sylvester, William</actor>

Incase you require the sample project contact me at ashwin[dot]rayaprolu[@]gmail[dot].com

Error While Downloading Files In IE

IE The Culprit
IE The Culprit

I was working a PDF Dowload in my application and one fine day move my application to client test system where the application was aired over https. That screwed up my day to find out bug in my application. But finally when i googled for it i found out that IE has screwed up everything for me.

The problem is with enabling no cache headers in response header.

response.setHeader(“Cache-Control”, “no-cache”); //Forces caches to obtain a new copy of the page from the origin server
response.setHeader(“Cache-Control”, “no-store”); //Directs caches not to store the page under any circumstance
response.setDateHeader(“Expires”, 0); //Causes the proxy cache to see the page as “stale”
response.setHeader(“Pragma”, “no-cache”); //HTTP 1.0 backward compatibility

The moment i removed this everthing worked fine. And finnaly made my last laugh.

For More Reference :http://support.microsoft.com/kb/316431