Sunday, December 26, 2010

Using Gmail to Send Emails (with attachments)



In this post we will learn how to send attachment in email like file or image also how to embed the image inside the email.

The good thing about Gmail is that we can use it to send emails as SMTP server.

Here is the needed steps:

1.Define the following attributes:

smtpServerIP = smtp.gmail.com;
smtpServerPort = 465;
smtpServerUser = Your gmail email;
smtpServerPassword = Your gmail email password;

2.The following is mail sending method:

public void sendMail(final String[] toUserEmail, final String subject, final String body,final BufferedImage myImage, final File file, final boolean isPicture) {

new Thread() {
@Override
public void run() {
try {
Properties props = new Properties();
props.put("mail.smtp.host", smtpServerIP);
props.put("mail.smtp.port", smtpServerPort);
props.put("mail.smtp.auth", "true");
//props.put("mail.debug", "false");
props.put("mail.smtp.socketFactory.port", smtpServerPort);
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback", "false");
Authenticator auth = new SMTPAuthenticator();
Session session = Session.getInstance(props, auth);
//session.setDebug(false);
// create a message
Message msg = new MimeMessage(session);
msg.setHeader("HomeMonitor", "By Osama Oransa");
// set the from and to address
InternetAddress addressFrom = new InternetAddress(smtpServerUser);
msg.setFrom(addressFrom);
InternetAddress[] addressTo = new InternetAddress[toUserEmail.length];
for (int i = 0; i < toUserEmail.length; i++) {
addressTo[i] = new InternetAddress(toUserEmail[i]);
}
msg.setRecipients(Message.RecipientType.TO, addressTo);
String[] messageParts = body.split("##");
//no thing attached
if (messageParts.length == 1) {
msg.setContent(body, "text/html");
//image is attached
//body is text and image
} else if (messageParts.length == 2) {
MimeMultipart multipart = new MimeMultipart();//"related");
MimeBodyPart messageBodyPart;
// first part html text before image
messageBodyPart = new MimeBodyPart();
if (isPicture) {
messageBodyPart.setContent(messageParts[0] + "

" + messageParts[1], "text/html");
multipart.addBodyPart(messageBodyPart);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
boolean readingImageResult;
try {
readingImageResult = ImageIO.write(myImage, "jpg", byteArrayOutputStream);
System.out.println("Result of writing the image is " + readingImageResult);
} catch (IOException ex) {
ex.printStackTrace();
}
byte[] byteArray = byteArrayOutputStream.toByteArray();
MimeBodyPart messageBodyPart2 = new MimeBodyPart();
DataSource fds = new ByteArrayDataSource(byteArray, "image/jpg");
messageBodyPart2.setDataHandler(new DataHandler(fds));
messageBodyPart2.setHeader("Content-ID", "");
multipart.addBodyPart(messageBodyPart2);
msg.setContent(multipart);
} else {
//is file attached, like voice....
messageBodyPart.setContent(messageParts[0] + "
" + messageParts[1], "text/html");
multipart.addBodyPart(messageBodyPart);
// Part two is attachment
MimeBodyPart messageBodyPart2 = new MimeBodyPart();
DataSource source = new FileDataSource(file);
messageBodyPart2.setDataHandler(new DataHandler(source));
messageBodyPart2.setFileName(file.getName());
multipart.addBodyPart(messageBodyPart2);
msg.setContent(multipart);
}
}
// Setting the Subject and Content Type
msg.setSubject(subject);
Transport.send(msg);
System.out.println("Message sent to " + toUserEmail + " OK.");
} catch (Exception ex) {
ex.printStackTrace();
System.out.println("Exception " + ex);
}
}
}.start();
}

3. Define inner class for authentication:

// Also include an inner class that is used for authentication purposes
private class SMTPAuthenticator extends javax.mail.Authenticator {
@Override
public PasswordAuthentication getPasswordAuthentication() {
System.out.println("call authentication");
String username = smtpServerUser;
String password = smtpServerPassword;
return new PasswordAuthentication(username, password);
}
}


The method send email either plain email or with attachement or with embeded picture in it.
final String[] toUserEmail, final String subject, final String body,final BufferedImage myImage, final File file, final boolean isPicture)

It takes array of emails to send to them, subject and body of the email.
Then it take optional image or file to attach (not both so you can modify the method to include this extra-requirements)

The boolean isPicture is used to deal with picture as embedded object..

In case you need to attach image or file , you need to place in the body of the email the token ## file name or image name (or title).

This is easy usage method for sending emails with attachment and in our example we used Gmail as SMTP server.

Wednesday, December 22, 2010

Java Home Monitor Application

New Open source application is released..

URL:

http://sourceforge.net/projects/home-monitor/

In summary :

This application used to monitor your home via email using your USB web camera and microphone , there is a lot of configurations to customize it upon needs. A motion detection is also supported.

Features:

* Use USB web camera and microphone
* Work while computer is locked
* Differentiate between capturing the image/audio and sending them in email as attachments
* Configurable for customization of the needs
* Motion detection to send out of configuration shots.
* Can send emails using gmail user account.
* Captured media stored in specified directory and send some according to the configurations.
* Depends on LTI-CIVIL for accessing the USB camera: http://lti-civil.org/
* You can download the library and pick the needed library for the operating system
* Run over any operating system.
* Tested well in Java 5 , still there is issue in email sending with attachment in Java 6.
* Optionally Play sound/recorded message on repeated motion detection.
* Wait for configurable time before start capturing.
* In Version 1.1 (1) a new configuration item to delete old picture if new matched it.
* (2) Also FTP Support is added.

Future Enhancements:

-Detect motion detection in voice files ..
-Send video files (combined video+audio).
-Send SMS through any free gateway.

Saturday, December 18, 2010

Capture photo / image from Web Cam / USB Camera using Java

In this post we will show how to use a USB camera to capture a picture from inside a Java application..
We will use the library LTI-CIVIL which is part of FMJ (Freedom for Media in Java)



Let's go through the needed steps:

1.Download LTI-CIVIL:

Which is a Java library for capturing images from a video source such as a USB camera. It provides a simple API and does not depend on or use JMF!
The advantage behind this library that it doesn't depend on JMF (which is almost very old now)
The project URL: http://lti-civil.org/
Download URL: http://sourceforge.net/projects/lti-civil/files/

Extract the zip/tar file and you will find 2 things we will use:
a) lti-civil-no_s_w_t.jar
b) native folder contain the native libraries according to the operating system , pick the one for the system you are using.


