Archive

Posts Tagged ‘Snippet’

Payroll System – source code

January 28th, 2012 No comments

An analysis report on payroll system with diagrams is the 2nd most visited article. As per visitor’s interest I am writing this article to help you technically design your own payroll system.
I am not aware what computer language you prefer. So attaching source code for sample payroll system in maximum of languages. This is just for your reference and ideas. So you don’t leave any functionality by mistake while designing the whole system. It’ll also help you to complete your payroll system project in less time. And will give you an idea about screen designing.

Visual Basic .net

Payroll system in Visual Basic .net with source code
Account information
username: admin
password: admin

Java applet

Source code

Please rescan the downloaded files because I afraid from hackers before GOD ;-)

Let me know by your comments if you need more screen shots, source code or something else that can help you.

How to force a programmer implementing an interface

November 13th, 2011 No comments

Most of the times we want programmer to follow common naming conventions for standard methods through out the all classes. It helps when we need to call a method using reflection or may be with some other purpose. But other developers generally are not aware with these rules. So they starts defining their own methods similar to standard method but not exact same in name.

There is a way to force them to use same naming convention using interface. Implementation of this way could be different as per your project requirement.

Interface

interface Player{
    public void play();
    public void pause();
    public void stop();
}

Classes which are implementing Player Interface;

class AudioPlayer implements Player{...}
class VideoPlayer implements Player{...}

Some extra class. Meaningless but seems relevant

Class PlayList{}

An enum who plays important role;

enum MEDIAPLAYER {
    AUDIO,VIDEO;

    public Player getPlayer() {
        switch (this) {
            case AUDIO:
                return new AudioPlayer();
            case VIDEO:
                return new VideoPlayer();
            default:
                return new AudioPlayer();
        }
    }
}

Using in code

Player testPlayer = MEDIAPLAYER.getPlayer();
:
testPlayer.play();

Now if any new player is added, its entry will go to MEDIAPLAYER which is returning Player type object. So everyone would have to implement Player

Another approach

You can create an abstract class, say MasterPlayer, who is having all the abstract methods Player interface has. In addition, MasterPlayer will have some additional methods like managing PlayList

I hope this example will help you to understand when to use what in interface and abstract class.

Write your own Progress Listener

May 17th, 2011 No comments

While writing some other articles over Anonymous Classes, I wrote a code to watch over how many bytes of a file has bean read or write. I am sharing that code with all of you to improve understanding in use of anonymous Classes, advanced java concept.

This is very simple and handy code. You can change it as per your need like to keep a watch over file uploading (to limit upload file size), or intimating admin via mail when log file size exceed etc.

This article will also help you to understand need of interfaces over abstract classes.

myFileWriter.java

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Reader;

/**
 * Copyright (C) 2011 Amit Gupta
 * You are free to redistribute the code or its modified version
 * by giving the credit to original code.
 *
 * This code is useful to understand the concept and
 * importance of anonymous class. And how to reuse java classes
 * @author Amty
 *
 */
public class myFileWriter extends OutputStreamWriter //implements myProgressListener
{
	myProgressListener mpl;
	long pBytesWrite;
	public myFileWriter(OutputStream arg0) {
		super(arg0);
		//mpl=this;
		pBytesWrite=0;
	}

	@Override
	public void write(int c) throws IOException {
		super.write(c);
		pBytesWrite++;
		if(mpl != null){
			mpl.update(pBytesWrite);
		}
	}

	public void setProgressListener(myProgressListener mpl){
		this.mpl = mpl;
	}
	//public void update(long pBytesRead, long pContentLength, int pItems){}

	public static void main(String[] args) throws Exception{
		FileOutputStream fos = new FileOutputStream("D:\\article-stack\\amtyOutput.txt");
		FileInputStream fis = new FileInputStream("D:\\article-stack\\amtyInput.txt");
		InputStreamReader isr = new InputStreamReader(fis, "UTF8");
		Reader in = new BufferedReader(isr);

		myProgressListener mpltest = new myProgressListener() {

			@Override
			public void update(long pBytesWrite) {
				System.out.println(pBytesWrite + "Bytes are written");
			}
		};

		myFileWriter mfw = new myFileWriter(fos);
		mfw.setProgressListener(mpltest);
		int ch;
	    while ((ch = in.read()) > -1) {
	       mfw.write((char) ch);
	    }
	    in.close();
	    mfw.close();
	}
}

myProgressListener.java

public interface myProgressListener {
	public void update(long pBytesWrite);
}

Output:

74381Bytes are written
74382Bytes are written
74383Bytes are written
:
77710Bytes are written
77711Bytes are written
77712Bytes are written
77713Bytes are written
77714Bytes are written

