Monday 27 February 2012

Wednesday 22 February 2012

Command not found shell script

Problem: Every time I run my shell script "example.sh" it always gives me result "command not found". Though all the commands in script get executed, Still I get this message

Reason: The root cause for this problem is line ending characters represented different in Windows and Linux.

Solution: Convert the file format from Windows to Linux. You can use the command "dos2unix" that will convert line endings, etc from Windows to unix format. i.e. it strips \r (CR) from line endings to change them from \r\n (CR+LF) to \n (LF)
 
# dos2unix example.sh

If you are a java developer and using ant to build your code. You can use below ant task to convert file format from dos to unix.
 

Startup and Shutdown scripts for a java application

ProblemI have a java application that needs to run as a background process in Linux. The process needs to be started and shutdown with shell scripts.

Approach: We can use nohup utility in linux to run Java process in background. After starting the process write the process id into a file. kill the process during shutdown using process id.

Startup Script:
 
#Start java application as a background process
nohup java -jar app.jar &

#write the process id to file
echo $! > PID



Shutdown Script:
 
#kills the background  java process
kill -9   `cat PID`

#clean up the process ID file
rm -rf PID


 

Monday 20 February 2012

Shows all the files in a directory and its sub directories

Below java program traverse through directory and displays all the files in it.

 
 
package com.test;

import java.io.File;

/**
 * Shows all the files in a directory and its sub directories 
 * @author luckyacademy
 *
 */
public class ListFiles {
 public static void main(String[] args) {

  showFiles(new File("C:\\dell"));
 }

 /**
  * Recursively shows all the files.
  */
 private static void showFiles(File dirPath) {
  
  for (File file : dirPath.listFiles()) {
   if (file.isDirectory()){ //if it is directory, traverse the directory recursively  
    showFiles(file);
   } 
   System.out.println("file Name: " + file.getAbsolutePath());
  }
 }

}

Running Java process in background



nohup command in linux can be used to run java process in background. 

nohup is most often used to run commands in the background as daemons.

nohup is a POSIX command to ignore the HUP (hangup) signal, enabling the command to keep running after the user who issues the command has logged out. The HUP (hangup) signal is by convention the way a terminal warns depending processes of logout.


  Below command runs the java application in background.
 nohup java -jar sample.jar &

Sunday 19 February 2012

Reading properties file java

Reading properties file in java:

Properties file in java is a simple key value file where key and value is separated by  '='.

Below example reads properties files and displays all the elements in it.

Config.properties is a property file.
 
 
#configuration properties
#key=value
username=abc
password=123
PropertyReader reades the config.properties
 

package demo;

import java.io.FileInputStream;
import java.util.Properties;
/**
 * Reads properties file and display all the contents in it
 * @author luckyacademy
 *
 */
public class PropertyReader {
 public static void main(String[] args) throws Exception {
  
  //open input stream to properties file
  FileInputStream fin = new FileInputStream("config.properties");
  Properties pr = new Properties();
  
  // read properties file
  pr.load(fin);
  
  //read value for key username
  System.out.println("Reading value: " + pr.getProperty("username"));

  //display all properties in file.
  for(Object key:pr.keySet()){
   System.out.println("Key: "+key+ " Value: "+pr.getProperty((String)key));
  }
  
  //close the properties file
  fin.close();
 }
}

Sending mail using Java

Send Mail Using Java Mail API:

Following example demonstrates simply methodology to send mail using java mail api. Here the mail server is running on localhost and listening on port 19025.  Java Mail API uses SMTP protocol to send mails.

Generally mail servers are configured to listed on standard SMTP port 25. Here apache james mail server is listing on Port 19025.

 
package demo;

import java.util.Properties;

import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMessage.RecipientType;

/**
 * Send mail using SMTP Protocol
 * 
 * @author luckyacademy
 */
public class SendMailDemo {