2.Create the Java App:

Add to the class-path of the project the jar file and the native library folder.
To Run the project as jar file , you can use the JVM parameter:

-Djava.library.path=".....\native\win32-x86" to add the library to the class path of the jar file.


3.Create a class file:

Name it like TestWebCam implements CaptureObserver

4. Define the following instance variables:

JButton start = null;
JButton shot = null;
JButton stop = null;
CaptureStream captureStream = null;
boolean takeShot=false;

5.In the constructor:

Add the following code to initialize the capturing device:

public TestWebCam() {
CaptureSystemFactory factory = DefaultCaptureSystemFactorySingleton.instance();
CaptureSystem system;
try {
system = factory.createCaptureSystem();
system.init();
List list = system.getCaptureDeviceInfoList();
int i = 0;
if (i < list.size()) {
CaptureDeviceInfo info = (CaptureDeviceInfo) list.get(i);
System.out.println((new StringBuilder()).append("Device ID ").append(i).append(": ").append(info.getDeviceID()).toString());
System.out.println((new StringBuilder()).append("Description ").append(i).append(": ").append(info.getDescription()).toString());
captureStream = system.openCaptureDeviceStream(info.getDeviceID());
captureStream.setObserver(TestWebCam.this);
}
} catch (CaptureException ex) {
ex.printStackTrace();
}
//UI work of the program
JFrame frame = new JFrame();
frame.setSize(7000, 800);
JPanel panel = new JPanel();
frame.setContentPane(panel);
frame.setVisible(true);
frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
start = new JButton("Start");
stop = new JButton("Stop");
shot = new JButton("Shot");
panel.add(start);
panel.add(stop);
panel.add(shot);
panel.revalidate();
start.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
captureStream.start();
} catch (CaptureException ex) {
ex.printStackTrace();
}
}
});
stop.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
captureStream.stop();
} catch (CaptureException ex) {
ex.printStackTrace();
}
}
});
shot.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
takeShot=true;
}
});
}