Here is attached code for your reference.
This area is protected to registered users only.

Interface vs Abstract classes, a practical difference

May 16th, 2011 No comments

An Interface: This is a collection of methods. They have no definition whatsoever and their function is determined by the class that implements them. An example of an interface is a List. All lists (ArrayList, LinkedList) have add() and remove() methods because they implement the List interface, which demands them.

public interface List {
    public void add (Object o);
    public void remove (Object o);
}

public class MyList implements List {

    public void add (Object o) {
       // I must implement this method because of the interface List
    }

    public void remove (Object o) {
       // I must implement this method because of the interface List
    }
}

The implements keyword is used by a class to indicate that it is going to implement the methods demanded by an interface. A class can implement as many interfaces as it likes; the only requirement is that it provides a definition for each of those methods. It can also be defined as abstract and rely upon its subclasses to define some. Then, those methods are just like the abstract methods of any other abstract class.

Take an example of List interface. Most methods don’t care what kind of list they get; they just want to know that the object supports the common list methods. In the statement:

List<String> myList = new ArrayList();

You are creating an actual ArrayList object, but hiding it’s implementation under the List interface. Then, later, if you decide to use a LinkedList instead, you don’t have to change all of your code since it is also implementing the List interface.

Interface is programming structure where you define your functions/services that you want to expose to public or other modules. Kind of a contract where you promise that you are providing some functionalities or services, but hiding the implementation so that implementation can be changed without affecting your contract.

Abstract class is a partially implemented class and it has no real meaning other than serving as a parent for multiple child classes those with real meaning. Abstract class is special parent class that provides default functionalities to multiple child classes. It is created as abstract because of unavailability of suitable concrete parent class.

The extends keyword is used by a class to indicate that it is going to add functionality to some existing class. If the parent class is abstract, the extending class must implement any of those abstract methods in the parent.

Unlike interfaces, abstract classes can contain fields that are not static and final, and they can contain implemented methods. Such abstract classes are similar to interfaces, except that they provide a partial implementation, leaving it to subclasses to complete the implementation. If an abstract class contains only abstract method declarations, it should be declared as an interface instead.

Points to remember:

Interfaces and interface methods are implicitly abstract even if not declared as so. So there is no need to explicitly specify it.

Below code is senseless.

public abstract interface <interface-name> {
 public abstract void <function-name>(...);
}

Other differences

  1. An interface can extend any number of interfaces.
  2. A class can optionally extend exactly one class; it extends Object if you don’t specify anything.
  3. A class can implement any number of interfaces.
  4. Any class can be declared abstract.
  5. Any class that has abstract methods must be declared abstract.
  6. Any class that extends an abstract class or implements an interface must implement all abstract and interface methods or else must be declared abstract.

Practical usages and designs to inscribe clear picture in your mind

  • Interfaces allow the creation of proxies that encapsulate a concrete class. This is used extensively by frameworks in order to intercept method calls to the concrete class (e.g., for starting a transaction before the method is executed or to write to the log).
  • Keep watch over upload file size
  • Creating progress monitor in Java
  • If an abstract class contains only abstract method declarations, it should be declared as an interface instead.

I am designing an java based API. I’ll share its design once it is completed. It’ll help you to understand the concepts of interfaces, abstract classes, enum, modifers, creating your own data type, delegators, OOPS concept etc. with example. So keep reading….

enum Examples

May 13th, 2011 No comments

I hope you already had read much about enum on various sites and books. Ad you must be aware with how to use enum, where to use, its syntax etc etc.

Here, I am giving just examples on enum (collected from many sites.). So it can improve your understanding in enum.

ApplicationStatus

public class ApplicationStatus {

	 public static  enum APP_STATUS{
	        ALL_GOOD(1, "All things are going good"),
	        WARNING(2, "SOMETHING IS BAD"),
	        ERROR(3, "Its an Error"),
	        FATAL(4, "Its crashed");

	        private String  statusMessage;
	        private int statusId;
	        private APP_STATUS(int statusId, String statusMessage){
	            this.statusId = statusId;
	            this.statusMessage = statusMessage;
	        }

	        public int getStatusId(){
	            return statusId;
	        }

	        public String getStatusMessage(){
	            return statusMessage;
	        }

	        public boolean isAttentionRequired(){
	            if(statusId<3)
	                return false;
	            else
	                return true;
	        }
	    }

	    public void handleAppStatusChange(APP_STATUS newStatus){
	        if(newStatus.isAttentionRequired()){
	            //notify admin
	        	System.out.println("Some problem with application. Application is in " + newStatus + " status.");
	        }
	        //Log newStatus.getStatusId() in the logfile
	        //display newStatus.getStatusMessage() to the App Dash-Board
	    }

