Archive

Posts Tagged ‘Ready to use’

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.

Serialization – a Sci Fi comic book story

December 18th, 2011 No comments

Short story about serialization

Serialization an interesting story of mars and earth scientistAfter hard work of many years, Earth’s scientist developed a robot who can help them in daily work. But this robot was less featured than the robots which were developed by the scientist of Mars planet.

After a meeting between both planet’s scientist, it is decided that mars will send their robots to earth. But a problem occurred. The cost of sending 100 robots to earth was $100 millions. And it takes around 60 days for traveling.

Finally, Mar’s scientist decided to share their secret with Earth’s scientists. This secret was about the structure of class/robot. Earth’s scientists developed the same structure on earth itself. Mar’s scientists serialized the data of each robot and send it to earth. Earth’s scientists deserialized the data and fed it into each robot accordingly.

This process saved the time in communicating mass amount of data.

Some of the robots were being used in some defensive work on Mars. So their scientists marked some crucial properties of those robots as transient before sending their data to Earth. Note that transient property is set to null(in case of reference) or to default value(in case of primitive type) when the object gets deserialized.

One more point which was noticed by Earth’s scientists is that Mars’s scientists ask them to create some static variables to keep environmental detail. This detail is used by some robots. But Mars’s scientists dint share this detail since the environment on earth was different than Mars environment.

Even though knowing about the robot class structure and having serialized data Earth’s scientist were not able to deserialize the data which can make robots working.

Exception in thread "main" java.io.InvalidClassException:
SerializeMe; local class incompatible: stream classdesc
:

Mars’s scientists were waiting for the complete payment. Once the payment was done Mars’s scientists shared the serialVersionUID with Earth’s scientists. Earth’s scientist set it to robot class and everything became fine.

One of the Mar’s Scientist: Earth’s scientists are very slow to deserialize some of our best Robots. They must be using old version of java. They should either switch to new java version or to implement Externalizable.

Terms highlighted in above example are:
a. Serialization
b. Deserialization
c. Transient variables
d. Static variables
e. Externalizable

Technically

Serialization is nothing but storing current state of an object to physical file. So the data can be used later by deserializing it.

When it is required:

a. When a system gets crashed.
b. When a player want to save all played game data so he can continue playing later.
c. When a process need to be stopped by some reason. But it must continue working the next time with the same data.

How to

a. Implements Serializable or Externalizable
b. Serialize:

	ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("fileName"));
	out.writeObject(obj);

c. Deserialize:

	ObjectInputStream in = new ObjectInputStream(new FileInputStream("fileName"));
	in.readObject();

Java serialization all important points through image Image in words

1.       Object of class A can’t be deserialized to the object of class B.

2.       Object of class A can’t be deserialized to the object of class A itself if any of the instance variable changes its nature. For example

  1. Name
  2. Data type
  3. Removed from the class
  4. Make it transient or static

But if serialVersionUID is added to the class of serialized and deserialized object with same value then deserialization will not generate any error (excluding point b). So if variable is not found then its value is not set.

In short, deserialization finds instance variable with the same name they were used to serialize. If variable name is changed or they are removed from the class then it throws error. But if serialVersionUID is same then it skips initialization for not found variables.

In addition, if a variable is found with the same name but its datatype is changed then it generate error of casting even if serialVersionUID is same.

Changing their access level doesn’t impact.

3.       If serialVersionUID is not same for the class of serialized and deserialized object then deserialization throws error even if class structure are exact same.

4.       Methods, transient variables and static variables are not transient.

5.       An object can be serialized only if its class implements either Serializable or Externalizable.

6.       If extra variables found than the variables which are serialized then they are set to their default value at the time deserialization.

7.       Making a class part of inheritance tree is allowed. But moving a class in existing inheritance tree up/down is not allowed since it can affect saved/serialized object tree.


Why Externalizable

  1. It provides control of reading/writing object to/from an output/input stream.
  2. It was very useful till Java 1.2 since reflection was slow
  3. You can decide which object has to left from object tree or what default value has to be set to transient variables while deserialization.

Methods of Externalizable

public void writeExternal(ObjectOutput out) throws IOException {
	out.writeFloat(x);
	out.writeFloat(y);
	out.writeFloat(z);
	out.writeFloat(w);
}