6.Add the following 2 methods mandated by the implemented interface CaptureObserver:

public void onNewImage(CaptureStream stream, Image image) {
if(!takeShot) return;
takeShot=false;
System.out.println("New Image Captured");
byte bytes[] = null;
try {
if (image == null) {
bytes = null;
return;
}
try {
ByteArrayOutputStream os = new ByteArrayOutputStream();
JPEGImageEncoder jpeg = JPEGCodec.createJPEGEncoder(os);
jpeg.encode(AWTImageConverter.toBufferedImage(image));
os.close();
bytes = os.toByteArray();
} catch (IOException e) {
e.printStackTrace();
bytes = null;
} catch (Throwable t) {
t.printStackTrace();
bytes = null;
}
if (bytes == null) {
return;
}
ByteArrayInputStream is = new ByteArrayInputStream(bytes);
File file = new File("/img" + Calendar.getInstance().getTimeInMillis() + ".jpg");
FileOutputStream fos = new FileOutputStream(file);
fos.write(bytes);
fos.close();
BufferedImage myImage = ImageIO.read(file);
shot.setText("");
shot.setIcon(new ImageIcon(myImage));
shot.revalidate();
} catch (IOException ex) {
ex.printStackTrace();
}
}

public void onError(CaptureStream stream, CaptureException ce) {
System.out.println("Error!");
}

7.Optionally, to Covert image to Gray Scale:

In case you need to convert it into Gray scale (for image processing purposes you can replace the following line with this block:

Old Line:
shot.setIcon(new ImageIcon(myImage));

New Block:

//Convert myImage to gray scale
BufferedImage imageGray = new BufferedImage(myImage.getWidth(), myImage.getHeight(),
BufferedImage.TYPE_BYTE_GRAY);
Graphics g = imageGray.getGraphics();
g.drawImage(myImage, 0, 0, null);
g.dispose();
shot.setIcon(new ImageIcon(imageGray));


8.Add main method to this class to run it:

public static void main(String args[])
throws Exception {
TestWebCam test = new TestWebCam();
}

9.Connect the USB Camera and run the application...

It should show 3 buttons : Start , Stop and Shot..
Click on start , then on shot, it will get you the current web camera image, move the web camera and take another shot by click on the picture to update it.


**Possible Issues:

1.Native library is not in the classpath.
2.Wrong native library is used.
3.USB Camera is not correct connected or installed.
4.Another program is running connected to the camera resource (you may be running your program 2 times)

You can use the CaptureStream parameter as well, but i think if you need to capture a streaming web cam , it would better to use images with intervals.


*** UPDATE: based on a lot of requests asking about using it to capture videos, here is the new post discussing the topic in details:

WebCam Video Capture in Java

Hope this help more to address this issue in particular.

*** UPDATE|: based on number of requests to access the web camera from JSP file , here is a link to a post discussing the how to in details:

Accessing Webcam Within JSP


*** UPDATE: if you want sample code , please download my other open source project Interactive4J, it has example for video and images.

Friday, November 5, 2010

New Open Source : Java Web Chat Module

Overview:

This project aim to develop a plug-in module for ready use in Java Web application with a little effort, it has many ways to persist the account details (XML vs DB) and it can be used as a standalone application for "Support services" in the web sites.

Features:

* Web Chat Module
* Ajax based
* Support UTF-8 (for multi-lingual)
* Standalone Service or Plugin in your web site
* Easy customizable, account management is left to implementer
* XML-based account management is the default, you can use DB instead.
* Easy icons customization and adding more themes to it.
* Performance is good and least memory consumption.
* Support emoticons
* Sound is supported in IE (only currently, can be fixed later with HTML5)
* Messages failed to deliver returned to the sender.



Project URL:
http://sourceforge.net/projects/java-web-chat/

The module is easy customizable and fit into any Java web application (or non-Java) and can be used as a standalone chat gateway.

Source code in a Netbeans project can downloaded here.

Saturday, September 11, 2010

2010 Duke's Choice Awards Winner




http://java.com/en/dukeschoice/

The Duke's Choice Awards celebrate extreme innovation in the world of Java technology and are granted to the most innovative projects using the Java platform.

The 2010 Duke's Choice Awards winners will be featured at the Oracle Technology Network (OTN) tent on Mason Street (between Ellis and O'Farrell streets) during JavaOne in San Francisco September 20-23rd.