	public static void main(String[] args) {
		ApplicationStatus app = new ApplicationStatus();
		app.handleAppStatusChange(APP_STATUS.ALL_GOOD);
		app.handleAppStatusChange(APP_STATUS.WARNING);
		app.handleAppStatusChange(APP_STATUS.FATAL);
	}

}

CommonLanguage

public class CommonLanguage {

  enum Lang {ENGLISH, FRENCH, URDU, JAPANESE}

  /** Find the languages in common between two people. */
  public static void main(String... aArgs){
    EnumSet<Lang> ariane = EnumSet.of(Lang.FRENCH, Lang.ENGLISH);
    EnumSet<Lang> noriaki = EnumSet.of(Lang.JAPANESE, Lang.ENGLISH);
    log( "Languages in common: " + commonLangsFor(ariane, noriaki) );
  }

  private static Set<Lang> commonLangsFor(Set<Lang> aThisSet, Set<Lang> aThatSet){
    Set<Lang> result = new LinkedHashSet<Lang>();
    for(Lang lang: aThisSet){
      if( aThatSet.contains(lang) ) {
        result.add(lang);
      }
    }
    return result;
  }

  private static void log(Object aMessage){
    System.out.println(String.valueOf(aMessage));
  }
}

Error

public enum Error {
	  DATABASE(0, "A database error has occured."),
	  DUPLICATE_USER(1, "This user already exists.");

	  private final int code;
	  private final String description;

	  private Error(int code, String description) {
	    this.code = code;
	    this.description = description;
	  }

	  public String getDescription() {
	     return description;
	  }

	  public int getCode() {
	     return code;
	  }

	  @Override
	  public String toString() {
	    return code + ": " + description;
	  }
	}

Heat

public class Heat {

	enumConstr size;

	public static void main(String[] args) {
		Heat constr = new Heat();
	    constr.size = enumConstr.BIG;

	    Heat constr1 = new Heat();
	    constr1.size = enumConstr.OVERWHELMING;

	    System.out.println(constr.size.getOunces());//8
	    System.out.println(constr1.size.getOunces());//16
	    System.out.println(constr.size.getName());//PONDS
	    System.out.println(constr1.size.getName());//null
	}

		enum enumConstr {
			HUGE(10), OVERWHELMING(16), BIG(10,"PONDS");//(;)Compulsory

			int ounces; String name;
			enumConstr(int ounces){ this.ounces = ounces; }

			enumConstr(int ounces,String name){
			    this.ounces = ounces;
			    this.name = name;
			}

			public int getOunces(){  return ounces; }
			public String getName(){ return name; }
		}
}

Terrain

public enum Terrain {
	  NONE(""),

	  WALL("Wall") {
	    @Override public boolean preventsMovement() {
	      return true;
	    }
	    @Override public boolean blocksLineOfSight() {
	      return true;
	    }
	  },

	  PIT("Pit") {
	    @Override public boolean preventsMovement() {
	      return true;
	    }
	  },

	  FOG("Fog") {
	    @Override public boolean blocksLineOfSight() {
	      return true;
	    }
	  };

	  private String displayName;

	  private Terrain(String displayName) {
	    this.displayName = displayName;
	  }
	  public String getDisplayName() {
	    return displayName;
	  }
	  public boolean preventsMovement() {
	    return false;
	  }
	  public boolean blocksLineOfSight() {
	    return false;
	  }
	}

WeekDays

public class WeekDays {

	private enum Day {
	    SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
	    THURSDAY, FRIDAY, SATURDAY
	}

	 Day day;

	    public WeekDays(Day day) {
	        this.day = day;
	    }

	    public void tellItLikeItIs() {
	        switch (day) {
	            case MONDAY: System.out.println("Mondays are bad.");
	                         break;

	            case FRIDAY: System.out.println("Fridays are better.");
	                         break;

	            case SATURDAY:
	            case SUNDAY: System.out.println("Weekends are best.");
	                         break;

	            default:     System.out.println("Midweek days are so-so.");
	                         break;
	        }
	    }

	    public static void main(String[] args) {
	    	WeekDays firstDay = new WeekDays(Day.MONDAY);
	        firstDay.tellItLikeItIs();
	        WeekDays thirdDay = new WeekDays(Day.WEDNESDAY);
	        thirdDay.tellItLikeItIs();
	        WeekDays fifthDay = new WeekDays(Day.FRIDAY);
	        fifthDay.tellItLikeItIs();          

	    }

}

Color

public enum Color {
    RED(625, 740),
    ORANGE(590, 625),
    YELLOW(565, 590),
    ...

    //Electro-magnetic Spectrum wavelength in nm
    int startWavelength;
    int endWavelength;