public void readExternal(ObjectInput in) throws IOException {
	x = in.readFloat();
	y = in.readFloat();
	z = in.readFloat();
	w = in.readFloat();
}

Sample Code

I am attaching source code, I practiced on, for serialization and externalization.

This area is protected to registered users only.

Analysis of processing data file

December 17th, 2011 No comments

I am working on a project where I need to read a text file and for every valid record I have to update database. I also have to write a response/log file. This seems very easy. Although I decided to make a generic solution which can be followed in object oriented way in any project easily.

Requirement

1.       Read all files from a folder following some specific naming conventions.

2.       There will max N records in a file and M fix number of columns in a record.

3.       File header will contain specific fields which are required to validate records in a file.

4.       There will be 2 tables in database. One for keeping file processing information like number of successfully proceed records, total records in a file, failed record, start & end time etc. And another for keeping records detail.

5.       Each field in record has to be format validated and then business validated.

6.       Instead of any update to database first the file then the record must be validated.

7.       It should generate a response file which can be sent for monitoring purpose later.

Design:

I made some classes where each class is responsible for their work only.

FileProcessor (IO processing)

1.       Reads Input folder for specific type of file.

2.       Calls ValidateFile() of FileValidator

3.       Moves a file to specific folder as per return value from ValidateFile()

FileValidator (Single file validation)

1.       Reads each line from input file.

2.       Calls

  1. isValidate() of FileHeader for first line
  2. isValidate() of FileFooter for last line
  3. isValidate() of FileRecord for rest lines

3.       It also writes a response/log file. You can make a separate class for response file in case you want formatted output/logs.

4.       It also performs database operation, if required in your project, when isValidate() returns specific message.

Status

1.       This is an enum.

2.       FileOperation class takes multiple decision on the basis of return value from ValidateFile(). Same with FileValidator class. It writes different messages to response file as per return value from isValidate(). This decision can’t be taken on the basis of boolean value. I guess returning enum is better than returning a String.

FileHeader, FileRecord, FileFooter (Single record validation)

1.       Header of a file generally contains meta data of file records like number of records in a file, max & min length of record, number of fields in a record line etc.

2.       All of them are made as bean class. It helps to store values in database and to compare later.

3.       Any change to these classes will not impact other classes but enum Status. To remove this dependency or to make it more independent you can create a separate class or interface. But remember FileProcessor and FileValidator classes take decision on the basis of return enum. So if this value get changed a little bit change in these classes will also be required.

Java data File Processing analysis

*This article is copyrighted with all examples and images used in this article. Publication of this article to any where without referencing to original article or to hard copy or any modification in original images or example is strictly prohibited.

Java Collection Framework Doodle Chart – what to use when and why

November 21st, 2011 2 comments

I saw most of the people, including me, using ArrayList and HashMap only in their project. I was surprised why the Java provided us so many varieties of collection classes if we are done with only these two.

Since I was not interested to read a whole book for this so I made a doodle chart (cheat sheet, decision chart and short notes) that you can hang to your desk wall or somewhere on your notice board. I have tried to pin up all small aspects related to collection framework. It can help you to decide which class or data structure you should use in your project and why, to maintain high performance.

This is first version of the chart excluding the practical use of Queue interfaces and its classes. I’ll definitely cover them in next article or in next version of this chart.

java,cheat sheet,short notes,class diagram,collection framework,doodle chart

properties,hashtable,hashmap,set,map,sortedset,treemap,treeset,linkedlist,linkedhashmap,linkedhashset,hashset,IdentityHashMap,WeakHashMap,Dictionary,NavigableMap,NavigableSet

java,cheat sheet,short notes,class diagram,flowchart,collection framework,arraylist,hashtable,hashmap,set,map,sortedset,treemap,treeset,linkedlist,linkedhashmap,linkedhashset,hashset,IdentityHashMap,WeakHashMap,NavigableMap,NavigableSet

Above images are not suitable to reference. So you can download PDF version from below link.

This area is protected to registered users only.

*Above contents are copyrighted. You are free to redistribute the PDF or images but the credit to the author or author’s site must not be removed.

Java Generics Cheat sheet