Innovative Health Care & Human Services
Pulse Pulse Health Intact System, remote telemedicine server that connects doctors, patients and care facilities. Monitoring devices connected to the patient's mobile phone is uploaded and shared. Uses Java EE 6 (server), Java SE 1.6 Swing clients (desktop) and Java ME CLDC (client)




http://www.oracle.com/technetwork/articles/java/dukeschoicewinners-171159.html

Java technologies: Server uses JDK1.6 and JEE 6 (Struts application with some exposed Servlets and Web Services), Java Encryption APIs, JDBC and Java Mail APIs. Mobile/PC clients use J2ME CLDC 1.0 and MIDP 1.1, push registry, Bluetooth APIs, File Connection APIs, Java SE 1.6 Swing, and RMS.

Employing a full complement of Java technology, the Pulse Health Intact system offers remote telemedicine solutions to the developing world—transmitting patient information and monitoring data (blood pressure, blood sugar, ECG, etc.) to doctors via Bluetooth connections and mobile handsets, as well as integrating with existent hospital medical record systems. The server portion of the system employs JDK1.6 and Java EE 6 (Struts application with some exposed Servlets and Web Services), Java Encryption APIs (for secure patient privacy), JDBC (for integration with existent hospital systems) and Java Mail APIs. Meanwhile, the mobile/PC client applications use J2ME CLDC 1.0 and MIDP 1.1, push registry, Bluetooth APIs, File Connection APIs, Java SE 1.6 Swing, and RMS to persist application settings. “Java’s complete set of APIs for web/enterprise solutions, Mobile applications, and standalone applications made this dream come true,” says company System Architect, Osama Oransa.



For more details about Health Intact click Here.

Here is some info about me in I'm future of the Java campaign:

http://www.oracle.com/us/javaonedevelop/future-of-java-168616.html#oransa

I have made a lot of efforts in gathering the requirements and put the architecture, high level and low level design of this solution.



Conference Keynote presentation in this URL:
http://ondemandpreview.vportal.net/?auid=146&sid=4171

Live interview with Oracle Technology Tent in this URL:
http://medianetwork.oracle.com/media/show/15627?n=playlist&nid=86




This Award is one of the important milestones in my life, but there will be still more and more isA and the coming should be better isA.

Osama Oransa

Tuesday, August 17, 2010

Cryptography 1

"Classical Cryptography"

Some Basic Terminology
*plaintext - original message
*ciphertext - coded message
*cipher - algorithm for transforming plaintext to ciphertext
*key - info used in cipher known only to sender/receiver
*encipher (encrypt) - converting plaintext to ciphertext
*decipher (decrypt) - recovering plaintext from ciphertext
*cryptography - study of encryption principles/methods
*cryptanalysis (codebreaking) - study of principles/ methods of deciphering
*ciphertext without knowing key
*cryptology - field of both cryptography and cryptanalysis

We have 2 big categories in cryptography private key (single key) or public key (double key) all classical cryptography fall into the private key where a key exist and we need to keep it private between the sender and reciver only .. We will discuss the public key with the modern cryptography..

Let's discuss the Classical Cryptography: this include 3 types ; substitution where some letters replace by others , transposition where exchange some letters positions and the 3rd type is one time pad where the letter changed totally by manipulating them the key..

A) Classical Substitution Ciphers:

-letters of plaintext are replaced by other letters or by numbers or symbols
1.Caesar Cipher:
Replaces each letter by 3rd letter (or k shifted letter)
example:
meet me after the toga party
PHHW PH DIWHU WKH WRJD SDUWB
Mathematically give each letter a number (a=0,.....z=25)
a b c d e f g h i j k l m n o p q r s t u v w x y z
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25

