Thursday 29 November 2012

Updating artifact in remote maven repository

Problem: I have to updated "liferay-portal-6.0.6.zip" artifact in remote maven repository.

Solution:

  1. Provide remote repository access setting in settings.xml for example
    1. Edit file C:\Users\dragonadmin\.m2\settings.xml
    2. Provide server info

    3. 
                        
                            remote-repository
                            admin
                            *****
                          
      
      
  2. Execute below command on terminal to update the artifcat.

    1.  
      mvn deploy:deploy-file -DgroupId=com.liferay -DartifactId=liferay-portal -Dversion=6.0.6 -Dpackaging=zip -Dfile=C:/work/liferay-portal-6.0.6.zip  -Durl=http://dragon.home.com:8081/artifactory/maven-proxy -DrepositoryId=remote-repository
      

Thursday 1 November 2012

Free ports in Linux

Problem: Want to find free ports in Linux. 
Solution:  You can use  nc (or netcat) utility to do port scanning and find out free ports in the system.
Example:
Below command list ports that are binded from 1-10000

 
[root@dragon ~]# nc -z localhost 1-10000
Connection to localhost 22 port [tcp/ssh] succeeded!
Connection to localhost 25 port [tcp/smtp] succeeded!
Connection to localhost 111 port [tcp/sunrpc] succeeded!
Connection to localhost 631 port [tcp/ipp] succeeded!
Connection to localhost 925 port [tcp/*] succeeded!
Connection to localhost 2207 port [tcp/*] succeeded!
Connection to localhost 2208 port [tcp/*] succeeded!
Connection to localhost 4105 port [tcp/*] succeeded!
Connection to localhost 4728 port [tcp/*] succeeded!
Connection to localhost 5222 port [tcp/xmpp-client] succeeded!
Connection to localhost 5229 port [tcp/*] succeeded!
Connection to localhost 5269 port [tcp/xmpp-server] succeeded!
Connection to localhost 7005 port [tcp/afs3-volser] succeeded!
Connection to localhost 7070 port [tcp/arcp] succeeded!
Connection to localhost 7080 port [tcp/*] succeeded!
Connection to localhost 7777 port [tcp/cbt] succeeded!
Connection to localhost 8005 port [tcp/*] succeeded!
Connection to localhost 8009 port [tcp/*] succeeded!
Connection to localhost 8010 port [tcp/*] succeeded!
Connection to localhost 8080 port [tcp/webcache] succeeded!
Connection to localhost 8222 port [tcp/*] succeeded!
Connection to localhost 8223 port [tcp/*] succeeded!
Connection to localhost 8224 port [tcp/*] succeeded!
Connection to localhost 8225 port [tcp/*] succeeded!
Connection to localhost 9005 port [tcp/*] succeeded!
Connection to localhost 9009 port [tcp/pichat] succeeded!
Connection to localhost 9080 port [tcp/glrpc] succeeded!
Connection to localhost 9090 port [tcp/websm] succeeded!

Tuesday 30 October 2012

Finding RAM Size in Linux

Problem: Finding RAM size in Red Hat Linux
Solution: 
Top command gives you the RAM size
 
[root@dragon~]# top
top - 00:03:46 up 15:52,  1 user,  load average: 0.00, 0.00, 0.00
Tasks:  96 total,   2 running,  94 sleeping,   0 stopped,   0 zombie
Cpu(s):  0.0%us,  0.3%sy,  0.0%ni, 99.7%id,  0.0%wa,  0.0%hi,  0.0%si,  0.0%st
Mem:   4044540k total,   688452k used,  3356088k free,   137140k buffers
Swap:  2064376k total,        0k used,  2064376k free,   380340k cached

  PID USER      PR  NI  VIRT  RES  SHR S %CPU %MEM    TIME+  COMMAND
 8289 root      15   0 12740 1068  808 R  0.3  0.0   0:00.03 top
    1 root      15   0 10348  684  572 S  0.0  0.0   0:00.97 init

Check in the meminfo file.
[root@dragon~]#  cat /proc/meminfo
MemTotal:      4044540 kB
MemFree:       3356088 kB
Buffers:        137140 kB
Cached:         380348 kB
SwapCached:          0 kB
Active:         308108 kB
Inactive:       312956 kB
HighTotal:           0 kB
HighFree:            0 kB
LowTotal:      4044540 kB
LowFree:       3356088 kB
SwapTotal:     2064376 kB
SwapFree:      2064376 kB
Dirty:              28 kB
Writeback:           0 kB

 

Getting all the assets related to a category Liferay

Problem: Want to list all the assets related to a category.
Solution: Below template takes category name as parameter in the URL and lists all the assets that relates to provided category


#set ($current_url = $request.get("attributes").CURRENT_COMPLETE_URL)
#set ($paramName='categoryName')
#set ($catName = $httpUtil.getParameter($current_url, $paramName))
#set ( $AssetCategoryLocalService = $serviceLocator.findService( "com.liferay.portlet.asset.service.AssetCategoryLocalService" ))
#set ( $CatListDQ = $AssetCategoryLocalService.getCategories() )
#foreach( $catItem in $CatListDQ )
    #if($catItem.getName()==$catName)
     #set ( $catId=$catItem.getCategoryId())
    #end
#end
#set ( $assetEntryQuery = $portal.getClass().forName( "com.liferay.portlet.asset.service.persistence.AssetEntryQuery" ).newInstance()) 
#set ( $V = $assetEntryQuery.setAllCategoryIds( $catId))
#set ( $acsUtil = $portal.getClass().forName( "com.liferay.portlet.asset.service.AssetEntryLocalServiceUtil" ).newInstance()) 
#set ( $AssetEntryList = $acsUtil.getEntries( $assetEntryQuery ))
#foreach( $asset in $AssetEntryList )
$asset.getTitle() 
#end

Sunday 21 October 2012

Web Content Display portlet to display article dynamically - Liferay

Problem: I want to use web content display portlet to display articles dynamically  (i.e) I will pass article-id as an argument to page and web content display portlet has to read the article-id and display the content.

Solution: 
The above problem can be solved by creating an template. Have the below script in your template.
Sample URL for page would be http://localhost:8080/web/carlovers/dynamic-page?articleId=10712
 
## Get Article Id from the request URL
#set ($current_url = $request.get("attributes").CURRENT_COMPLETE_URL)
#set ($paramName='articleId')
#set ($articleId = $httpUtil.getParameter($current_url, $paramName))
#set ($journalArticleLocalService = $serviceLocator.findService("com.liferay.portlet.journal.service.JournalArticleLocalService"))
## Get article based on article id
#set ($article = $journalArticleLocalService.getArticle($getterUtil.getLong($request.theme-display.scope-group-id),$articleId))

## display relavent information
$article.getUrlTitle()
$article.getContentByLocale($request.theme-display.language-id)



Setting browser title as article title - Liferay

Problem:  I want to set web content title (article title) as browser title in liferay.

Solution: Create a template for your web content and you can use predefined velocity variables like "$reserved-article-title.data" to get the title of the article that is currently displayed. Set the title to document.title

Example:
 



Monday 15 October 2012

Reading URL Parameters in Liferay template

Problem: Reading URL parameters that are passed to a page in web content display portlet.

Solution: Create a template for your web content and read url parameters in the template.

#set ($current_url = $request.get("attributes").CURRENT_COMPLETE_URL)
#set ($paramName='articleId')
#set ($articleId = $httpUtil.getParameter($current_url, $paramName))

In the above code we are trying to read url paramter articleId. Example URL is http://localhost:8080/web/carlovers/myhome?articleId=10740

Wednesday 22 August 2012

Java coding best practices

Following are the java programming best practices. 

1) Javadoc comments should be added to the class as well as the methods.
2) Unused member variables should not be present in the classes.
3) Proper catch blocks should be added for exception handling instead of single Exception object handler.
4) Proper naming conventions should be used for variables, method and class names.
5) Instead of using hard coded strings, constants should be declared in a separate Constants class.
6) All database and file handlers should be properly closed when there is no further need for them.
7) No trailing spaces should be present in code lines.
8) Uniform coding standards for braces, loops, if-else, switch should be used across the application.
9) If similar logic is being used at multiple places then it should be declared in a helper class and called from multiple places.
10) A single method should not exceed 100 lines of code as it becomes difficult to maintain beyond that.
Split a single big method into multiple smaller methods.
11) Usage of API classes and methods should be encouraged instead of writing custom code for performing the same operations.
12) A single statement should not go beyond the viewable area of the editor or IDE and should be split across multiple lines.
13) Extra emphasis should be given on writing the unit test cases for the code which is going to be released.
14) The addition of any piece of code should not break existing functionality.
15) Usually a single database transaction can be done by writing the SQL query in multiple ways and there is a huge
difference in the performance of database transactions depending upon the way in which SQL query is written.
16) If a class has many member variables and the instance of that class can be initialized by initializing
only a partial number of variables then it is better to have static factory methods for initializing the
member variables instead of overloading the constructors.
17) Creating immutable class should be encouraged than mutable classes.
18) The best way to check if the String object is neither null nor empty string is to use the following code: if(“”.equals(str))
19) Add appropriate access specifiers to methods instead of marking all methods in a class as public.
20) Follow best practices suggested by any framework/library being used in the application like Spring, Struts, Hibernate, jQuery.
 

Thursday 9 August 2012

Unable to deploy portlet in Liferay

Problem: Unable to deploy portlet in Liferay Portal Server 6.1.0 CE. While deploying i am getting exceptions like "war does not support this version of Liferay" or " Add war to the blacklist"

 
com.liferay.portal.kernel.deploy.auto.AutoDeployException: sample-struts-portlet-6.1.0.1.war does not support this version of Liferay
 at com.liferay.portal.deploy.auto.PortletAutoDeployer.autoDeploy(PortletAutoDeployer.java:99)
 at com.liferay.portal.deploy.auto.PortletAutoDeployListener.deploy(PortletAutoDeployListener.java:78)
 at com.liferay.portal.kernel.deploy.auto.AutoDeployDir.processFile(AutoDeployDir.java:180)
 at com.liferay.portal.kernel.deploy.auto.AutoDeployDir.scanDirectory(AutoDeployDir.java:222)
 at com.liferay.portal.kernel.deploy.auto.AutoDeployScanner.run(AutoDeployScanner.java:50)
Caused by: com.liferay.portal.kernel.deploy.auto.AutoDeployException: sample-struts-portlet-6.1.0.1.war does not support this version of Liferay
 at com.liferay.portal.tools.deploy.BaseDeployer.deployFile(BaseDeployer.java:746)
 at com.liferay.portal.deploy.auto.PortletAutoDeployer.autoDeploy(PortletAutoDeployer.java:96)
 ... 4 more
06:08:32,312 INFO  [AutoDeployDir:203] Add sample-struts-portlet-6.1.0.1.war to the blacklist 


Root Cause: The portlet is build with higher version of SDK than the current version of portal server. (i.e) The portlet is built with 6.2 SDK and deployed in 6.1 Liferay portal server.

Solution:
 Edit the file  "liferay-plugins-sdk-6.1.0-ce\portlets\sample-struts-portlet\docroot\WEB-INF\liferay-plugin-package.properties" and update the poperty "liferay-versions" and redploy the portlet.

 
liferay-versions=6.1.0
 

Finding size of directory Linux

Problem: Finding size of folder or directory in Unix/Linux.
Solution: du (abbreviated from disk usage) is a standard Unix program used to estimate file space usage—space used under a particular directory or files on a file system.
Below command finds the size of home directory 
 
 
[root@dragon home]# du -sh .
3.7G    .

Monday 30 July 2012

Finding disk space in Linux

Problem: Finding disk space in Linux.
Solution:  We can use command df to find the disk space.
 
[root@dragon ~]# df -h
Filesystem            Size  Used Avail Use% Mounted on
/dev/vg_root          29G   11G  17G   38%  /
tmpfs                 504M  88K  504M  1%   /dev/shm
/dev/sda1             485M  44M  416M  10%  /boot
/dev/lv_home          29G   448M 27G   2%   /home
 

Tuesday 24 July 2012

Finding files in linux

Problem: Finding or Searching files in Linux
Solution: In Linux or Unix you can use find command to find files. Find command will search for the files in current working directory and its subdirectories as well.


  1. To find a file named install.log
     
    [root@dragon ~]# find -name install.log
    ./install.log
    
  2.  To find all files that starts with ins (i.e) ins*
     
    [root@dragon ~]# find -name ins\*
    ./install.log
    ./install.log.syslog
    ./vmware-tools-distrib/installer
    ./vmware-tools-distrib/etc/installer.sh
    

Sunday 22 July 2012

Finding java version

Problem: How to find java version.
Solution: If you have java installed on your machine and it is in system path. -version option gives you the information about Java running on your machine.

 
[root@myworkstation ~]# java -version
java version "1.6.0_20"
OpenJDK Runtime Environment (IcedTea6 1.9.7) (rhel-1.39.1.9.7.el6-i386)
OpenJDK Client VM (build 19.0-b09, mixed mode)
 

Monday 16 July 2012

Finding MySQL Server version

Problem: How to find version of MySQL server.
Solution: You can find out version information using version variables. 

Login to mysql server and fire the below statement
 
 
mysql> SHOW VARIABLES LIKE "%version%";

Sample Result:
 
+-------------------------+---------------------+
| Variable_name           | Value               |
+-------------------------+---------------------+
| protocol_version        | 10                  |
| version                 | 5.1.52              |
| version_comment         | Source distribution |
| version_compile_machine | x86_64              |
| version_compile_os      | redhat-linux-gnu    |
+-------------------------+---------------------+

Thursday 12 July 2012

Using beyond compare script to generate difference report

Beyond Compare has support for command line script options.

Step1: Create a Script file.
          Type the below contents and save it into file "BCScript.txt"
 
file-report layout:side-by-side  options:display-all,line-numbers   output-options:html-color output-to:%3 %1 %2


Step2 : Run the script file.
 
bc2.exe @BCScript.txt a.java b.java diffreport.html

Thursday 5 July 2012

Knowing Red Hat Linux release details

Problem: Find Red Hat Linux version details
Solution:   /etc/redhat-release contains version details of Red Hat Linux

#cat /etc/redhat-release

#uname -a

Monday 2 July 2012

Couldn’t connect to liferay HSQL database

Problem: When I am trying to connect to default database used by Liferay. I am getting an exception “HSQLDB-In memory: The database is already in use by another process: lockFile: org.hsqldb.persist.LockFile@ca3f17a1”

Solution:
  • Open the properties file C:\demo\liferay-portal-6.0.6\data\hsql\lportal.properties
  • Change the value of “hsqldb.lock_file” to “false
  • Restart the liferay tomcat server

Info:
  • JDBC URL = jdbc:hsqldb:file:/C:/demo/liferay-portal-6.0.6/data/hsql/lportal
  • UserName=sa
  • Password=
  • Password is empty

Remove duplicate element in list - Java

Problem: Remove duplicate element in the list
Solution: Use set as flag to remove duplicate elements in the list
 
package com.lac;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

/**
 * Employee bean
 */
class Employee {
 private int id;
 private String name;

 public Employee(int id, String name) {
  super();
  this.id = id;
  this.name = name;
 }

 public int getId() {
  return id;
 }

 public void setId(int id) {
  this.id = id;
 }

 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }

}