    Color(start, end) {
        this.startWavelength = start;
        this.endWavelength = end;
    }

    public int getStartWavelength() { return startWavelength; }
    public int getEndWavelength() { return endWavelength; }

    public static void main(String[] args) {
        System.out.println("Red color's wavelength range, "
            + RED.getStartWavelength()+" ~ "+RED.getEndWavelength());
    }
}

Sample log4j.properties

April 28th, 2011 No comments

log4j is an easier way to track your application flow. It provides many ways to write logs. Its best feature is less code to make more. You just need to create a log4j.properties(generally common to all application, sample is given below.). And write 2 line of code. Read How to use log4j for more understanding.

log4j.rootLogger=DEBUG, CA, FA, mail

#Console Appender
log4j.appender.CA=org.apache.log4j.ConsoleAppender
log4j.appender.CA.layout=org.apache.log4j.PatternLayout
#log4j.appender.CA.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n
#log4j.appender.CA.layout.ConversionPattern=%5r %-5p [%t] %c{2} - %m%n
log4j.appender.CA.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %c{1} [%p] %m%n

#File Appender
log4j.appender.FA=org.apache.log4j.FileAppender
log4j.appender.FA.File=sample.log
log4j.appender.FA.layout=org.apache.log4j.PatternLayout
log4j.appender.FA.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n

# Set the logger level of File Appender to WARN
log4j.appender.FA.Threshold = WARN

#email appender
log4j.appender.mail=org.apache.log4j.net.SMTPAppender
#defines how othen emails are send
log4j.appender.mail.BufferSize=1
log4j.appender.mail.SMTPHost=&quot;smtp.myservername.xx&quot;
log4j.appender.mail.From=fromemail@myservername.xx
log4j.appender.mail.To=toemail@myservername.xx
log4j.appender.mail.Subject=Log ...
log4j.appender.mail.threshold=error
log4j.appender.mail.layout=org.apache.log4j.PatternLayout
log4j.appender.mail.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n

#DailyRollingFileAppender  Appender
log4j.appender.DFA=org.apache.log4j.DailyRollingFileAppender
log4j.appender.DFA.File=sampleDFA.log
log4j.appender.DFA.layout=org.apache.log4j.PatternLayout
log4j.appender.DFA.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n
log4j.appender.DFA.DatePattern='.' yyyy-MM-dd-HH-mm 

#RollingFileAppender Appender
log4j.appender.RFA=org.apache.log4j.RollingFileAppender
log4j.appender.RFA.File=sampleRFA.log
log4j.appender.RFA.layout=org.apache.log4j.PatternLayout
log4j.appender.RFA.layout.ConversionPattern=%d %C %L %-5p: %m%n
log4j.appender.RFA.MaxFileSize=100KB
log4j.appender.RFA.MaxBackupIndex=3
log4j.appender.RFA.Append=false

log4j fileappender – Advanced

April 28th, 2011 No comments

As you seen in my last log4j article about log4j appenders – power of logging, There are various appenders provided by log4j. We discussed few.

Here i am discussing 2 more appenders which help us to divide log file as per the time basis or the size of file. It is very useful to take backup of old logs or to track logs.

DailyRollingFileAppender

Creates file per day. You can keep the backup of old files. It extends FileAppender.

Sample property file entry

log4j.appender.DAILY=org.apache.log4j.DailyRollingFileAppender
log4j.appender.DAILY.File=${user.home}/daily.log
log4j.appender.DAILY.DatePattern='.'&nbsp;yyyy-MM-dd-HH-mm

You can define date pattern as follows

DatePattern Rollover schedule Example
'.'yyyy-MM Rollover at the beginning of each month At midnight of May 31st, 2002 /foo/bar.log will be copied to /foo/bar.log.2002-05. Logging for the month of June will be output to /foo/bar.log until it is also rolled over the next month.
'.'yyyy-ww Rollover at the first day of each week. The first day of the week depends on the locale. Assuming the first day of the week is Sunday, on Saturday midnight, June 9th 2002, the file /foo/bar.log will be copied to /foo/bar.log.2002-23. Logging for the 24th week of 2002 will be output to /foo/bar.log until it is rolled over the next week.
'.'yyyy-MM-dd Rollover at midnight each day. At midnight, on March 8th, 2002, /foo/bar.log will be copied to /foo/bar.log.2002-03-08. Logging for the 9th day of March will be output to /foo/bar.log until it is rolled over the next day.
'.'yyyy-MM-dd-a Rollover at midnight and midday of each day. At noon, on March 9th, 2002, /foo/bar.log will be copied to /foo/bar.log.2002-03-09-AM. Logging for the afternoon of the 9th will be output to /foo/bar.log until it is rolled over at midnight.
'.'yyyy-MM-dd-HH Rollover at the top of every hour. At approximately 11:00.000 o’clock on March 9th, 2002, /foo/bar.log will be copied to /foo/bar.log.2002-03-09-10. Logging for the 11th hour of the 9th of March will be output to /foo/bar.log until it is rolled over at the beginning of the next hour.
'.'yyyy-MM-dd-HH-mm Rollover at the beginning of every minute. At approximately 11:23,000, on March 9th, 2001, /foo/bar.log will be copied to /foo/bar.log.2001-03-09-10-22. Logging for the minute of 11:23 (9th of March) will be output to /foo/bar.log until it is rolled over the next minute.

