Java i18n Internationalization Example

Internationalization is the process of designing an application so that it can be adapted to various languages and regions without engineering changes.

Sometimes I was wondering term internationalization is abbreviated as i18n, Why? and Found reason is   there are 18 letters between the first "i" and the last "n." :)

Why to use i18n and Benifits of i18n :
  1. Support for new languages does not require recompilation as stored in Properties Files.
  2. Can be localized quicklyby setting Local as per Language and country
  3. Instead of hard coding Textual elemtns(GUI labels,status message,Error message. they are stored outside and retrieved dynamically.
  4. By small additional of data(properties file of different landuage) , same code can be run WorldWide.
  5. Culturally dependent data, like dates and currencies, appear in formats that line up with user's region and language

Viewing Content of Jar in Java

jar tvf <myjarfile>.jar - Display Verbose output

0 Mon Mar 28 01:49:30 IST 2011 META-INF/
 217 Mon Mar 28 01:49:28 IST 2011 META-INF/MANIFEST.MF
   0 Mon Mar 28 01:49:30 IST 2011 datamapping/
   0 Mon Mar 28 01:49:30 IST 2011 datamapping/Properties/
  777 Mon Mar 28 01:49:28 IST 2011 datamapping/DataMapping$1.class
  770 Mon Mar 28 01:49:28 IST 2011 datamapping/DataMapping$2.class
  553 Mon Mar 28 01:49:28 IST 2011 datamapping/DataMapping$3.class
16453 Mon Mar 28 01:49:28 IST 2011 datamapping/DataMapping.class
  553 Mon Mar 28 01:49:30 IST 2011 datamapping/DisplayData$1.class
 2331 Mon Mar 28 01:49:30 IST 2011 datamapping/DisplayData.class
 4938 Mon Mar 28 01:49:30 IST 2011 datamapping/Properties/Envproperties.properties

jar tf <myjarfile>.jar - This command displays the contents of the JAR file to stdout:

How to Create Jar in Java

jar cf  <jar-file>  <input-files>

Options :
c  - option indicates that you want to create a JAR file.

- option indicates that you want the output to go to a file rather than to stdout.

jar-file  - is the name that you want the resulting JAR file to have. You can use any filename for a JAR file. By convention, JAR filenames are given a .jar extension, though this is not required.

input-file(s) - is a space-separated list of one or more files that you want to be placed in your JAR file.
If any of the "input-files" are directories, the contents of those directories are added to the JAR archive recursively.

How to List Entries in Jar Files using Java Program

The JarFile class is used to read the contents of a JAR file.

Class JarFiles extends the class java.util.zip.ZipFile with support for reading an optional Manifest entry. The Manifest can be used to specify meta-information about the JAR file and its entries.

JarFiles has method called entries() which is used to returns an enumeration of the ZIP file entries. Using Enumeration, You can iterate over entries to list enteries in JarFiles

Retrieve Modifier Information using Java Reflection APIs

Java Reflection has API called getModifiers() which is used to get Modifier information of class. just create object of class and call getModifiers() method. Play with Modifier and it's methods.

Java Program to get Modifier Information using Java Reflection API:

System.out.println("Modifier Information - ");
List list = new ArrayList();
Class originalClassObj = list.getClass();
int modifier = originalClassObj.getModifiers();
if (Modifier.isPublic(modifier)) {
 System.out.println("public");
}
if (Modifier.isAbstract(modifier)) {
 System.out.println("abstract");
}
if (Modifier.isFinal(modifier)) {
 System.out.println("final");
}
Output :

Modifier Information - 
public


Retrieve Constructor Information of class using Java Reflection APIs

In order to retrieve Constructor information, just create object of class and call
getConstructors() api.

Java Program to retrieve Constructor Information using Java Reflection API :

Constructor[] constructor = originalClassObj.getConstructors();
System.out.println("Constructor used - ");
for (int i = 0; i < constructor.length; i++) {
    System.out.println(constructor[i].getName());
}


Retrieve Fields Information of class using java Reflection APIs

Using Java Reflecion APIs you can get fields information of class easily. just create object of class and get fields using getFields();

Java Program to retrieve fields information using java Reflection Apis :
Field[] fields = originalClassObj.getFields();
System.out.println("Fields used - ");
for (int i = 0; i < fields.length; i++) {
    System.out.println(fields[i].getName());
}


Retrieve SuperClass information using Java Reflection API

Using Java Reflection APIs you can retrieve superClass name, it's simple name,packagename, implemented interfaces and many more.

Key points to retrieve SuperClass Information :
  1. Create Object of class which has super class
  2. Get SuperClass using getSuperClass()
  3. Get SuperClass name using getName()
  4. Get SuperClass simple name using getSimpleName().
  5. Get SuperClass PackageName using getPackage()
  6. Get interfaces using getInterfaces()

Retrieve Methods Information of Class using Java Reflection API

    Using Java Reflection API, It's easy to get all methods information of class.

    Key points to retrieve Methods information of class :
    1. Create Object of Class
    2. Retrieve all methods of class in Method[] array using getMethods()
    3. Get Method name using getName()
    4. Get Return Type of method using getReturnType()
    5. Get all parameter of method using getParameterTypes()

    How to check Number is Palindrome number or not using Java

    Number is called Palindrome number if original number and reverse of original number are same.
    ex. 46364. Just reverse the number and compare it with original number. that's it

    Java Program to check number is palindrome or not :

    package com.anuj.algorithms;
    
    /**
     *
     * @author Anuj Patel
     */
    public class Palindrom {
    
        protected void checkPalindrom(int num) {
            int reverse = 0;
            int original = num;
    
            for (int i = 0; i <= num; i++) {
                int rand = num % 10;
                num = num / 10;
                reverse = reverse * 10 + rand;
            }
            System.out.println("Original Number is - " + original);
            System.out.println("Reverse Number is - " + reverse);
    
            if (reverse == original) {
                System.out.println("number is Palindrom\n");
            } else {
                System.out.println("number is not palindrom\n");
            }
        }
    
        public static void main(String[] args) {
            Palindrom palindrom = new Palindrom();
            //palindrom.checkPalindrom(46361);
            palindrom.checkPalindrom(46364);
        }
    }
    

    Output :
    Original Number is - 46361
    Reverse Number is - 16364
    number is not palindrom

    Original Number is - 46364
    Reverse Number is - 46364
    number is Palindrom

    How to Check Number is ArmStrong or not using Java

    Number is called as ArmStrong number if sum of each digits's cube is equal to original number.

    Ex. 153 = (1*1*1) + (5*5*5) + (3*3*3)

    Please follow below Steps to check if number is armstring number or not using java : 

    1. Take Reminder of number
    2.  Cube the reminder and add it to Sum
    3.  Retrieve pending number to be evaluate and set it to Number
    4.  Perform above checks until number is greater than 0.

    Retrieve Implemented Interfaces using Java Reflection API

    Consider that i have some java class and i want to get all interfaces which my class implements and want to list all those interfaces.How can i retrieve information about all implemented interfaces information using Java Reflection API, have a look at below :

    I have create object such as List list = new ArrayList(); and we will retrieve all implemented information using java relection API.

    We already know ArrayList Heirarchy as :
    public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, Serializable

    Java Program to retrieve Implemented Interfaces :

    List list = new ArrayList();
    Class originalClass = list.getClass();        
    
    //retrieve implemeted interfaces
    Class[] ointerfaces = originalClass.getInterfaces();
    System.out.println("\nImplemented Interfaces - ");
    for (int i = 0; i < ointerfaces.length; i++) {
     if (ointerfaces[i].isInterface()) {
      System.out.println(ointerfaces[i].getName() + " is interface");
     } else {
      System.out.println(ointerfaces[i].getName() + " is Class");
     }
    }
    Output :
    Implemented Interfaces - 
    java.util.List is interface
    java.util.RandomAccess is interface
    java.lang.Cloneable is interface
    java.io.Serializable is interface 
    


    Retrieve Class Information using Java Reflection API

    Reflection API should be used by developers who has strong understanding of language fundamentals.

    Using Reflection APIs , you can

    1. Retrieve Class Information
    2. Retrieve Implemented Interfaces
    3. Retrieve Methods information used in Provided Class
    4. Retrieve Constructors information used in provided class
    5. Retrieve Fields information
    6. Retrieve SuperClass information of provided class
    7. Retrieve Modifier Information

    Here, i am just showing small java code for how you can retrieve class information. Please refer to this blogs for more examples of Java Reflections API explanation and java codes.

    Java Program :
    List list = new ArrayList();
    
    Class originalClass = list.getClass();        
    System.out.println("Original Class Information");
    System.out.println("ClassName - " + originalClass.getName());
    System.out.println("SimpleName -  " + originalClass.getSimpleName());
    System.out.println("PackageName - " + originalClass.getPackage());
    
    Output :
    Original Class Information
    ClassName - java.util.ArrayList
    SimpleName -  ArrayList
    PackageName - package java.util, Java Platform API Specification, version 1.7
    

    Sending Email using Spring MailSender and Gmail SMTP Server

    Spring provides interface called "MailSender" (org.springframework.mail.MailSender) to send mail.
    Developer can use MailSender method send(SimpleMailMessage simpleMessage)and pass SimpleMailMessage with From,To,Subject, and Text set.

    MailSender Documentation : MailSender
    SimpleMailMessage Documentation : SimpleMailMessage


    Java Program to send Mail using Spring MailSender :
    package com.anuj.spring.mail;
    
    import org.springframework.mail.MailSender;
    import org.springframework.mail.SimpleMailMessage;
    
    /**
     *
     * @author Anuj Patel
     */
    public class NotifyImpl {
        
        private MailSender mailsender;
        
        public MailSender getMailsender() {
            return mailsender;
        }
        
        public void setMailsender(MailSender mailsender) {
            this.mailsender = mailsender;
        }
        
        public void sendMail(String from, String to, String subject, String message) {
            SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
            simpleMailMessage.setFrom(from);
            simpleMailMessage.setTo(to);
            simpleMailMessage.setSubject(subject);
            simpleMailMessage.setText(message);
            
            mailsender.send(simpleMailMessage);
        }
    } 
    

    Spring - java.lang.ClassNotFoundException: org.aopalliance.aop.Advice

    Even after adding all Spring 3.1 jar i was getting excpetion as below :

    Exception in thread "main" org.springframework.beans.factory.CannotLoadBeanClassException:
    Caused by: java.lang.ClassNotFoundException: org.aopalliance.aop.Advice
        at java.net.URLClassLoader$1.run(Unknown Source)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.net.URLClassLoader.findClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        ... 49 more
       
    Solution :

    As part of https://jira.springsource.org/browse/SPR-2011, Removed AOP Alliance interfaces from spring-aop.jar and
    the aopalliance.jar needs to be added explicitly. Instead of using jar from any other sources, it's better to use jar from official maven repository.

    What is Maven and Why to use it?

    Apache Maven is a basically used for managing project's build, reporting and documentation. Maven is based on model which is called POM(Project Object Model).

    Consider example that you need to use log4j for your application for logging.

    In Usual way , you need to search,download and add log4j.jar into your project dependency and what if  upgraded version of log4.jar is available and you want to add into your project. You have to do this manually. Maven can assist you in order to overcome with this manual process.

    In Maven, you need to know "maven coordinates" for library you want to add into your project. Ex. coordinates for log4.j which you can find at Maven Central Repository

    Once you have groupId,artifactsId and version available then You should add following lines into your Project's pom.xml

    Maven Local,Central and Remote Repositories

    Maven repository is divided into 3 types :
    1. Maven local Repository
    2. Maven Central Repository
    3. Maven Remote Repository

    Maven local repository :  It' place where all project dependency libraries which are specified in project's pom.xml are stored here after downloaded by Maven
    Default to home directory is
      1. Unix/Mac OS X – ~/.m2 on 
      2. Windows – C:\Documents and Settings\.m2 on Windows
      This default location can be change by editing conf/setting.xml
      <!-- localRepository
         | The path to the local repository maven will use to store artifacts.
         |
         | Default: ~/.m2/repository
        <localRepository>/path/to/local/repo</localRepository>

      How to enable Proxy setting in Maven

      Considering that you have installed maven and environment variable M2_HOME is pointing to installation directory of Maven and %M2_MAVEN%/bin is appended to your environment variable %PATH%.

      Open setting.xml from %M2_HOME%/conf/settings.xml. 
      UnComment following code and add your Proxy Details.

      <proxies>

          <!-- proxy
           | Specification for one proxy, to be used in connecting to the network.
           |
          <proxy>
            <id>optional</id>
            <active>true</active>
            <protocol>http</protocol>
            <username>proxyuser</username>
            <password>proxypass</password>
            <host>proxy.host.net</host>
            <port>80</port>
            <nonProxyHosts>local.net|some.host.com</nonProxyHosts>
          </proxy>
          -->
        </proxies>

      Save file. Please note that no restart 

      How to load multiple Spring bean configuration file

      When you are working on large project where stracturized  folder structure is being used for Spring Beans configuration files ex. Spring-Core.xml in Core Folder, Spring-Common.xml in Common folder etc

      You may load multiple Spring bean configuration files in code :
      ApplicationContext context = 
           new ClassPathXmlApplicationContext(new String[] {"Spring-Core.xml",
                    "Spring-Common.xml"});

      This way is not properly organized.It will be better if we can import multiple xml into one xml and then define single main XML into ClassPathXmlApplicationContext
      Ex. 
      <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">    
             <import resource="common/Spring-Core.xml"/>  
            <import resource="connection/Spring-Common.xml"/> 
      </beans>

      Validate Numeric number in Java

      There are many situation where we require to validate numeric number while doing development. You can achieve it by writing regular expression and in corporate it into your code.

      Following example shows you, how to validate numeric number using java. A numeric number can start with + or - having digits at starting and there can be . in betwwen and ends with numeric digits.

      We have used regular expression as - ^[-+]?[0-9]*\\.?[0-9]+$ , where
      ^[-+]?: Starts with an optional "+" or "-" sign.
      [0-9]*: May have one or more digits.
       \\.? : May contain an optional "." (decimal point) character.
      [0-9]+$ : ends with numeric digit.

      Validate Phone number in Java

      If you are developing standalone java application or web application, there will be cases you come across where you require to validate phone numbers according to different formats.

       Phone number can have formats as (nnn)nnn-nnnn or nnnnnnnnnn or nnn-nnn-nnnn
      or as per your requirement :)

      Explanation to Regular expression  ^\\(?(\\d{3})\\)?[- ]?(\\d{3})[- ]?(\\d{4})$ is :
      1. ^\\(? - May start with an option "("
      2. (\\d{3}) - Followed by 3 digits
      3.  \\)? - May have an optional ")"
      4. [- ]? : May have an optional "-" after the first 3 digits or after optional ) character
      5. (\\d{3}): Followed by 3 digits
      6. [- ]? - May have another optional "-" after numeric digits
      7. (\\d{4})$ : ends with four digit

      Validate Email Address in Java

      While building any web application we sometimes required to write email validation in our validation helper classes. You can validate email address using following way. All you need is to just have regular expression to validate Email Address and Java's Patten and Matcher classes.

      Valid email addresses

      • niceandsimple@example.com
      • very.common@example.com
      • a.little.lengthy.but.fine@dept.example.com
      • disposable.style.email.with+symbol@example.com
      • user@[IPv6:2001:db8:1ff::a0b:dbd0]
      • "much.more unusual"@example.com
      • "very.unusual.@.unusual.com"@example.com
      • "very.(),:;<>[]\".VERY.\"very@\\ \"very\".unusual"@strange.example.com
      • 0@a
      • postbox@com (top-level domains are valid hostnames)
      • !#$%&'*+-/=?^_`{}|~@example.org
      • "()<>[]:,;@\\\"!#$%&'*+-/=?^_`{}| ~  ? ^_`{}|~.a"@example.org
      • ""@example.org

      Apache Maven Installation and Maven Configuration

      Maven : Apache Maven is a basically used for managing project's build, reporting and documentation. Maven is based on model which is called POM(Project Object Model).

      Installation :

      1. Download Maven from http://maven.apache.org/download.html eg.version Maven 3.0.4
      2. unzip into any Directory. ex. C:\Program Files\apache-maven-3.0.4(Windows) or /usr/local/apache-maven/apache-maven-3.0.4(Unix)
      3. Add Environment variable M2_HOME = <Installation dir without bin directory> or export M2_HOME = <path of installed without bin>
      4. append %M2_HOME%\bin into PATH Environment
      Unix : export M2=$M2_HOME/bin and export PATH=$M2:$PATH
      6. Optional – add the environment variable MAVEN_OPTS to specify JVM properties, e.g.
      Windows : MAVEN_OPTS = -Xms256m -Xmx512m
      Unix : export MAVEN_OPTS=”-Xms256m -Xmx512m”
      5. goto cmd and check Maven as : mvn -version

      Deep Dive into Spring Setter Injection

      Spring setter injection provide you to set value of different types of Data which you use while developing application. If you are not aware of Constructor or Setter Injection concept, please refer Spring Setter Injection and Constructor Injection before going through tutorial.

      I will show you how to use it Spring setter Injection for different types of data.somehow due to formatting String is displayed as string.please use String in your example.

      1. Create PropertyTest.java
      package com.anuj.spring.core.injection;
      
      import java.util.List;
      import java.util.Map;
      import java.util.Properties;
      import java.util.Set;
      
      /**
       *
       * @author Anuj J Patel
       */
      public class PropertyTest {
          
          private int intData;
          private double doubleData;
          private float floatData;
          private String stringData;
          private int[] intArr;
          private String[] stringArr;
          private List listdata;
          private Map map;
          private Properties properties;
          private Set setData;
      
          public PropertyTest() {
              System.out.println("Constructor Called");
          }
          
          @Override
          public String toString() {
              return "PropertyTest{" + "intData=" + intData + ", doubleData=" + doubleData + ", floatData=" + floatData + ", stringData=" + stringData + ", intArr=" + intArr + ", stringArr=" + stringArr + ", listdata=" + listdata + ", map=" + map + ", properties=" + properties + ", setData=" + setData + '}';
          }
          
          public double getDoubleData() {
              return doubleData;
          }
      
          public void setDoubleData(double doubleData) {
              this.doubleData = doubleData;
          }
      
          public float getFloatData() {
              return floatData;
          }
      
          public void setFloatData(float floatData) {
              this.floatData = floatData;
          }
      
          public int[] getIntArr() {
              return intArr;
          }
      
          public void setIntArr(int[] intArr) {
              this.intArr = intArr;
          }
      
          public int getIntData() {
              return intData;
          }
      
          public void setIntData(int intData) {
              this.intData = intData;
          }
      
          public List getListdata() {
              return listdata;
          }
      
          public void setListdata(List listdata) {
              this.listdata = listdata;
          }
      
          public Map getMap() {
              return map;
          }
      
          public void setMap(Map map) {
              this.map = map;
          }
      
          public Properties getProperties() {
              return properties;
          }
      
          public void setProperties(Properties properties) {
              this.properties = properties;
          }
      
          public Set getSetData() {
              return setData;
          }
      
          public void setSetData(Set setData) {
              this.setData = setData;
          }
      
          public String[] getStringArr() {
              return stringArr;
          }
      
          public void setStringArr(String[] stringArr) {
              this.stringArr = stringArr;
          }
      
          public String getStringData() {
              return stringData;
          }
      
          public void setStringData(String stringData) {
              this.stringData = stringData;
          }
      }
      

      Spring JdbcTemplate and Spring SimpleJdbcTemplate difference with Example

      To use the SimpleJdbcTemplate you need to use JDK 1.5 or higher. SimpleJdbcTemplate takes advantage of the Java 5 language features like varargs, autoboxing, generics and covariant returns.

      Following example shows you how to use SimpleJdbcTemplate and advantage of it over JdbcTemplate
      package com.anuj.spring.db;
      
      import java.sql.ResultSet;
      import java.sql.SQLException;
      import javax.sql.DataSource;
      import org.springframework.jdbc.core.simple.ParameterizedRowMapper;
      import org.springframework.jdbc.core.simple.SimpleJdbcTemplate;
      
      /**
       *
       * @author Anuj J Patel
       */
      public class ForumDAOSimpleJDBCImpl implements ForumDAO{
      
          /**
           * Simple JDBCTemplate
           * 1.When using SimpleJDBCTemplate there is no need to typecast from int to Integer
           * and you can pass variable length arguments instead of Object array
           * 2.There is no need to typecast return object, parameterizedRowMapper object's type parameter 
           * will be taken by default
           */
          private SimpleJdbcTemplate simpleJDBCTemplate;
          
          public void setDataSource(DataSource dataSource){
              this.simpleJDBCTemplate = new SimpleJdbcTemplate(dataSource);
          }
          
          @Override
          public void insert(Forum forum) {
              String query = "insert into tbforum(forumId,forumName,forumDesc) values(?,?,?)";
              simpleJDBCTemplate.update(query, forum.getForumId(),forum.getForumName(),forum.getForumDesc());
              System.out.println("Record Inserted successfully");
          }
      
          @Override
          public Forum selectForum(int forumId) {
              String query="select * from tbforum where forumId=?";
              
              return simpleJDBCTemplate.queryForObject(query, 
                      new ParameterizedRowMapper(){
                              @Override
                              public Forum mapRow(ResultSet rs, int rowNum) throws SQLException {
                                  return new Forum(rs.getInt("forumId"),rs.getString("forumName"), rs.getString("forumDesc"));
                              };               
                      },forumId);        
          }
          
      }
      

      JAX-RS Handling XML using JAXB Annotation

      In this tutorial, I will show you how to create an “user” object, convert it into XML file,
      and return it back to the client.

      Create an object, annotate with JAXB annotation to support XML file conversion.

      POJO Class with JAXB annotation :
      @XmlRootElement(name = "user")
      
      public class User {
      
       String username;
       String password;
       int pin;
      
       @XmlElement
       public String getUsername() {
        return username;
       }
      
       public void setUsername(String username) {
        this.username = username;
       }
      
       @XmlElement
       public String getPassword() {
        return password;
       }
      public void setPassword(String password) {
        this.password = password;
       }
      
       @XmlAttribute
       public int getPin() {
        return pin;
       }
      
       public void setPin(int pin) {
        this.pin = pin;
       }
      }
      


      Restful Service for XML in JAX-RS :
      To return a XML file, annotate the service method with @Produces("application/xml").
      import javax.ws.rs.GET;
      import javax.ws.rs.Path;
      import javax.ws.rs.Produces;
      
      @Path("/xml/user")
      public class XMLService {
      
       @GET
       @Path("/get")
       @Produces("application/xml")
       public User getUserInXML() {
      
        User user = new User();
        user.setUsername("anuj");
        user.setPassword("password");
        user.setPin(123456);
      
        return user;
      
       }
      
      }
      

      File Download in JAX-RS

      In JAX-RS, for user to download a file, annotate the method with @Produces("text/plain") :

      Put @Produces(“text/plain”) on service method, with a Response return type. It means the output is a text file.
      Set “Content-Disposition” in Response header to tell browser pop up a download box for user to download.

      Download File in JAX-RS :

      See a full example to download a text file in JAX-RS.

      import java.io.File;
      import javax.ws.rs.GET;
      import javax.ws.rs.Path;
      import javax.ws.rs.Produces;
      import javax.ws.rs.core.Response;
      import javax.ws.rs.core.Response.ResponseBuilder;
      
      
      @Path("/file")
      public class FileService {
      
       private static final String FILE_PATH = "c:\\file.log";
      
       @GET
       @Path("/get")
       @Produces("text/plain")
       public Response getFile() {
            File file = new File(FILE_PATH);
      
            ResponseBuilder response = Response.ok((Object) file);
            response.header("Content-Disposition","attachment; filename=\"file_from_server.log\"");
            return response.build();
        }
      
      }
      


      File Type :
      txt : @Produces("text/plain")
      image  : @Produces("image/png")
      pdf : @Produces("application/pdf")
      excel : @Produces("application/vnd.ms-excel")

      @HeaderParam Implementation in JAX-RS

      There are 2 ways to get HTTP request header in JAX-RS :
      Inject directly with @HeaderParam
      Pragmatically via @Context

      Implementation using @HeaderParam :

      In this example, it gets the browser “user-agent” from request header.

      @MatrixParam Implementation in JAX-RS

      In this tutorial , i will show usage of @MatrixParam. Matrix parameters are a set of “name=value” in URI path, for example, /books/2012;author=anuj
      In above URI, the matrix parameter is “author=anuj“, separate by a semi colon “;“.


      @MatrixParam example

      import javax.ws.rs.GET;
      import javax.ws.rs.MatrixParam;
      import javax.ws.rs.Path;
      import javax.ws.rs.PathParam;
      import javax.ws.rs.core.Response;
      
      
      @Path("/books")
      public class BookService {
      
       @GET
       @Path("{year}")
       public Response getBooks(@PathParam("year") String year,
         @MatrixParam("author") String author,
         @MatrixParam("country") String country) {
      
        return Response
         .status(200)
         .entity("getBooks is called, year : " + year
          + ", author : " + author + ", country : " + country)
         .build();
       }
      }
      

      Results :
      1. URI Pattern : “/books/2012/”
      getBooks is called, year : 2012, author : null, country : null
      2. URI Pattern : “/books/2012;author=anuj”
      getBooks is called, year : 2012, author : anuj, country : null
      3. URI Pattern : “/books/2012;author=anuj;country=usa”
      getBooks is called, year : 2012, author : anuj, country : usa
      4. URI Pattern : “/books/2012;country=usa;author=anuj”
      getBooks is called, year : 2012, author : anuj, country : usa

      Installing APK into Android Emulator/Devices

      Directing Commands to a Specific Emulator/Device Instance

      If multiple emulator/device instances are running, you need to specify a target instance when issuing adb commands. To so so, use the -s option in the commands. The usage for the -s option is:
      adb -s <serialNumber> <command> 
      As shown, you specify the target instance for a command using its adb-assigned serial number. You can use the devices command to obtain the serial numbers of running emulator/device instances.
      Here is an example:
      adb -s emulator-5556 install helloWorld.apk
      Note that, if you issue a command without specifying a target emulator/device instance using -s, adb generates an error.

      Installing an Application

      You can use adb to copy an application from your development computer and install it on an emulator/device instance. To do so, use the install command. With the command, you must specify the path to the .apk file that you want to install:
      adb install <path_to_apk>
      Note that, if you are using the Eclipse IDE and have the ADT plugin 
      installed, you do not need to use adb (or aapt) directly to install your
      application on the emulator/device. Instead, the ADT plugin handles the
      packaging and installation of the application for you. 

      Querying for Android Emulator/Device Instances

       Before issuing adb commands, it is helpful to know what emulator/device instances are connected to the adb server. You can generate a list of attached emulators/devices using the devices command:
      
      
      adb devices
      
      In response, adb prints this status information for each instance:
      • Serial number — A string created by adb to uniquely identify an emulator/device instance by its console port number. The format of the serial number is -. Here's an example serial number: emulator-5554
      • State — The connection state of the instance. Three states are supported:
        • offline — the instance is not connected to adb or is not responding.
        • device — the instance is now connected to the adb server. Note that this state does not imply that the Android system is fully booted and operational, since the instance connects to adb while the system is still booting. However, after boot-up, this is the normal operational state of an emulator/device instance.
      The output for each instance is formatted like this:
      [serialNumber] [state]

      Spring Setter Injection and Constructor Injection

      In this post i am going to demonstrate you how to set bean property using spring setter injection and constructor. First i will demonstrate Happy scenario and later will be complex. This will force you to think deeply about bean.xml

      Consider i have class User containing 3 property name,age and country. Using spring i want to display value of user with all it's property.

      User.java
      package com.anuj.spring.injection;
      /**
       *
       * @author Anuj J Patel
       *
       */
      public class User {
      
          private String name;
          private int age;
          private String country;
      
          public String getName() {
              return name;
          }
      
          public void setName(String name) {
              this.name = name;
          }
      
          public int getAge() {
              return age;
          }
      
          public void setAge(int age) {
              this.age = age;
          }
      
          public String getCountry() {
              return country;
          }
      
          public void setCountry(String country) {
              this.country = country;
          }
      
          public String toString()
          {
              String output = "Name : " + name + " Age: " + age + " Country:" + country;
              return output;
          }
      }