/**
 * Remove Duplicates in list
 * 
 */
public class RemoveDuplicates {
 public static void main(String[] args) {
  //Create Employee objects
  Employee a= new Employee(1, "Jhon");
  Employee b= new Employee(2, "Jane");
  Employee c= new Employee(3, "King");
  
  List list= new ArrayList();
  list.add(a);list.add(b);list.add(c); //add employees
  list.add(b);//add duplicate employee
  
  final Set empIds= new HashSet();//flag that keeps employee ids
  
  for(Iterator it=list.listIterator();it.hasNext();){
   Employee emp=it.next();
   if(empIds.add(emp.getId())==false){//if found duplicate remove from the list
    it.remove();
   }
  }
  
  for(Employee emp:list){
   System.out.println(emp.getId());
   System.out.println(emp.getName());
  }
  
 }

}

Friday 22 June 2012

Convert Object array to Primitive array vice versa

Problem: Convert Object array to Primitive array vice versa.
Solution: ArrayUtils in apache commons lang can be used to do the same.



 
package com.lac;

import org.apache.commons.lang.ArrayUtils;

public class Conversion {
 public static void main(String[] args) {
  int i[] = new int[] { 1, 2, 3, 4 };
  
  // Convert Primitive int array to Object Integer Array
  Integer obj[] = ArrayUtils.toObject(i);

  // Convert Object array to Primitive array
  i = ArrayUtils.toPrimitive(obj);

 }
}

