[Library]: Adding Library Into Java[TM] Project

“currently, i develop an application under Java platform, and i need to use a class which i’ve never used before, where can i get the library which contains the class?”

“how to add more library into my Java project [or program]?”

that questions rise when someone realize that his program needs an additional libraries. there are a sequence of problem people used to face on:

  1. what library does my program needs?
  2. i know the library but where can i get it [or download it]?
  3. i have the library but how to add it into my program?

most of people are getting stuck to find out what kind of library does his program requires to run, the easiest way to find it out is by forcing the program to run, then an exception will be thrown and you just need to see what is missing…? for example, see the following exception:

Exception [TOPLINK-4003] (Oracle TopLink Essentials - 2.0.1 (Build b09d-fcs (12/06/2007))): oracle.toplink.essentials.exceptions.DatabaseException
Exception Description: Configuration error.  Class [com.mysql.jdbc.Driver] not found.
 at oracle.toplink.essentials.exceptions.DatabaseException.configurationErrorClassNotFound(DatabaseException.java:101)
 at oracle.toplink.essentials.sessions.DefaultConnector.loadDriver(DefaultConnector.java:183)
 at oracle.toplink.essentials.sessions.DefaultConnector.connect(DefaultConnector.java:98)
 .....

that’s because of missing class com.mysql.jdbc.Driver, then check this one:

Exception in thread "main" java.lang.NoClassDefFoundError: javax/mail/Message
 at javamail.Main.main(Main.java:8)
Caused by: java.lang.ClassNotFoundException: javax.mail.Message
 at java.net.URLClassLoader$1.run(URLClassLoader.java:200)
 at java.security.AccessController.doPrivileged(Native Method)
 .....

it’s caused by the missing of class javax.mail.Message, then “how to know the library [jar file] if i just know the required class?” simply open your browser and go to http://findjar.com/ to seach what jar file contains the class. download it.

now you have the jar, so how to connect the library [jar file] to the program? there are two possibilities, your program written with IDE or NOT at all.

if you use an IDE in develop your program you just need to add it on, in NetBeans IDE for example you just need to do these:

  1. right click on the project then select properties,
  2. go to ‘Libraries’ category,
  3. select ‘Add JAR/Folder’ to find you JAR file.

but if you don’t use any IDE, you have to link the JAR to the ‘Environtment Variables’, i will show how to add it in Windows operating system.

  1. first ensure the JAR file is in your local drive, then right click on the My Computer icon > select Properties
  2. select the Advanced tab > select Environtment Variables
  3. find the ‘Path’ variable and edit it to add your jar directory location
  4. finish. reopen your command prompt [if you use it].

have a good day,…

Advertisements

[Exception]: a java mail exception

do you get this exception stack:

Exception in thread "main" java.lang.NoClassDefFoundError: javax/mail/Message
 at javamail.Main.main(Main.java:8)
Caused by: java.lang.ClassNotFoundException: javax.mail.Message
 at java.net.URLClassLoader$1.run(URLClassLoader.java:200)
 at java.security.AccessController.doPrivileged(Native Method)
 at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
 at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
 at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
 at java.lang.ClassLoader.loadClass(ClassLoader.java:252)
 at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:320)
 ... 1 more
Java Result: 1

the exception thrown because you miss the Mail API.
You can download it here: http://java.sun.com/products/javamail/downloads/index.html
to fix it up, just add the required Mail API.
[see here to see how to link an external library]

have a good day

[Exception]: a database exception [part 1]

do you get this exception stack:


Exception in thread "main" Local Exception Stack:
Exception [TOPLINK-4003] (Oracle TopLink Essentials - 2.0.1 (Build b09d-fcs (12/06/2007))): oracle.toplink.essentials.exceptions.DatabaseException
Exception Description: Configuration error.  Class [com.mysql.jdbc.Driver] not found.
at oracle.toplink.essentials.exceptions.DatabaseException.configurationErrorClassNotFound(DatabaseException.java:101)
at oracle.toplink.essentials.sessions.DefaultConnector.loadDriver(DefaultConnector.java:183)
at oracle.toplink.essentials.sessions.DefaultConnector.connect(DefaultConnector.java:98)
at oracle.toplink.essentials.sessions.DatasourceLogin.connectToDatasource(DatasourceLogin.java:184)
at oracle.toplink.essentials.internal.sessions.DatabaseSessionImpl.loginAndDetectDatasource(DatabaseSessionImpl.java:582)
at oracle.toplink.essentials.ejb.cmp3.EntityManagerFactoryProvider.login(EntityManagerFactoryProvider.java:280)
at oracle.toplink.essentials.internal.ejb.cmp3.EntityManagerSetupImpl.deploy(EntityManagerSetupImpl.java:229)
at oracle.toplink.essentials.internal.ejb.cmp3.base.EntityManagerFactoryImpl.getServerSession(EntityManagerFactoryImpl.java:93)
at oracle.toplink.essentials.internal.ejb.cmp3.base.EntityManagerFactoryImpl.createEntityManagerImpl(EntityManagerFactoryImpl.java:126)
at oracle.toplink.essentials.internal.ejb.cmp3.base.EntityManagerFactoryImpl.createEntityManagerImpl(EntityManagerFactoryImpl.java:120)
at oracle.toplink.essentials.internal.ejb.cmp3.EntityManagerFactoryImpl.createEntityManager(EntityManagerFactoryImpl.java:91)
at simplejpa.entities.manager.DBManager.refreshEntityManager(DBManager.java:17)
at simplejpa.entities.manager.DBManager.addNewAccount(DBManager.java:28)
at simplejpa.Main.main(Main.java:13)
Java Result: 1

the exception thrown because you miss the Database Driver, exception above occurs if you forget to link the MySQL Database Driver [sometimes called with MySQL Connector]. for MySQL, you can get the Driver here: http://dev.mysql.com/downloads/connector/j/
to fix it up, just add the required JDBC Driver.
[see here to see how to link an external library]

have a good day

Sending Email using Java[TM] Mail API

“can somebody help me to send email using java?”

a year ago, i had a project which requires mail functionality. the most required function was to send email. then we decided to design a class which exploit Java Mail API to fulfill the requirement.
actually we designed only one class, but for improvement, i break it into two classes, these are the classes and the codes:
MailSender

package javamail;

import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;

public class MailSender {

 private String SMTPHost;
 private String SMTPPort;
 private String username;
 private String password;

 public MailSender() {
 SMTPHost = "";
 SMTPPort = "";
 username = "";
 password = "";
 }

 public MailSender(String _SMTPHost, String _SMTPPort,
 String _username, String _password) {
 SMTPHost = _SMTPHost;
 SMTPPort = _SMTPPort;
 username = _username;
 password = _password;
 }

 public void setPassword(String _password) {
 password = _password;
 }

 public void setUsername(String _username) {
 username = _username;
 }

 public String getSMTPHost() {
 return SMTPHost;
 }

 public void setSMTPHost(String _SMTPHost) {
 SMTPHost = _SMTPHost;
 }

 public String getSMTPPort() {
 return SMTPPort;
 }

 public void setSMTPPort(String _SMTPPort) {
 SMTPPort = _SMTPPort;
 }