 public static void main(String[] args) throws Exception {
  String from = "abc@gmail.com";
  String to = "contact@localhost";
  String subject = "Demo Subject";
  String body = "Demo Body";

  Properties props = new Properties();

  // mail server host name and port
  props.put("mail.smtp.host", "localhost");
  props.put("mail.smtp.port", "19025");

  // Get Session
  Session mailSession = Session.getDefaultInstance(props);

  // Create a message object
  Message simpleMessage = new MimeMessage(mailSession);

  InternetAddress fromAddress = new InternetAddress(from);
  InternetAddress toAddress = new InternetAddress(to);

  simpleMessage.setFrom(fromAddress);
  simpleMessage.setRecipient(RecipientType.TO, toAddress);
  simpleMessage.setSubject(subject);
  simpleMessage.setText(body);

  // Send Message
  Transport.send(simpleMessage);

 }

}

 

Friday 17 February 2012

Java Client Exchange Web Services - EWS

Following snippets explains you to write Java Clients that consumes Microsoft Exchange Web Services.

From Exchange Server 2010 Microsoft stopped WEBDAV support on exchange server.  Java Clients using WEBDAV needs to migrate to consume EWS to fetch mail, compose, send  emails ..etc 

Read five email items from inbox

package demo;

import java.net.URI;

import microsoft.exchange.webservices.data.ExchangeCredentials;
import microsoft.exchange.webservices.data.ExchangeService;
import microsoft.exchange.webservices.data.FindItemsResults;
import microsoft.exchange.webservices.data.Item;
import microsoft.exchange.webservices.data.ItemView;
import microsoft.exchange.webservices.data.WebCredentials;
import microsoft.exchange.webservices.data.WellKnownFolderName;

public class EWSDemo {
 public static void main(String[] args) throws Exception {
  ExchangeService service = new ExchangeService();
  // Provide Crendentials
  ExchangeCredentials credentials = new WebCredentials("username", "password");
  service.setCredentials(credentials);

  // Set Exchange WebSevice URL
  service.setUrl(new URI("https://myexchangehost/EWS/exchange.asmx"));

  // Get five items from mail box
  ItemView view = new ItemView(5);

  // Search Inbox
  FindItemsResults findResults = service.findItems(WellKnownFolderName.Inbox, view);

  // iterate thru items
  for (Item item : findResults.getItems()) {
   System.out.println(item.getSubject());
  }

 }
} 
Reading Body 

 
item.getBody()
 Reading body using the method item.getBody() it yields to exception
 
Exception in thread "main" microsoft.exchange.webservices.data.ServiceObjectPropertyException: You must load or assign this property before you can read its value.
To overcome it first the body needs to be loaded.
item.load();
Reading Non default mail box
Some time it is possible for single user to have multiple mail boxes. Following snippet shows you to access non default mail box for eg sysadmin@abc.com
Mailbox mb = new Mailbox();
mb.setAddress("syadmin@abc.com");
FolderId folderId = new FolderId(WellKnownFolderName.Inbox, mb);
  
// Search Inbox syadmin@abc.com
FindItemsResults findResults = service.findItems( folderId, view);
Reading UnRead Emails
  // Get five items from mail box
  ItemView view = new ItemView(5);
  
  //Set Filter to Read UnRead emails
  SearchFilter itemFilter = new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, true);
  // Search Inbox
  FindItemsResults findResults = service.findItems(WellKnownFolderName.Inbox,itemFilter,view);

  // iterate thru items
  for (Item item : findResults.getItems()) {
     System.out.println(item.getSubject());
  }

Marking mail as read
// iterate thru items
  for (Item item : findResults.getItems()) {
   //Type cast it to EmailMessage
   EmailMessage em = (EmailMessage) item;
   em.setIsRead(true);
   em.update(ConflictResolutionMode.AlwaysOverwrite);
   System.out.println(em.getSubject());
  }
Reading mail Headers and body
// iterate thru items
  for (Item item : findResults.getItems()) {
   item.load();
   String subject=item.getSubject();
   //Read Body
   String body = MessageBody.getStringFromMessageBody(item.getBody());
   System.out.println(subject);
   System.out.println(body);
   //Reading Header
   InternetMessageHeaderCollection headers = item.getInternetMessageHeaders();
   for(InternetMessageHeader header:headers){
    System.out.println("Header Name: "+header.getName()+" Header Value: "+header.getValue() );
   }
  }