October 31st, 2011 No comments

After writing some articles on java generic I realized that I need a short reference sheet which can remind me about what I learnt or written. So I designed this sheet. It was very difficult to design this short of doodled reference sheet in MS word. Even though I did it after wasting many hours.

Java Generics doodled cheat sheet

Download from here
This area is protected to registered users only.
Some of the examples in sheet refer my previously written articles. Read them once. They’ll help you to remember the actual link between concept and reference syntax.

  1. Java Generics – Boys are not allowed in Girls community
  2. Java Generics continue
  3. End of Java Generic

*Attached contents to this article are under copyright. Don’t modify it or change the reference name. You are free to redistribute the same copy.

Invoice & Inventory reports

August 16th, 2011 No comments

Maximum visit to my site are basically for searching articles related to invoice, inventory and payroll. Even though none of the user has requested for any specific article, I am writing this article for supporting such users.

There are some templates which are needful for billing ,sales ,purchase and other invoices. Take their printout or modify as per your need.

Pro Forma Invoice Template – most useful when two companies are doing business together for the first time and for import/export transactions.


pro forma invoice template

Purchase Order Template

purchase order template

Billing Statement

Billing statement

Sales Invoice

sales invoice template

*Please note that all templates are in excel format and free to use. They might not be macro enabled due to limit of free version. But best for printing media and your ideas. If you are really willing to create your own macros or formula refer Complete Video series to learn excel

WordPress plugin hack to display a post with thumbnail

August 11th, 2011 No comments

amtyThumb plugin provides best way to generate thumbnail of an image. It can extract first image from any post. It provides you a single function to do this.

Now just edit your any plugin to display thumbnail along with post list.

Go to setting page of WP-PostViews page. You will find following text in Most Viewed Template:

<li><a href="%POST_URL%"  title="%POST_TITLE%">%POST_TITLE%</a> - %VIEW_COUNT% views</li>

Add %THUMBNAIL% option to above text

<li><img src="%THUMBNAIL%" /><a href="%POST_URL%"  title="%POST_TITLE%">%POST_TITLE%</a> - %VIEW_COUNT% views</li>

Modify wp-postviews/wp-postviews.php
search for “$output .= $temp;”. Add below line just before the searched test.

$temp = str_replace("%THUMBNAIL%", amty_lead_img(75,75,1,'','','zoom',$post->ID);, $temp);

You can edit plugin in the same manner. Otherwise wait for coming version of amty Thumb Post which has capability to display mostly, recently, rarely …. posts with thumbnail and with any style.

Read more about using amtyThumb here. This article will guide you more about amty_lead_img() function & to insert a thumbnail in your post using shortcode.

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.

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

Sequence Diagrams

May 6th, 2011 No comments

Time is running out for college students, they are hurried in preparing reports. I already had written article over UML Types with the purpose of helping them in preparing reports.

Diagrams, statistics, and UI designs are most important part of the project report. Fewer people are interested to read whole the report. They analyze your project from the diagrams inscribed in your report.

Here, one more short & sweet tutorial about Sequence diagram which helps you to understand the flow of your project. Sequence diagram helps you to know the sequence of interaction between various components(like classes, database etc). You can clearly show the steps of a complete process with these diagrams.

Please refer below guide for your reference. You can save it to read offline.



If you need more examples for your study, just comment here…

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.

Sample database for books

April 26th, 2011 No comments

sample database of books
As soon as the semester end is coming, students are downloading sample database most. So here i am including one more database file of books. Attached Zip file includes CSV,XML,MDB,XLS file for your reference. It is not a huge database. It contains a list of around 30-50 books with their author name, price & all. So you’ll not have to waste your time to create it.

Various version of database will help you to use it in any project. It also has images of listed books.
This area is protected to registered users only.

How to integrate Rupee or other currency symbol on your webpage without images

April 26th, 2011 No comments

You would have seen many websites showing text with stylish fonts, even if those fonts are not available on client site.
It’s very simple. Just copy paste a CSS code somewhere in HEAD tag.

If you are aware with my new font amty currency then you can do it in next 2 steps very easily.

  1. You need fonts(various format) to keep on your web server. You can download them from the download link given in the end of this article.
  2. Use the following CSS code in your CSS file or on your webpage