 public void sendMail(List<String> _to, List<String> _toCC,
 List<String> _toBCC, String _subject, String _content)
 throws Exception {
 if (IMAPAuthenticator.getIMAPAuthentication(SMTPHost, username, password)) {
 Properties props = System.getProperties();

 props.put("mail.smtp.host", SMTPHost);
 props.put("mail.debug", "true");
 props.put("mail.smtp.port", "25");
 props.put("mail.smtp.localhost", SMTPPort);
 props.put("mail.smtp.auth", "false");

 Session session = Session.getInstance(props);
 Message message = new MimeMessage(session);

 try {
 message.setFrom(new InternetAddress(username +
 "@" + SMTPHost));

 for (int counter = 0; counter < _to.size(); ++counter) {
 message.setRecipient(Message.RecipientType.TO, new InternetAddress(_to.get(counter)));
 }

 if (_toCC != null) {
 for (int counterCC = 0; counterCC < _toCC.size(); ++counterCC) {
 message.setRecipient(Message.RecipientType.CC, new InternetAddress(_toCC.get(counterCC)));
 }
 }

 if (_toBCC != null) {
 for (int counterBCC = 0; counterBCC < _toBCC.size(); ++counterBCC) {
 message.setRecipient(Message.RecipientType.BCC, new InternetAddress(_toBCC.get(counterBCC)));
 }
 }

 message.setSubject(_subject);
 message.setText(_content);
 message.setSentDate(new Date());

 Transport.send(message);

 } catch (Exception e) {
 e.printStackTrace();
 throw e;
 }
 } else {
 throw new AuthenticationFailedException("invalid user");
 }
 }
}

IMAPAuthenticator

package javamail;

import com.sun.mail.imap.IMAPStore;
import java.util.Properties;
import javax.mail.Session;

public class IMAPAuthenticator {

 public static boolean getIMAPAuthentication(String _IMAPHost,
 String _username, String _password) throws Exception {
 boolean isAuthenticated = false;

 try {
 Properties properties = System.getProperties();
 Session session = Session.getDefaultInstance(properties);
 IMAPStore store = (IMAPStore) session.getStore("imap");

 store.connect(_IMAPHost, _username, _password);
 store.close();
 isAuthenticated = true;

 } catch (Exception ex) {
 ex.printStackTrace();
 isAuthenticated = false;
 }

 return isAuthenticated;
 }
}

to test it, write this code in your Main class then run it.

package javamail;

import java.util.ArrayList;

public class Main {

 public static void main(String[] args) throws Exception {
 MailSender ms = new MailSender();
 ms.setUsername("myusername");
 ms.setPassword("myPASSwORD");
 ms.setSMTPHost("mail.myhosting.ac.id");
 ms.setSMTPPort("25");

 ArrayList<String> to = new ArrayList();
 ArrayList<String> toCC = new ArrayList();
 String subject = "[JavaMail]: subject";
 String content = "[JavaMail]: content";
 to.add("mr@mail.hishost.com");
 toCC.add("ms@herhost.co.id");
 toCC.add("bthr@mail.somewhere.net");

 ms.sendMail(to, toCC, toCC, subject, content);
 }
}

check your inbox and have a good day…

serialize [object] and deserialize in Java[TM]

“can i store my object into file?”
“how to transmit an object over the network”

in java programming, you can write or transmit your object over the network, how come? java provides an object serialization which ‘converts’ an object into a streaming bits, then you can do many things with the stream.
“could you give me some example?”, okay, in this session i will show you how to serialize objects and deserialize it back.
this are term people used to know:
object -> serialize / deflate / marshalling -> streaming bits
streaming bits -> deserialize / inflate / unmarshalling – > objects
one thing you have to remember is when you want to make a serializable class, make sure that you ‘flag’ it by implements java.io.Serializable interface.
the scenario of the sample is like this:
there are three classes:
SerializableObject: the class which object will be serialized
ObjectDeflater: object to streaming bit ‘converter’
ObjectInflater: streaming bit to object ‘converter’

this is very simple, just create a new project [i use JDK 1.6 update 10 and NetBeans 6.5 IDE] then create the three required classes. after that, write down these codes:

code for SerializableObject:

package javaserialization;
import java.io.Serializable;

public class SerializableObject implements Serializable {