then have Caesar cipher as:
c = E(p) = (p + k) mod (26)
p = D(c) = (c – k) mod (26)

2.Monoalphabetic Cipher:
Rather than just shifting the alphabet ,could shuffle (jumble) the letters arbitrarily
each plaintext letter maps to a different random ciphertext letter hence key is 26 letters long

Plain: abcde fghij klmno pqrst uvwxyz
Cipher: DKVQF IBJWP ESCXH TMYAU OLRGZN

Plaintext: if we wish to replace letters
Ciphertext: WI RF RWAJ UH YFTSDVF SFUUFYA

now have a total of 26! = 4 x 1026 keys with so many keys, might think is secure but would be !!!WRONG!!! problem is language characteristics=Language Redundancy and Cryptanalysis:
letters are not equally commonly used in English E is by far the most common letter followed by T,R,N,I,O,A,S other letters like Z,J,K,Q,X are fairly rare



3.Playfair Cipher:
one approach to improving security was to encrypt multiple letters the Playfair Cipher is an example a 5X5 matrix of letters based on a keyword fill in letters of selected keyword,fill rest of matrix with other letters eg. using the keyword MONARCHY



Plaintext is encrypted two letters at a time
-If a pair is a repeated letter, insert filler like 'X’.
e.g. BALLOON will be treated as: BA LX LO ON
-If the plaintext has an odd number of characters, a 'X' letter is appended to the end of plaintext.
-Encryption:
* If both letters m1 and m2 fall in the same row, then c1 and c2 replace each with letter to the right of m1 and m2, respectively.



* If both letters fall in the same column, replace each with the letter below it



* Otherwise each letter is replaced by the letter in the same row and in the column of the other letter of the pair.

And Reverse this in decryption.

4.Vigenère Cipher:
basically multiple caesar ciphers ,key is multiple letters long K = k_(1) k_(2) ... k_(d)
based on a Vigenère Tableau

Plaintext THIS PROC ESSCANAL SOBE EXPRES SED
Keyword CIPH ERCI PHERCIPH ERCI PHERCI PHE
Ciphertext VPXZ TIQK TZWTCVPS WFDM TETIGA HLH


(Vigenère Tableau)

B) Classical Transposition Ciphers:
Letters positions exchanged using a key by which we can decrypt the message by returning the letters to the original location.

1.Scytale cipher
:
a strip of paper was wound round a staff message written along staff in rows, then paper removed leaving a strip of seemingly random letters. not very secure as key was width of paper & staff



2.Geometric Figure
Write message following one pattern and read out with another
Example: I CAME I SAW I CONQUERED



3.Row Transposition ciphers:
In general write message in a number of columns and then use some rule to read off from these columns.
Key could be a series of number being the order to: read off the cipher; or write in the plaintext.
Also We can use a word, with letter order giving sequence: to write in the plaintext; or read off the cipher

Key (W): C O M P U T E R
Key (W): 1 4 3 5 8 7 2 6



C) One-Time Pad:
If a truly random key as long as the message is used, the cipher will be secure
called a One-Time pad is unbreakable since ciphertext bears no statistical relationship to the plaintext since for any plaintext & any ciphertext there exists a key mapping one to other can only use the key once though problems in generation & safe distribution of key.

Key is never re-used and generated from Unpredictable random numbers (physical sources, e.g. radioactive decay)

By either subtraction (in Traditional) and XOR (or modulo 2 addition) in modern.
Key=581295 , Plain=853759
-Encryption: (subtraction)
5 8 1 2 9 5
__

8 5 3 7 5 9
___________

7 3 8 5 4 6

-Decryption:
5 8 1 2 9 5
__
7 3 8 5 4 6
____________
8 5 3 7 5 9

-Encryption (XOR):
Plain 01010011000111
Key 00110011001100
_________________________
Cipher 01100000001011

-Decryption (XOR):
Cipher 01100000001011
Key 00110011001100
_________________________
Plain 01010011000111


Abstracted from Dr.Baha Hasan Lectures, AAST