Sample java code

PatternLayout pl;
FileAppender as_appender = new DailyRollingFileAppender(pl, logFilePath, "'.'dd-MM-yyyy");

RollingFileAppender

RollingFileAppender extends FileAppender, to backup the log files when they reach a certain size.
Sample property file entry

log4j.appender.ROLLING=org.apache.log4j.RollingFileAppender
log4j.appender.ROLLING.File=${user.home}/rolling.log
log4j.appender.ROLLING.MaxFileSize=1MB

log4j.appender.ROLLING.MaxBackupIndex=5

Description

For above property file, when log file size will reach up to 1 MB then new log file with the same name will be created. And current log file will be renamed to <old name>.1 and so on. MaxBackupIndex says how many backup files has to be kept.

FileAppender

FileAppender append logs to every time to specified log file.

Sample property file entry

log4j.appender.FILE=org.apache.log4j.FileAppender
log4j.appender.FILE.File=${user.home}/out.log
log4j.appender.FILE.Append=false

Description

Append property is set to true by default. If it is true then logs will be append every time else the previous logs will be overwritten every time.

How to stop a user to upload big size files?

February 9th, 2011 3 comments

If you are planning to validate a file over its size at client side only using some java script then SORRY.
File upload

Listen

Listen

Listen

You need not to be disappointed. I have many solutions

  1. ActiveX control
    Write the following code in script tag in your HTML.

    function getSize()
    {
    	var myFSO = new ActiveXObject(&quot;Scripting.FileSystemObject&quot;);
    	var filepath = document.upload.file.value;
    	var thefile = myFSO.getFile(filepath);
    	var size = thefile.size;
    	alert(size + &quot; bytes&quot;);
    }
    

    Please note this
    Use of ActiveX control is always avoided due to security reasons.
  2. Java Applet – I had written a Java applet. But i’ll prefer to write a separate code for the same.
  3. SWF – I haven’t tried it before. But it is a very good option.
  4. .htaccess
    Write following line in your .htaccess file.

    LimitRequestBody 2097152

    Apache error log will generate this entry when you exceed this limit on a form post or get request:

    Requested content-length of 4000107 is larger than the configured limit of 2097152
    

    And it will also display this message back in the web browser:

    &lt;h1&gt;Request Entity Too Large&lt;/h1&gt;

    By the way, the error number returned is 413. So, you could use a directive in your .htaccess file.

    Redirect 413 413.html
  5. Best way:
  6. Let client upload the file. Don’t write it at server end immediately. Instead,

    1. Create a file progress bar who monitors how much part of a file has been uploaded.
    2. Once it crosses maximum specified size limit;
      1. Leave writing
      2. Prompt the client.

    Now see how to implement this logic in Java

    1

    Download following jars

    • commons-fileupload-1.2.1
    • commons-io-1.4

    You will get them easily on apache sites.


    2

    Add following code in your java class say servlet.

    import org.apache.commons.fileupload.servlet.ServletFileUpload;
    import org.apache.commons.fileupload.disk.DiskFileItemFactory;
    import org.apache.commons.fileupload.*;
    
    import org.apache.commons.io.*;


    3

    Following line will help you to identify whether client is uploaded a file or not.

    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    


    4

    If yes then first read all the values through some iterator. And check whether there is any non form field (means whether the current item is a file)

    Object img = itr.next();
    FileItem item = (FileItem) img;
    if (!item.isFormField()){
    :
    }
    


    5

    Now its up to you whether you write a file on your server immediately. Or Byte by Byte. I’ll suggest for second option.

    byte[] boundary = &quot;article-stack.net&quot;.getBytes();
    //byte[] boundary = new byte[1000000]; //geting hanged by defining fixed no of bytes
    try{
        MultipartStream ms = new MultipartStream(item.getInputStream(),boundary,1000);
    
        FileOutputStream fileOut = new FileOutputStream(savedFile);
        ms.readBodyData(fileOut);
        fileOut.flush();
        fileOut.close();
    }catch(Exception exp)
    {
      savedFile.delete();
      exp.printStackTrace();
    }
    


    6

    Its not done boss. You have to write a progress listener.

    ProgressListener progressListener = new ProgressListener(){
       private long megaBytes = -1;
       public void update(long pBytesRead, long pContentLength, int pItems) {
           long mBytes = pBytesRead / 1000000;
           if (megaBytes == mBytes) {
               return;
           }
           megaBytes = mBytes;
           System.out.println(&quot;We are currently reading item &quot; + pItems);
           if (pContentLength == -1) {
               System.out.println(&quot;So far, &quot; + pBytesRead + &quot; bytes have been read.&quot;);
           } else {
               System.out.println(&quot;So far, &quot; + pBytesRead + &quot; of &quot; + pContentLength
                                  + &quot; bytes have been read.&quot;);
           }
       }
    };
    

    Modify the above progress listener as per your need to limit the file size.