 private final int DEFAULT_ID = 0;
 private final String DEFAULT_NAME = "DEFAULT_NAME";
 private final String DEFAULT_MESSAGE = "DEFAULT_MESSAGE";
 private int objectId;
 private String objectName;
 private String objectMessage;

 public SerializableObject() {
 objectId = DEFAULT_ID;
 objectName = DEFAULT_NAME;
 objectMessage = DEFAULT_MESSAGE;
 }

 public SerializableObject(
 int _objectId,
 String _objectName,
 String _objectMessage) {
 objectId = _objectId;
 objectName = _objectName;
 objectMessage = _objectMessage;
 }

 public int getObjectId() {
 return objectId;
 }

 public void setObjectId(int objectId) {
 this.objectId = objectId;
 }

 public String getObjectMessage() {
 return objectMessage;
 }

 public void setObjectMessage(String objectMessage) {
 this.objectMessage = objectMessage;
 }

 public String getObjectName() {
 return objectName;
 }

 public void setObjectName(String objectName) {
 this.objectName = objectName;
 }

 public void printInfo() {
 System.out.println(
 objectId + "\n" +
 objectName + "\n" +
 objectMessage + "\n");
 }
}

code for ObjectDeflater:

package javaserialization;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;

public class ObjectDeflater {

 private String filePath;
 private File file;
 private FileOutputStream fos;
 private ObjectOutputStream oos;

 public ObjectDeflater(String _filePath) {
 filePath = _filePath;
 }

 private void allocate() throws IOException {
 file = new File(filePath);
 fos = new FileOutputStream(file);
 oos = new ObjectOutputStream(fos);
 }

 private void dealocate() {
 try {
 oos.close();
 } catch (IOException ioe) {
 ioe.printStackTrace();
 }
 }

 public void deflateObject(int _numberOfObject) throws IOException {
 allocate();

 SerializableObject so = null;
 for (int objCounter = 0; objCounter < _numberOfObject; ++objCounter) {
 so = new SerializableObject(objCounter, "my name is: " + objCounter, "my message is: " + objCounter);
 oos.writeObject(so);
 }

 dealocate();
 }
}

code for ObjectInflater:

package javaserialization;

import java.io.EOFException;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;

public class ObjectInflater {

 private String filePath;
 private File file;
 private FileInputStream fis;
 private ObjectInputStream ois;

 public ObjectInflater(String _filePath) {
 filePath = _filePath;
 }

 private void allocate() throws IOException {
 file = new File(filePath);
 fis = new FileInputStream(file);
 ois = new ObjectInputStream(fis);
 }

 private void dealocate() {
 try {
 ois.close();
 } catch (IOException ioe) {
 ioe.printStackTrace();
 }
 }

 public void inflateObject() throws IOException, ClassNotFoundException {
 allocate();

 SerializableObject so = null;
 try {
 while ((so = (SerializableObject) ois.readObject()) != null) {
 so.printInfo();
 }
 } catch (EOFException eofe) {
 // reaches end of file
 // no action required
 // leave it blank
 }

 dealocate();
 }
}

to test the project, write this code in the Main class:

package javaserialization;

public class Main {

 public static void main(String[] args) {
 // your file path, it must be exists
 String filePath = "D:\\tutorials\\JavaSerialization\\objectschest.txt";
 ObjectDeflater od = null;
 ObjectInflater oi = null;

 try {
 od = new ObjectDeflater(filePath);
 od.deflateObject(5);
 } catch (Exception ex) {
 ex.printStackTrace();
 }

 try {
 oi = new ObjectInflater(filePath);
 oi.inflateObject();
 } catch (Exception ex) {
 ex.printStackTrace();
 }
 }
}

run the project then discover what is happening…
have a good day,

Using Java Persistence API [JPA] – Sample [2]

well, in this section you will try to update and remove a record in a database through Java Persistence API.

hum,… this part is a continued part of the provious section actually, so you need to do the previous [about record insertion] before continuing to this one.

