Tuesday 11 March 2014

ANT - Build Script to run JAR file

Build.xml to run a JAR file
<project name="MyProject" default="all" basedir=".">
    <property name="jarfile" value="Sample.jar" description="JAR Folder" />
    <target name="runJar" description="execute jar">
        <java jar="${jarfile}.jar" fork="true"/>
    </target>
    <target name="all" depends="runJar">
        <echo message="Build complete." />
    </target>
 </project>
Build.xml to run a JAR file which has arguments
<project name="MyProject" default="all" basedir=".">
    <property name="jarfile" value="Sample.jar" description="JAR Folder" />
    <target name="runJar" description="execute jar">
        <java jar="${jarfile}.jar" fork="true">
            <!-- Pass Arguments Here -->
            <arg line="${arg1}"/>
            <arg line="${arg2}"/>
        </java>
    </target>
    <target name="all" depends="runJar">
        <echo message="Build complete." />
    </target>
</project>

ANT - Build.xml to detect Operating System

Build.xml
<project name="MyProject" default="main">
   <target name="main" description="execute commands depending on OS">
       <condition property="isUnix">
          <os family="unix" />
       </condition>
       <condition property="isWindows">
          <os family="windows" />
       </condition>
       <antcall target="setUnixEnv" />
       <antcall target="setWindowsEnv" />
   </target>
 
   <target name="setUnixEnv" if="isUnix">
       <echo>This is an Unix machine.</echo>  
       <!-- Put your Logic here . An example is shown below-->
       <exec executable="sh">
          <arg value="-c" />
          <arg value="chmod 777 file.js" />
       </exec>
   </target>
 
   <target name="setWindowsEnv" if="isWindows">
       <echo>This is a Windows machine.</echo>
       <!-- Put your Logic here . An example is shown below-->
       <exec executable="cmd">
          <arg value="/c"/>
          <arg value="ipconfig"/>
       </exec>
   </target>
</project>

  

Monday 10 March 2014

File Reading in Java

File Reading will be a part of any project or application.
Depending on the requirements, there may be need to either read the file line by line or character by character or word by word.
The below program has three methods which can perform each task separately.
Grab your method and start Coding!!!

Program

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;

/**
 * This program is used to play around with different methods of File Reading
 * @author Nijin Vinodan
 *
 */
public class FilesReader {
                /**
                 * This method is used to read file line by line
                 * @param fileName
                 */
                public void readFileLineByLine(String fileName){
                                try{
                                                FileInputStream fstream = new FileInputStream(fileName);
                                                DataInputStream in = new DataInputStream(fstream);
                                                BufferedReader br = new BufferedReader(new InputStreamReader(in));
                                                String strLine;
                                                while ((strLine = br.readLine()) != null){
                                                                System.out.println(strLine);
                                                }
                                                in.close();
                                }
                                catch(FileNotFoundException e){}
                                catch(IOException e){}
                }
               
                /**
                 * This method is used to read file character by character
                 * @param fileName
                 */
                public void readFileLetterbyLetter(String fileName){
                                FileInputStream fileInput;
                                try {
                                                fileInput = new FileInputStream(fileName);
                                                int read;
                                                while ((read = fileInput.read()) != -1) {
                                                   char c = (char) read;
                                                   System.out.println(c);
                                                }
                                                fileInput.close();
                                }
                                catch (FileNotFoundException e) {}
                                catch (IOException e) {}
                }
               
                /**
                 * This method is used to read file word by word
                 * @param fileName
                 */
                public void readFileWordByWord(String fileName){
                                File file = new File(fileName);
                                try {
                                                Scanner scanInput = new Scanner(new FileReader(file));
                                                while(scanInput.hasNext()){
                                                                System.out.println(scanInput.next());
                                                }
                                                scanInput.close();
                                }
                                catch (FileNotFoundException e) {}
                }
}

Monday 28 October 2013

Developing Restful Web services Using IBM JAX-RS

Java™ API for RESTful Web Services (JAX-RS) is a programming model that provides a mechanism for developing services that follow Representational State Transfer (REST) principles. Using JAX-RS, development of RESTful services is simplified.