@font-face {
	font-family: 'Conv_AmtyCurrency';
	src: url('fonts/AmtyCurrency.eot');
	src: local('?'),
	url('fonts/AmtyCurrency.woff') format('woff'),
	url('fonts/AmtyCurrency.ttf') format('truetype'),
	url('fonts/AmtyCurrency.svg') format('svg');
	font-weight: normal;
	font-style: normal;
}
Please note this

  1. Different browsers support different version of font. So we must to keep and reference all type of fonts on web server
  2. Amty Currency font is open source. So it can be used by any organization
  3. Remember that @font-face increase one extra http request since required font are not referred from client cache.
  4. Referring images instead of font could be a good option since images are stored in client cache. And they decrease http requests. In addition images can be merged with other images. And it can be used as image sprite.
  5. Using font is better than images since you can re-size it, color it as per your need. For every symbol of font you need not to create a separate image.

Sample Demo & required files

This area is protected to registered users only.

Really Simplest CAPTCHA integration

March 13th, 2011 No comments

CATCHA is required for humanity check. So you can save your site from any script attack. If you are running a site on wordpress platform then implementing CAPTCHA would be so much easier. The same script you can use to integrate in any PHP site.

1

Write a function to display CAPTCHA somewhere on your site.

function Display_captcha(){
	$common_captcha = new ReallySimpleCaptcha();
	$common_captcha_defaults = array(
			'chars' =&gt; 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789',
			'char_length' =&gt; '4',
			'img_size' =&gt; array( '72', '24' ),
			'fg' =&gt; array( '0', '0', '0' ),
			'bg' =&gt; array( '255', '255', '255' ),
			'font_size' =&gt; '16',
			'font_char_width' =&gt; '15',
			'img_type' =&gt; 'png',
			'base' =&gt; array( '6', '18'),
			);

	/**************************************
	* All configurable options are below  *
	***************************************/

	// Set Really Simple CAPTCHA Options
	$common_captcha-&gt;chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789amty';
	$common_captcha-&gt;char_length = '4';
	$common_captcha-&gt;img_size = array( '72', '24' );
	$common_captcha-&gt;fg = array( '0', '0', '0' );
	$common_captcha-&gt;bg = array( '255', '255', '255' );
	$common_captcha-&gt;font_size = '16';
	$common_captcha-&gt;font_char_width = '15';
	$common_captcha-&gt;img_type = 'png';
	$common_captcha-&gt;base = array( '6', '18' );

	// Set common Form Options

	// Generate random word and image prefix
	$common_captcha_word = $common_captcha-&gt;generate_random_word();
	$common_captcha_prefix = mt_rand();
	// Generate CAPTCHA image
	$common_captcha_image_name = $common_captcha-&gt;generate_image($common_captcha_prefix, $common_captcha_word);
	// Define values for common form CAPTCHA fields
	$common_captcha_image_url =  get_bloginfo('wpurl') . '/wp-content/plugins/really-simple-captcha/tmp/';
	$common_captcha_image_src = $common_captcha_image_url . $common_captcha_image_name;
	$common_captcha_image_width = $common_captcha-&gt;img_size[0];
	$common_captcha_image_height = $common_captcha-&gt;img_size[1];
	$common_captcha_field_size = $common_captcha-&gt;char_length;
	// Output the common form CAPTCHA fields
	$common_captcha_arr = array(
		array ( 'img',$common_captcha_image_src,$common_captcha_image_width, $common_captcha_image_height),
		array ( 'text',$common_captcha_field_size),
		array ( 'hidden',$common_captcha_prefix),

	);
	return $common_captcha_arr;
}

2

Write a function to verify CAPTCHA.

function Verify_captcha($prefix,$code)
{
	$question_captcha = new ReallySimpleCaptcha();
		$question_captcha_prefix = $prefix;
		$question_captcha_code = $code;
		$question_captcha_correct = false;
		$question_captcha_check = $question_captcha-&gt;check( $question_captcha_prefix, $question_captcha_code );
		$question_captcha_correct = $question_captcha_check;
		$question_captcha-&gt;remove($question_captcha_prefix);
		$question_captcha-&gt;cleanup();
		if ( ! $question_captcha_correct ) {
			return false;
		}
		return true;
}