updating and removing record by using JPA is so easy. in this session you just need to modify two classes that we have made before [in the previous part].

  1. first is modifying DBManager class by adding four more methods, the class will be like this:
    package simplejpa.entities.manager;
    import javax.persistence.Query;
    import javax.persistence.EntityManager;
    import javax.persistence.EntityManagerFactory;
    import javax.persistence.Persistence;
    import simplejpa.entities.Account;
    
    public class DBManager {
    
     private EntityManager em;
     private EntityManagerFactory emf;
    
     private EntityManager refreshEntityManager() {
     emf = Persistence.createEntityManagerFactory("SimpleJPAPU");
     if (em == null) {
     em = emf.createEntityManager();
     }
    
     return em;
     }
    
     public void addNewAccount(
     String _accountName,
     String _accountEmail,
     String _accountPhone,
     String _accountAddress) {
     refreshEntityManager();
     try {
     em.getTransaction().begin();
     Account account = new Account();
     account.setAccountName(_accountName);
     account.setAccountEmail(_accountEmail);
     account.setAccountPhone(_accountPhone);
     account.setAccountAddress(_accountAddress);
    
     em.persist(account);
     em.getTransaction().commit();
     } catch (Exception ex) {
     ex.printStackTrace();
     }
     }
    
     public Account getAccountWithID(Long _accountId) {
     refreshEntityManager();
     Account account = null;
     Query query = em.createQuery("SELECT A FROM Account A WHERE A.accountId=:ACCOUNTID");
     query.setParameter("ACCOUNTID", _accountId);
    
     try {
     account = (Account) query.getSingleResult();
     } catch (Exception ex) {
     ex.printStackTrace();
     }
    
     return (account);
     }
    
     public Account getAccountWithName(String _accountName) {
     refreshEntityManager();
     Account account = null;
     Query query = em.createQuery("SELECT A FROM Account A WHERE A.accountName=:ACCOUNTNAME");
     query.setParameter("ACCOUNTNAME", _accountName);
    
     try {
     account = (Account) query.getSingleResult();
     } catch (Exception ex) {
     ex.printStackTrace();
     }
    
     return (account);
     }
    
     public void updateAccountWithID(
     Long _accountId,
     String _newAccountName,
     String _newAccountEmail,
     String _newAccountPhone,
     String _newAccountAddress) {
     refreshEntityManager();
     try {
     em.getTransaction().begin();
     Account account = getAccountWithID(_accountId);
     account.setAccountName(_newAccountName);
     account.setAccountEmail(_newAccountEmail);
     account.setAccountPhone(_newAccountPhone);
     account.setAccountAddress(_newAccountAddress);
    
     em.merge(account);
     em.getTransaction().commit();
     } catch (Exception ex) {
     ex.printStackTrace();
     }
     }
    
     public void removeAccountWithID(
     Long _accountId) {
     refreshEntityManager();
     try {
     em.getTransaction().begin();
     Account account = getAccountWithID(_accountId);
    
     em.remove(account);
     em.getTransaction().commit();
     } catch (Exception ex) {
     ex.printStackTrace();
     }
     }
    }
    
  2. the next is to modifying Main class, just like this:
    package simplejpa;
    import simplejpa.entities.Account;
    import simplejpa.entities.manager.DBManager;
    
    public class Main {
    
     public static void main(String[] args) {
     // instantiate DBManager
     DBManager dbm = new DBManager();
    
     // try to add some new accounts
     dbm.addNewAccount("mario", "mariosimaremare@yahoo.co.id", "0123456789", "Sitoluama");
     dbm.addNewAccount("mario elyezer", "mariosimaremare@gmail.com", "081081081081", "Laguboti");
     dbm.addNewAccount("mario simaremare", "mariosimaremare@hotmail.com", "085208520852", "North Sumatera");
    
     // retrieve some registered accounts
     Account mario = dbm.getAccountWithName("mario");
     Account marioelyezer = dbm.getAccountWithName("mario elyezer");
    
     // try to remove account
     dbm.removeAccountWithID(mario.getAccountId());
     // try to update account
     dbm.updateAccountWithID(marioelyezer.getAccountId(), "mario elyezer subekti", "me@mycampus.com", "065506550655", "campus");
     }
    }
    
  3. ok, finish! you can run it to see what will happens…

