Showing posts with label java. Show all posts
Showing posts with label java. Show all posts

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

    Thursday, 17 October 2013

    Getting Xml Tag Values using Stack in Java (Applicable to HTML tags) - Parsing



    Method Functionality
    •  This method is used to parse the given XML / HTML Entry containing tags.
    •  The values inside the tags are pushed into the Stack.
    •  You can retrieve the values later from the stack by knowing the depth of the Element
    Input
    <student>
             <name>Nijin</name>
             <college>SSN</college>
             <city>Chennai</city>
    </student>

    Output
    [Nijin, SSN,Chennai]

    Program
    public String getValueFromXmlKey(String xmlEntry, int pos){
    String value= null;
    boolean tagDetected = false;

    Stack<String> stack = new Stack<String>();

    //Converting String to char Array
    char[] xmlEntryArray = xmlEntry.toCharArray();

    String elements = "";
    for(char c:xmlEntryArray){
    if(tagDetected==false){
    if(c=='<'){ //Searching for opening tag
    tagDetected = true;
    if(elements!=""){
    stack.push(elements);
    }
    elements = "";
    }
    else{
    elements += c;
    }
    }
    else{
    if(c=='>'){ //Searching for closing tag
    tagDetected = false;
    }
    }
    }
    System.out.println(stack.get(pos));
    return stack.get(pos);
    }

    Wednesday, 16 October 2013

    String is immutable in Java

    String has a concat(String) method which is used for concatenating.

    Illustration
    String string1 = "Java";
    string1.concat("Programming");
    System.out.println(string1);

    So, guess what will be string1?

    JavaProgramming ??
    No!!

    Its, still Java
    Because Strings are immutable in Java

    Sunday, 13 October 2013

    JDBC-ODBC Connectivity [MS Access]

    Procedure
    1.Go to Control Panel
    2.Click Administrative Tools -- Click Data Sources(ODBC)
    3. Now ODBC Data Source Administrator Dialog Box gets opened.
    4. Now click System DSN, a dialog box appears and then click Add..
    5. Create New Data Source dialog box gets opened and then click Driver Do Microsoft Access (*.mdb) and click Finish.
    6. When you click finish, ODBC Microsoft Access Setup gets opened
    Fill the following information
    Data Source Name: MyDatabase (note:any name, which you will be calling in your program)
    Description: <anything>
    7. Click Select and locate your mdb file
    8. Click OK for all opened dialog boxes. You have successfully created a connection for MS-ACCESS