Friday, March 16, 2012

JAVA: File and Directory Creator

This article will teach you on how to create and delete file(s) and directory(ies).
Below are the following code:

FileCreator.java

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import org.apache.log4j.Logger;
/**
 * Utility for creating new files and directories
 * @author Froilan Cardosa Benito
 * @since August 25, 2007
 */
public class FileCreator {
   /**
     * This method is used to create file. 
     * @param path 
     * @param fileName
     */
   public void createFile(String path, String fileName){
      try {
  OutputStream fileWriter = new FileOutputStream(path + fileName);
 fileWriter.close();
  } catch (FileNotFoundException e) {
         System.out.println(e.getMessage());
  } catch (IOException e) {
   System.out.println(e.getMessage());
  }
  }
  /**
  * This method is used to create directory.
  * @param directoryName
  * @return boolean
  */
  public boolean createDirectory(String directoryName){
  boolean isSuccessful = false;
  try{
  File directory = new File(directoryName);
if(!directory.exists()){
isSuccessful = (new File(directoryName)).mkdir();
  if (isSuccessful) {
System.out.println("\n~ Created directory " + directoryName + " successfully!");
  }
}else{
// Remove the previously created directory.
deleteDir(directory);
// Create a new directory.
isSuccessful = (new File(directoryName)).mkdir();
if (isSuccessful) {
               System.out.println("\n~ Created directory " + directoryName + " successfully!");
            }
         }
      } catch(Exception e){
  System.out.println(e.getMessage(), e);
isSuccessful = false;
  }
      return isSuccessful;
   }
   /** 
     * This method is used to delete a specific directory.
  * @param dir
  * @return boolean
  */
  private boolean deleteDir(File dir) {
      if (dir.isDirectory()) {
         String[] children = dir.list();
         for (int i=0; i
boolean success = deleteDir(new File(dir, children[i]));                
if (!success) {                
               System.out.println("Unable to delete directory " + dir.getName());
               return false;    
            }else{ 
               System.out.println("\n~ Deleted directory " + dir.getName() + " successfully!");
            }
         }
      }
      // The directory is now empty so delete it
      return dir.delete();
   }
   /** 
     * this method is used to create directory without existing delete. 
     * @param directoryName
  * @return boolean
     */
   public boolean createDirectoryWithoutExistingDelete(String directoryName){
  boolean isSuccessful = false;
  try{
         File directory = new File(directoryName);
         if(!directory.exists()){
  isSuccessful = (new File(directoryName)).mkdir();
  if (isSuccessful) { 
               System.out.println("\n~ Created directory " + directoryName + " successfully!");
  }
  }else{
 System.out.println("\n~ Directory " + directoryName + " exists!");
  }
      } catch(Exception e){
          System.out.println(e.getMessage(), e);
          isSuccessful = false;
      }
      return isSuccessful;
   }
   /**
     * This method is used to create multiple directories.
     * @param directoryNames
     * @return boolean
     */
   public boolean createDirectories(String directoryNames){
      boolean isSuccessful = false;
      try{
         isSuccessful = (new File(directoryNames)).mkdirs();
         if (isSuccessful) {
              System.out.println("\n~ Directories: " + directoryNames + " created!");
         }
      } catch(Exception e){ 
         System.out.println(e.getMessage(), e);
         isSuccessful = false;
      }
      return isSuccessful;
   }
}

JAVA: Email Notification


This article will teach you on how to send an email using javamail api.
download javamail jar file here:
Below are the following code:

EmailClient.java

import java.util.Date;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import com.util.emailer.Email;
/**
 * 
 * @author Froilan Cardosa Benito
 * @since March 06, 2012
 * @version 1.0
 * @category Email Notification
 *
 */