have a good day,

Using Java Persistence API [JPA] – Sample [1]

now, we will practice a simple action by using Java Persistence API to interact between a simple application and it’s database.
first of all, i use this as my specifications:
MySQL database, JDK 1.6 update 10 and NetBeans 6.5 as IDE.

let’s we start it:

  1. now create a database called ‘tutorialdb’ with only one table inside, ‘account’ table. you may see the table specification below:
  2. ok, i think there is no problem in database and table creation. now we go to the java code.
  3. open your NetBeans [i use NetBeans 6.5] and create a new project, name it as ‘SimpleJPA’.
  4. now we just need to ‘convert’ all tables into classes. how? by right clicking on the project, select ‘New’ > ‘Entity Classes from Database…’.
  5. if you have no database connection, just create a new one by choosing ‘New Database Connection’.
  6. fill all required fields, make sure that you fill all of them.
  7. then NetBeans will retrieve all tables inside the database, choose the ‘account’ then click ‘Next’ to continue…
  8. you can specified the package for this entity [and it’s recommended].
  9. after the entity generated, you’ll see some missing libraries, to fix it, you just need to add TopLink and MySQL Connector, don’t worry NetBeans provide all of them.  you just need to link it to them. how? right clicking on the project’s Libraries > Add Library. select TopLink Essential and MySQL JDBC Driver.
  10. the next step is creating a persistence unit, it’s a part of Java Persistence API, which act as the administrator of connectivity, and maintain the entity life cycle. to create a persistence unit, right clicking on the project > ‘New’ > ‘Persistence Unit’.
  11. then fill the persistence unit’s name, set the driver with TopLink [default] and select the database connection. finish.
  12. now you have a managed type of entity.
  13. hmm,… do we have all? actually, yes, but i would prefer to create a manager class which will simplify us [as the programmer] to interact with the entity object, just call it as ‘Database Manager’.
  14. okay, now create a new Java Class name it as ‘DBManager’ then write down this code:
  15. package simplejpa.entities.manager;
    
    import javax.persistence.EntityManager;
    import javax.persistence.EntityManagerFactory;
    import javax.persistence.Persistence;
    import simplejpa.entities.Account;
    
    public class DBManager {
    
     private EntityManager em;
     private EntityManagerFactory emf;
    
     private EntityManager refreshEntityManager() {
     emf = Persistence.createEntityManagerFactory("SimpleJPAPU");
     if (em == null) {
     em = emf.createEntityManager();
     }
    
     return em;
     }
    
     public void addNewAccount(
     String _accountName,
     String _accountEmail,
     String _accountPhone,
     String _accountAddress) {
     refreshEntityManager();
     try {
     em.getTransaction().begin();
     Account account = new Account();
     account.setAccountName(_accountName);
     account.setAccountEmail(_accountEmail);
     account.setAccountPhone(_accountPhone);
     account.setAccountAddress(_accountAddress);
    
     em.persist(account);
     em.getTransaction().commit();
     } catch (Exception ex) {
     ex.printStackTrace();
     }
     }
    }
    
  16. to test the JPA, on the Main class, write down this code:
package simplejpa;

import simplejpa.entities.manager.DBManager;

public class Main {

    public static void main(String[] args) {
        DBManager dbm = new DBManager();
        String name = "mario";
        String email = "mariosimaremare@yahoo.co.id";
        String phone = "00123456789";
        String address = "North Sumatera - Indonesia";
        dbm.addNewAccount(name, email, phone, address);
    }
}