Tuesday 8 May 2012

Core Java Interview Questions -Language Fundamentals

Question:What is the out of below program? 


package com.lac.faq;

class A {
 public int i;
}

public class ParamPassDemo {
 public static void main(String[] args) {
  A a =new A();//Create an object of A
  a.i=10;
  change(a);
  a=null;
  System.out.println(a.i); //Guess result of print statement
 }
 private static void change(A a){
  a=null; //assign null
 }
 
}
Answer: The out put of the above program is 10. Most of us think the out put can be "java.lang.NullPointerException" but it is not because Objects in java are passed by copy of reference. When 'a' is passed to function 'change' the copy of reference 'a' is passed, so making the copied reference 'null' doesn't have any impact.


Question: Determine the Output of below program?

package com.lac.faq;

public class MyString extends String {
 public static void main(String[] args) {
  MyString s1="abc",s2="xyz";
  System.out.println(s1+s2);
  
 }

}
Answer: Compilation Error "MyString.java:3: cannot inherit from final java.lang.String"
Explanation: String class is a final class and it is not possible to inherit from a final class.

Table creation time MySQL

Problem: To find table creation/modified time in a given database.

Solution: MySQL maintains table level audit information in data base 'information_schema' and in table 'TABLES' 

Below Query fetches information about table 'foo'