The IBM® implementation of JAX-RS provides an implementation of the JAX-RS specification.

IBM JAX-RS includes the following features:
  1. JAX-RS server runtime
  2. Standalone client API with the option to use Apache HttpClient 4.0 as the underlying client
  3. Built-in entity provider support for JSON4J
  4. An Atom JAXB model in addition to Apache Abdera support
  5. Multipart content support
  6. A handler system to integrate user handlers into the processing of requests and responses
Required Jars:
  1. jsr311-api.jar
  2. commons-lang.jar
  3. slf4j-api.jar
  4. slf4j-jdk14.jar
  5. ibm-wink-jaxrs.jar

For Procedure & Detailed description Click Here

Wednesday 23 October 2013

Preventing Browser Back Navigation after Logout - JSPs




Modern Browsers cache the previously visited pages and hence in certain websites where authentication plays an important role, it is necessary to clear them.

The example below illustrates the scenario.



  • An user logs into his account with credentials.
  • He navigates between pages within the site.
  • Once he logs out, the session will terminate but since the browser had cached the previous pages, it is possible for him to click the Back button and see the previously visited pages.
  • This could possibly breach the security. To avoid this it is necessary to prevent Browser back navigation.


  • The code given below explains the same scenario.

    index.jsp
    <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
        pageEncoding="ISO-8859-1"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    <title>Insert title here</title>
    </head>
    <body>
     <%
        session= request.getSession();
        session.setAttribute("username", "login");
     %>
     <form action="login.jsp" method="post">
        Username <input type="text" name="uname"><br/>
        <input type="submit"/>
     </form>
    </body>
    </html>
      
    login.jsp
    <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
        pageEncoding="ISO-8859-1"%>
    <%
       response.setHeader("Cache-Control","no-cache");
       response.setHeader("Cache-Control","no-store");
       response.setHeader("Pragma","no-cache");
       response.setDateHeader ("Expires", 0);
    
       if(session.getAttribute("username")==null)
          response.sendRedirect("index.jsp");
    %>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    <title>Insert title here</title>
    </head>
    <body>
     <%
      String uname = request.getParameter("uname") ;
      session = request.getSession();
      session.setAttribute("username", uname);
     %>
     <h3>Hi <%out.println(uname); %></h3>
     <form action="page1.jsp" method="post">
      Email <input type="text" name="email"/>
      <input type="submit"/>
     </form>
    </body>
    </html>
      
    page1.jsp
    <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
        pageEncoding="ISO-8859-1"%>
    <%
       response.setHeader("Cache-Control","no-cache");
       response.setHeader("Cache-Control","no-store");
       response.setHeader("Pragma","no-cache");
       response.setDateHeader ("Expires", 0);
    
       if(session.getAttribute("username")==null)
          response.sendRedirect("index.jsp");
    %>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    <title>PAGE 1</title>
    </head>
    <body>
     <%
         String email = request.getParameter("email") ;
     %>
     <h3>Hi <%out.println(email); %></h3>
     <form action="logout.jsp" method="post">
      <input type="submit" value="LOGOUT"/>
     </form>
    </body>
    </html>
    
    logout.jsp
    <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
        pageEncoding="ISO-8859-1"%>
        <%
       response.setHeader("Cache-Control","no-cache");
       response.setHeader("Cache-Control","no-store");
       response.setHeader("Pragma","no-cache");
       response.setDateHeader ("Expires", 0);
    
       session.invalidate();
    %>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    <title>LOGOUT</title>
    </head>
    <body>
         You have successfully logged out
    </body>
    </html>
     

    Friday 18 October 2013

    Enum in Java

    Enum Class for WeekDays
    public enum WeekDays {
         MONDAY("M"), TUESDAY("Tu"), WEDNESDAY("W"), THURSDAY("Th"), FRIDAY("F");
     
         private String weekday;
     
         private WeekDays(String s) {
             weekday = s;
         }
     
         public String getWeekday() {
             return weekday;
         }
    }
      
    Testing Enum
    public class test {
         public static void main(String[] args) {
             System.out.println(WeekDays.FRIDAY.getWeekday());
         }
    }
      
    Output
    F