Happy……..

Sample Java Servlet for your reference

January 28th, 2011 No comments

There is sample servlet code which read request parameters and response them back. This servlet will give you an idea about how a servlet looks. And how to process request parameter.

You must remember while writing a servlet that servlet is nothing but a special java class. Outside application whether your webpage or any other standalone application access a servlet by its alias name. This naming conversion has written inside a file say web.xml. Your server identifies the request and link it to proper servlet. So basically you need 3 components

  1. Servlet class
  2. web.xml
  3. some webpage to hit your servlet

Sample Servlet

import javax.servlet.*;
import javax.servlet.http.*;
import java.util.Map;
import java.util.Iterator;
import java.util.Map.Entry;

/**
 * This servlet accept form String data.
 * 1. Prints values of text box having name username,department and email
 * 2. Prints values of any form field having any name (including multiple selector, check boxes etc.)
 * 3. A form element having no name can not be accessed any way (parameter name, parameter map)
 * @author Amty
 */
public class ArticleStackPostHandler extends HttpServlet {

 public void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, java.io.IOException {

/* Use the ServletRequest.getParameter(String name), getParameterMap(), getParameterNames(), or getParameterValues() methods in the servlet's doPost method*/

        String name = request.getParameter("username");
        String depart = request.getParameter("department");
        String email = request.getParameter("email");
        response.setContentType("text/html");
        java.io.PrintWriter out = response.getWriter();

        out.println("<html>");
        out.println("<head>");
        out.println("<title>Welcome</title>");
        out.println("</head>");
        out.println("<body>");
        out.println("<h1>Your Identity</h1>");
        out.println("Your name is: " + ( (name == null ||  name.equals("")) ? "Unknown" : name));
         out.println("<br><br>");
         out.println("Your department is: " + ( (depart == null ||  depart.equals("")) ? "Unknown" : depart));
         out.println("<br><br>");
         out.println("Your email address is: " + ( (email == null ||  email.equals("")) ? "Unknown" : email));
        out.println("<h2>Using ServletRequest.getParameterMap</h2>");
        Map param_map = request.getParameterMap();
        if (param_map == null)
            throw new ServletException("getParameterMap returned null in: " + getClass().getName());

         //iterate through the java.util.Map and display posted parameter values
        //the keys of the Map.Entry objects ae type String; the values are type String[],
        //or String array
        Iterator iterator = param_map.entrySet().iterator();
        while(iterator.hasNext()){
            Map.Entry me = (Map.Entry)iterator.next();
            out.println(me.getKey() + ": ");
            String[] arr = (String[]) me.getValue();
            for(int i=0;i<arr.length;i++){
              out.println(arr[i]);
              //print commas after multiple values,
              //except for the last one
              if (i >= 0 && i != arr.length-1)
                out.println(", ");
            }//end for
                out.println("<br><br>");
        }//end while

        out.println("</body>");
        out.println("</html>");
        out.close();
  }

  public void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, java.io.IOException {

    doPost(request,response);
  }
}

Sample web.xml

    <servlet>
        <servlet-name>ArticleStackPostHandler</servlet-name>
        <servlet-class>ArticleStackPostHandler</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>ArticleStackPostHandler</servlet-name>
        <url-pattern>/PostHandler</url-pattern>
    </servlet-mapping>

Sample web page to hit this servlet

<%--
    Document   : index
    Created on : Jan 23, 2011, 2:54:06 PM
    Author     : Amty
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!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=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <h1><a href="http://article-stack.com/">Article-Stack.com</a></h1>
    <form action="PostHandler" method="post">
        <p>username:
  <input type="text" name="username" value="" />
          <br />
          department: <input type="text" name="department" value="" />
          <br />
          email: <input type="text" name="email" value="" />
          <br />
        </p>
        <p>color:
  <input type="checkbox" name="color" value="RED" checked="checked" >RED</input>
          <input type="checkbox" name="color" value="GREEN" >GREEN</input>
          <input type="checkbox" name="color" value="BLUE"  >BLUE</input>
        </p>
        <p>
          <select name="cities" size="3" multiple="multiple">
            <option>Mumbai</option>
            <option>Bangaloor</option>
            <option>Chennai</option>
            <option>Delhi</option>
            <option>Indore</option>
          </select>
        </p>
        <p>
          <input type="submit" value="Submit" />
        </p>
    </form>

        <h1>&nbsp;</h1>