public class EmailClient {
  /**
    * Send an email to specified recipients.
    * @param emailContent
    * @throws EmailClientException
    */
   public void emailClient(Email emailContent) throws EmailClientException{
      boolean debug = false;      
      //Set the host smtp address
      Properties props = new Properties();
      props.put("mail.smtp.host", emailContent.getSmtpHost());
      // create some properties and get the default Session
      Session session = Session.getDefaultInstance(props, null);
      session.setDebug(debug);
      // create a message
      Message msg = new MimeMessage(session);
      // set the from and to address
      InternetAddress addressFrom;
      try {         
         addressFrom = new InternetAddress(emailContent.getSenderFrom());
  msg.setFrom(addressFrom);
  InternetAddress[] addressTo = new InternetAddress[emailContent.getRecipientTo().length ];
         for (int i = 0; i < emailContent.getRecipientTo().length; i++) {
            addressTo[i] = new InternetAddress(emailContent.getRecipientTo()[i].trim());
         }
         msg.setRecipients(Message.RecipientType.TO, addressTo);         
         if(emailContent.getRecipientCc() != null){
            InternetAddress[] addressCc = new InternetAddress[emailContent.getRecipientCc().length];         
            for (int i = 0; i < emailContent.getRecipientCc().length; i++) {
               addressCc[i] = new InternetAddress(emailContent.getRecipientCc()[i].trim());
            }
            msg.setRecipients(Message.RecipientType.CC, addressCc);
         }
         //Opt.: You can also set your custom headers in the Email if you Want
         //msg.addHeader("MyHeaderName", "myHeaderValue");
         // Setting the Subject and Content Type
         msg.setSubject(emailContent.getEmailSubject());
         msg.setContent(emailContent.getEmailContent(), "text/plain");
         //msg.setFileName(emailContent.getEmailAttachment());
         msg.setSentDate(new Date());
         Transport tr = session.getTransport("smtp");
         tr.connect(emailContent.getSmtpHost(), "username", "password");
         msg.saveChanges();      // don't forget this
         tr.sendMessage(msg, msg.getAllRecipients());
         tr.close();      
      } catch (AddressException e) {
         throw new EmailClientException(e);
      } catch (MessagingException e) {
         throw new EmailClientException(e);
      } catch (Exception e){
         throw new EmailClientException(e);
      }
   }
   public static void main(String args[]){
      String[] recipientTo = {"youremail@domain.com"};
      String[] recipientCc = {"hisemail@domain.com"};      
      Email email = new Email();
      email.setSenderFrom("serveremail@domain.com");
      email.setEmailContent("Hello Froilan Benito. \n\nThis is a test email notification that will be used in Data Portal when a document is processed completely. \n\nThis is an auto generated email, please do not reply. \n\nPowered By: javamail API");
      email.setEmailSubject("Your Server");
      email.setRecipientTo(recipientTo);
      email.setRecipientCc(recipientCc);
      email.setSmtpHost("smtp.server.com");
      EmailClient e = new EmailClient();
      try {
         e.emailClient(email);
      } catch (EmailClientException e1) {
         // TODO Auto-generated catch block
         e1.printStackTrace();
      }
   }
}

EmailClientException.java


public class EmailClientException extends Exception {
   private static final long serialVersionUID = -8357647554996803590L;
   public EmailClientException(){
      super();
   }
   public EmailClientException(String message){
      super(message);

   }
   public EmailClientException(Throwable cause){
      super(cause);
   }
   public EmailClientException(String message, Throwable cause){
      super(message, cause);
   }
}

Email.java

public class Email {
   public String smtpHost;
   public String[] recipientTo;
   public String[] recipientCc;
   public String[] recipientBcc;
   public String senderFrom;
   public String emailSubject;
   public String emailContent;
   public String emailAttachment;

   public String getEmailContent() {
      return emailContent;
   }
   public void setEmailContent(String emailContent) {
      this.emailContent = emailContent;
   }
   public String getEmailSubject() {
      return emailSubject;
   }
   public void setEmailSubject(String emailSubject) {
      this.emailSubject = emailSubject;
   }
   public String[] getRecipientBcc() {
      return recipientBcc;
   }
   public void setRecipientBcc(String[] recipientBcc) {
      this.recipientBcc = recipientBcc;
   }
   public String[] getRecipientCc() {
      return recipientCc;
   }
   public void setRecipientCc(String[] recipientCc) {
      this.recipientCc = recipientCc;
   }
   public String[] getRecipientTo() {
      return recipientTo;
   }
   public void setRecipientTo(String[] recipientTo) {
      this.recipientTo = recipientTo;
   }
   public String getSenderFrom() {
      return senderFrom;
   }
   public void setSenderFrom(String senderFrom) {
      this.senderFrom = senderFrom;
   }
   public String getSmtpHost() {
      return smtpHost;
   }
   public void setSmtpHost(String smtpHost) {
      this.smtpHost = smtpHost;
   }
   public String getEmailAttachment() {
      return emailAttachment;
   }
   public void setEmailAttachment(String emailAttachment) {
      this.emailAttachment = emailAttachment;
   }
}



Related Posts Plugin for WordPress, Blogger...

Blog List