select * from information_schema.TABLES where TABLE_NAME='foo'



Wednesday 2 May 2012

Disabling portlet icons in Liferay

Problem:  Want to remove portlet icons like minimize, maximize, delete ..etc for all the portlets in liferay.  In some cases we dont want end user to delete or resize the deployed portlets. These operations should be done by only super admin/Omni admin/portal admin. In such case modify the portlet.vm to restrict these operations to only portal admin.

 Default icons for the tag cloud portlet.

 
 

Solution:  Edit portlet.vm and provide access to only portal admin.
 
 

   #if ($portlet_display.isShowBackIcon())
    #language("return-to-full-page")
   #else
   #if ($permissionChecker.isOmniadmin())
    $theme.iconOptions()
    $theme.iconClose()
    $theme.iconMinimize()
    $theme.iconMaximize()
   #end
   #end
  

Tuesday 1 May 2012

Reading environment variable in Java

Following example helps to read environment variable.
 
 
package com.lac.demo;

public class ReadEnv {
 public static void main(String[] args) {
  //Reads environment variable PATH
  String value=System.getenv("PATH");
  System.out.println(value);
 }
}

Click here to download source from www.luckyacademy.com

Tuesday 17 April 2012

Reading file in classpath

Problem: Below code shows how to read a file in classpath. The file can be in jar file or in physical file system.