</body>
</html>

How to implement log4j in java code itself without using log4j.properties

January 12th, 2011 2 comments

If you are not willing to use log4j configuration file ie log4j.properties then you will have to define a java class to set all properties in your code itself.

STEPS

  1. Creating a logger and appender. Add appender to logger.
  2. Set the LEVEL if you want
  3. Define log message layout.
  4. Don’t forget to attach log file path where you have to write your messages.

Sample code: Copy and paste below sample class somewhere in your java project.

public class Log
{
	public static Logger as_looger;

    public Log(){}

    static
    {
        as_looger = Logger.getLogger("articles logging");
//      as_looger = Logger.getLogger(Log.class.getName());
        FileAppender as_appender = null;

            as_appender = new DailyRollingFileAppender(new PatternLayout("%d{dd-MM-yyyy HH:mm:ss} %C %L %-5p: %m%n"), “path of file where to write logs”, "'.'dd-MM-yyyy");
        as_looger.setLevel(Level.DEBUG);
        as_looger.addAppender(as_appender);
    }
}

Since as_looger is declared as static in above example class. So you can use it throughout your java project using class name as follow;

Syntax

< Log class name >.< logger name >.< method denoting a level >(“message”);

Example

Log.as_logger.debug(“article-stack.com has been started.”);
Categories: Uncategorized Tags: , , , , , ,

SQL:How to fetch starting N rows from a table

October 7th, 2010 1 comment

DB2

		select *
		from 	(select rownumber() over(order by &lt;colName&gt;) as row_num, &lt;colName2&gt;
			from &lt;table name&gt;)
			as &lt;alias name&gt;
		where row_num &lt; N+1 with ur

Oracle

		select *
		from 	(select rowid as row_num, &lt;colName2&gt;
			from &lt;table name&gt;)
			as &lt;alias name&gt;
		where row_num &lt; N+1

SQL:How to fetch Nth row of a table

October 6th, 2010 No comments

DB2

		select *
		from 	(select rownumber() over(order by <colName>) as row_num, <colName2>
			from <table name>)
			as <alias name>
		where row_num = N with ur

Oracle

		select *
		from 	(select rowid as row_num, <colName2>
			from <table name>)
			as <alias name>
		where row_num = N

SQL:How to fetch rows from nth position to mth position

October 6th, 2010 No comments

DB2

		select *
		from 	(select rownumber() over(order by <colName>) as row_num, <colName2>
			from <table name>)
			as <alias name>
		where row_num between 1003 and 1118  with ur

Oracle

		select *
		from 	(select rowid as row_num, <colName2>
			from <table name>)
			as <alias name>
		where row_num between 1003 and 1118

How to test Regular expression across the programming languages?

September 29th, 2010 2 comments


Regular expression

Prerequisite

Regular expression, in introduction with full of example

A regular expression (regex or regexp for short) is a special text string for describing a search pattern.

There are various flavours of Regular Expressions. All the flavours are 80% common. Some languages provide more elements, functions and keywords for efficient searching. Maximum of them have common regular expression elements. You can test them in various languages as follow.

AWK

    awk ‘/RE/’ filename

JAVA

	boolean b = Pattern.matches("RE", "contents");

PHP

        preg_match_all(‘/RE/’,$contents,$result_array)

PERL
I havn’t gone through PERL syntax. But they are similar to AWK.

C# (.NET)

	Regex pattern=new Regex("RE");
        bool matching = return pattern.IsMatch("Contents");

Common elements are also supported by rich text editor programs like textpad or notepad++.

You can also try Online Tool to test for testing regular expression.

AWK: How to count number of entries for a month

August 2nd, 2010 No comments

I hope all of you are aware with AWK. This example will help you to understand AWK practically.
Sample Data:

	 10-Jul-10
	 23-Jul-10
	:
	 31-Jul-10
	 1-Aug-10
	:
	 4-Aug-10
	 5-Aug-10
awk 'BEGIN{
		FS="-";OFS=","
	}
	{
		$1="";
		print substr($0,2,length($0))
	}'
	dates.txt
| sort | 