3

Display it somewhere on your form.

&lt; form
&lt; ?php $common_captcha_arr = Display_captcha(); ?&gt;
&lt; p class=&quot;common-form-captcha&quot;&gt;
&lt; img src=&quot;&lt;?php echo $common_captcha_arr[0][1]; ?&gt;&quot; alt=&quot;captcha&quot; width=&quot;&lt;?php echo $common_captcha_arr[0][2]; ?&gt;&quot; height=&quot;&lt;?php echo $common_captcha_arr[0][3]; ?&gt;&quot; /&gt;
&lt; input id=&quot;common_captcha_code&quot; name=&quot;common_captcha_code&quot; size=&quot;&lt;?php echo $common_captcha_arr[1][1]; ?&gt;&quot; type=&quot;text&quot; class=&quot;textfield2&quot; /&gt;
&lt; input id=&quot;common_captcha_prefix&quot; name=&quot;common_captcha_prefix&quot; type=&quot;hidden&quot; value=&quot;&lt;?php echo $common_captcha_arr[2][1]; ?&gt;&quot; /&gt;
&lt; /p&gt;
&lt; /form&gt;

4

Verify it.

if(! Verify_captcha($_POST['common_captcha_prefix'],$_POST['common_captcha_code'])){
  :
}

* You would have to download & Install really-simple-captcha

Virtual Lab

February 12th, 2011 No comments

The Virtual Lab is intended as a flexible teaching and learning tool. It can be used for in-class discussions, pre-lab activities, or novel types of homework problems. The aim of this project is to increase student learning and motivation.


Virtual Chemistry Lab



Plan all Halts of your Life

February 11th, 2011 No comments

Normally people start feeling their responsibility once they cross age of 30 or when they got married. But some out of them starts planning their budget from the initial halt of their life. Like me…. Ha ha ha..

If you are not very good in finance and avoid bulky & boring clerical work then below excel templates would help you surely to plan your budget

Halt 1 : Personal Budget Planning

Personal budget planner excel template

Halt 2 : Wedding Budget Planning

Wedding budget planner excel template

Halt 3 : Family Budget Planning

Family budget planner excel template

Halt 4 : Kids Money Management

Kids Money Management planner excel template

Halt 5 : Retirement Plan

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……..

Best English to Hindi, Hindi to Hindi, Hindi to English online dictionaries

February 6th, 2011 No comments

I am lazy to read books……….

Are you a Hindi blogger?
Or you wanna search something equal to your Hindi words?

Till 5 days ago, I used to visit translate.google.com to find out English word. I put Hindi words there. In 60% cases Google suggests be near about word. I put it into Wordweb to check whether it matches to my need.
Now I have an online dictionary who gives me proper result and multiple options to select correct word. It keeps me away from any other dictionary.

See the Screenshots against word “Satyata” in different search. And select which one fits to your need.

online hindi dictionary bahri

online hindi dictionary caturvedi

online hindi dictionary dasa-hindi

online hindi google translation

*Best feature of theses dictionaries is, you can search for more Hindi words using English or Hindi search directly.

Amty Currency Font, a good replacement of currency images

February 2nd, 2011 No comments

Whenever a new currency symbol gets registered, Unicode is assigned to this. So people can use it in their application. But they need to update their application so that their applications can support new unicodes. Some people and organizations are supposed to use old version of applications due to licensing issue. Or because, updating to new version of application may need update in many existing resources.

On the other hand, using an open source font in your application is not only easy but it’ll require no changes or update in existing resources. In addition, it’ll minimize the effort too.


Amty Currency Font character chart

Best feature of this font is OPEN SOURCE (under GPL). You are free to use it in personal or corporate applications.

Why to use Amty Currency Font instead of Images?
Many of the website designers start using images to display currency symbol at their site. Amty Currency Font is a good replacement of this.

  • If you are aware with SEO concepts, there is an extra http request is required for each image on the page (single request for repeating images).
  • Size of the images is always greater than fonts.
  • You can display fonts in any size, any color with any background color.
  • You can use them to generate complex CAPTCHA images.
download