Solution: We can use "java.lang.Class.getResourceAsStream(String name)" to read file
 
 
package com.lac;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * Reads file in the class path
 * 
 * @author lac
 */
public class ReadFile {
 public static void main(String[] args) throws IOException {

  //Read Demo.txt from class path. The file Demo.txt is in package com.lac
  InputStream is = ReadFile.class.getResourceAsStream("/com/lac/Demo.txt");
  InputStreamReader isr = new InputStreamReader(is);
  BufferedReader br = new BufferedReader(isr);
  String fileContent = "";
  StringBuilder data = new StringBuilder();

  while ((fileContent = br.readLine()) != null) {
   data = data.append(fileContent);
  }
  is.close();

  System.out.println(data);
 }

}

Wednesday 11 April 2012

Jersey 1.8 and Spring 3.0 Integration Problem

When I am trying to integrate Jersey 1.8 with Spring 3.0.5. The integration use to fail with below exception
 
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.scheduling.annotation.internalAsyncAnnotationProcessor': Invocation of init method failed; nested exception is java.lang.NoClassDefFoundError: org/springframework/aop/interceptor/AsyncExecutionInterceptor

java.lang.ClassNotFoundException: org.springframework.aop.interceptor.AsyncExecutionInterceptor
 
Reason: The reason for this problem is. Jersey spring integration library "jersey-spring" is downloading older version of aop "spring-aop-2.5.6.SEC03.jar". If you exclude it. The problem should be solved.
Solution: Update the pom.xml to exclude the dependency "spring-aop"

  org.springframework
  spring-aop


Now Dependency section should look like.

   com.sun.jersey.contribs
   jersey-spring
   1.8
   
    
     org.springframework
     spring
    
    
     org.springframework
     spring-core
    
    
     org.springframework
     spring-web
    
    
     org.springframework
     spring-beans
    
    
     org.springframework
     spring-context
    
    
     org.springframework
     spring-aop
     
   
  

Thursday 5 April 2012

Generating Random Bytes using Java

 Below example explains to generate Random bytes.  We can use "java.util.Random" or "java.security.SecureRandom" to generate Random Bytes.

package demo;

import java.security.SecureRandom;
import java.util.Arrays;
import java.util.Random;

public class RandomByte {

 public static void main(String[] args) {
  System.out.println(Arrays.toString(getRandomByteArray(256)));
  
  //SecureRandom is a  bit costlier object. 
  SecureRandom random= new SecureRandom();
  System.out.println(Arrays.toString(random.generateSeed(256)));
  
 }
 public static byte[] getRandomByteArray(int size){
  byte[] result= new byte[size];
  Random random= new Random();
  random.nextBytes(result);
  return result;
 }
}

 

Wednesday 7 March 2012

Running tomcat on specific ip address

Problem:   Want to run tomcat on specific ip address on a host. If your system has multiple ipaddress and want to run tomcat on ip address 10.20.30.40. Follow below procedure

Solution: 

Edit tomcat/conf/server.xml and set ipaddress as value to attribure "address"

 
 
 

Tuesday 6 March 2012

Unable to install software in ubuntu 11.10

Problem: Unable to install software using Ubuntu Software Center in Ubuntu 11.10. It always throws error "Failed to download package files, Check your Internet connection "

Solution:
Run following command on terminal. This should solve the issue.
 
 sudo apt-get update 

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() );
   }
  }