awk 'BEGIN{
		getline;
		lastline=$0;
		count=1;
	}
	{
		if(lastline==$0)
		{
			count+=1;
		}
		else{
			print lastline": "count;
			lastline=$0;
			count=1;
		}
	}
     END{
		print lastline": "count;
	}'

Output:
Aug,10: 5
Jul,10: 22

Explanation:
We can break above commands in 3 parts. First part removes the date. And gives filtered out put like;

	 Jul,10
	 Jul,10
	 Jul,10
	:
	 Jul,10
	 Aug,10
	 :
	Aug,10
	 Aug,10

There may be a change that text file or input data have dates in any order. So the sort command just sorts the output given by first command. And provides support to third command. 3rd command is again a AWK command. And it searches for continuity of a pattern. Once pattern changes it prints the count.
To understand AWK examplesyou must read basic structure of AWK command.

AWK: How to remove all spaces & tabs from all fields of a file

August 1st, 2010 No comments

Following command will help you to remove all trailing and leading spaces from all fields of a text file. It also remove tab characters. I am assuming that all the fields in input file are separated by “^”. If you are using any other separator then set the value of FS in BEGIN block accordingly.

 awk 'BEGIN {FS="^";OFS="^";}{for (i=1; i<=NF; i++) {gsub(/^[ \t]+|[ \t]+$/,"",$i);} print }' filename > file_name_new
Please note this
This example will also help you to build data file for you database where you need to insert blank or null value when value for a field does not exist.

How to handles dates in java without panic

July 29th, 2010 4 comments
java date4j

Handling dates, their formatting and other operations in java are little bit problematic. I never found any efficient tool to print time stamp or to operate dates like adding days or finding out last day of the month or whether current year is leap year etc.
date4j provides efficient solution to do all date related operations. This is a very good replacement of java.util.Date. Refer the below example for this;


import java.util.TimeZone;

import hirondelle.date4j.*;

public class date4jYamty {

	public static void main(String[] args) {
		//DateTime dt = new DateTime("");
		String dt = DateTime.now(TimeZone.getDefault()).format("YYYY-MM-DD-hh.mm.ss.ffffff");
		//DateTime dateAndTime = new DateTime("2010-01-19 23:59:59");
		//DateTime dateAndTime = new DateTime("2010-01-19 23:59:59.123456789");
		//DateTime dateOnly = new DateTime("2010-01-19");
		//DateTime timeOnly = new DateTime("23:59:59");
		//DateTime dateOnly = DateTime.forDateOnly(2010,01,19);
		//DateTime timeOnly = DateTime.forTimeOnly(23,59,59,0);		

		System.out.println(DateTime.now(TimeZone.getDefault())); //Y:2010 M:7 D:22 h:21 m:23 s:58 f:130000000
		System.out.println(dt); //2010-07-22-21.23.58.110000
		System.out.println(DateTime.today(TimeZone.getDefault())); //Y:2010 M:7 D:22 h:null m:null s:null f:null		

		//DateTime dt = new DateTime("2010-01-15 13:59:15");
		//boolean leap = dt.isLeapYear(); //false
		//dt.getNumDaysInMonth(); //31
		//dt.getStartOfMonth(); //2010-01-01, 00:00:00.000000000
		//dt.getEndOfDay(); //2010-01-15, 23:59:59.999999999
		//dt.format("YYYY-MM-DD"); //formats as '2010-01-15'
		//dt.plusDays(30); //30 days after Jan 15
		//dt.numDaysFrom(someDate); //returns an int
		//dueDate.lt(someDate); //less-than
		//dueDate.lteq(someDate); //less-than-or-equal-to

	}

}

Output :

Output for any statement is attached with statement itself as comment.
You can comment out rest statements. They are written for your knowledge.

How to retain list of attachments while replying to all in outlook?

July 28th, 2010 No comments
Outlook macro

This is a very good example of visual basic macro. If you use outlook in your office or at home this code will surely save your time. This code is suggested by my friend Prathamesh Raorane.

This code is tested on Outlook 2003 and 2007 version

When you click on reply to all button in outlook, automatically list of attachments are removed. But list of all people which were in CC or in TO files are shown. Similarly, If you forward a mail then list of ids under CC or TO fields are removed. But attachment retained. Prathamesh gave me a code that can do both work in one short.

This area is protected to registered users only.

To use above code.

Open Outlook [I tested the above code in Outlook 2003 & 2007]
Press Alt + F11. Otherwise go to Tools menu and select macro option.
Open the macro editor.
Copy paste above code. And save it.
You may add a toolbar button. So from the next time you can run the code directly from the toolbar. Otherwise you’ll have to go to Tools > macro every time.

Once everything done then every time when you run the code will open separate window similarly when you click on “reply to all” button. List of attachments will be retained this time.

Special Thanks to Prathamesh Raorane