Archive

Archive for the ‘How & Why’ Category

WordPress plugin hack to display a post with thumbnail

August 11th, 2011 236 views 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.

Cracking a Password is an art

May 28th, 2011 93 views No comments

P@$$w0rd

Everyone is interested to steal personal information of others. But sometimes it is needful. I already had written 3 articles for hacking/cracking passwords and what to avoid.

  1. Brute-force and dictionary attack, poor hacking tactics
  2. How to extract contents from locked zip files
  3. 5 efficient ways to hack locked folders

One more article that I hadn’t published is about keylogger. Let me describe key loggers in brief.

Key logger is an application which can be installed anyone’s PC. They are completely hidden and even the antivirus becomes failed to catch them. They monitor what you type. And all keystrokes can be viewed by the bad guy later who installed it on the machine. They also can be mailed without any notification. So might be your PC is its victim. Nobody needs to visit your place to get this information. That’s why I strongly avoid accessing mails through cyber cafes.

Well! My aim for writing this article is to share a very useful link with you and to improve knowledge in how to guess password.

No body want to forget his password. So he generally chose the password related to his past, someone’s name or some stuff. To make it difficult he uses special characters looks similar to English character. For example , @ in place of a or $ or 5 in place of S.

One more common habit is putting @123 or @1234 at the end of password.

Well it is not the end there are more tricks which make someone guess password and crack it easily.

My this article is inspired by How To Guessing Hacking Figuring Cracking Password Art Guide

Write your own Progress Listener

May 17th, 2011 205 views 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 510 views 2 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 72 views 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());
    }
}

WordPress Multi Select Category Box

April 8th, 2011 795 views 4 comments

While developing some pages of my new site thinkzarahatke, I faced problem to display a multiple select category box. WordPress provides wp_dropdown_categories() function which display you a combo(select) box of categories. You can select only one category at a time.

Since I dint found any other function which can help me and I was not willing to use any plug in for the same so I set multiple attribute to select box at run time using jquery.

$(function() {
           $(".multiselect").attr( 'multiple', 'multiple' );
});

Using the above code you can make multi select category box easily.

Really Simplest CAPTCHA integration

March 13th, 2011 172 views 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

How to import NetBeans project into Eclipse

February 12th, 2011 9741 views 2 comments
netbeans Few days ago, when I faced some issues with NetBeans IDE, I switched to Eclips. Now the problem was my work. Placing java files from one place to another seems easy. But preparing configuration file is really time-consuming. And as usual I avoid manual work. SO let’s see what I did to import NetBeans workspace into Eclipse without wasting time
1


  1. There is a dist folder inside NetBeans workspace, containing a .war file. Import this war file into Eclipse. For this;
    1. Open eclips IDE > Go to File Menu => Import => War
  2. Above step will make package structure in Eclipse workspace similar to NetBeans. It’ll also prepare configuration file. Now you need to place source files only. For this
    1. Go to src folder inside NetBeans folder => Copy all contents => Place them to src folder inside NetBeans folder.
    2. Right click on Project name in right side panel of Eclipse IDE => Refresh

Your Eclipse workspace is prepared. If above trick doesn’t work for you refer another way;

2


OVERVIEW OF THE PROCESS

  1. Lets say you already have a NetBeans project created called MyProject and located at <PATH>\MyProject
  2. open NetBeans and change the project settings
  3. create a ZIP file of the <PATH>\MyProject\MyProject.zip
  4. create a new folder <PATH>\NEW (or your choice), this is where we are going to create the Eclipse Project
  5. open Eclipse create a new project and import the ZIP file
  6. create a new folder <PATH>\NEW\MyProject\dist(necessary for NetBeans)
  7. Now you can DECIDE when to work with Eclipse or NetBeans

DETAILED PROCESS

  1. Let’s say you already have a NetBeans project created called MyProject and located at <PATH>\MyProject
  2. open NetBeans
    • open MyProject
    • Right click MyProject and select Clean Project (this deletes the build/classed and dist folders)
    • open the file project.properties located in the folder <PATH>\MyProject\nbproject
    • change the build.dir to bin
    • change the build.classed.dir to ${build.dir}
    • save and close the file

close NetBeans

  1. create a ZIP file of the <PATH>\MyProject\MyProject.zip that will contain this folders:
    • nbproject
    • src
    • Any other folder or file that is located at <PATH>\MyProject
  2. create a new folder <PATH>\NEW (or your choice), this is where we are going to create the Eclipse Project
  3. open Eclipse
    • go to Window, Open Perspective, Java
    • go to File, New, Project, Java Project
    • click NEXT
    • type MyProject
    • select Create project at external location
    • type <PATH>\NEW\MyProject (this folder will be created by ECLIPSE)
    • select Create separate source and output folders
    • click NEXT
    • click FINISH
    • Right click on MyProject (at the Package Explorer)
    • select IMPORT
    • select ZIP file (usually the last option on the list)
    • click NEXT
    • BROWSE and look for the <PATH>\MyProject\MyProject.zip created on STEP 3
    • click FINISH

close Eclipse

  1. create a new folder <PATH>\NEW\MyProject\dist(necessary for NetBeans)
  2. Now you can DECIDE when to work with Eclipse or NetBeans

How to stop a user to upload big size files?

February 9th, 2011 589 views 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……..

Why to use log4j instead of java classical logging

January 22nd, 2011 313 views No comments

log4j makes your logging not only easier but efficient too. You are supposed to write less code. And can set its parameter at run time without changing actual code.

Read the below features which can make you use log4j.

  • log4j is thread-safe.
  • log4j is optimized for speed.
  • log4j is based on a named logger hierarchy.
  • log4j supports multiple output appenders per logger.
  • log4j supports internationalization.
  • log4j is not restricted to a predefined set of facilities.
  • Logging behavior can be set at run time using a configuration file.
  • log4j is designed to handle Java Exceptions from the start.
  • log4j uses multiple levels, namely ALL, TRACE, DEBUG, INFO, WARN, ERROR and FATAL.
  • The format of the log output can be easily changed by extending the Layout class.
  • The target of the log output as well as the writing strategy can be altered by implementations of the Appender interface.
  • log4j is fail-stop. However, although it certainly strives to make sure delivery, log4j does not guarantee that each log statement will be delivered to its destination.

How to calculate the minimum payment on credit card?

January 20th, 2011 308 views No comments

I never prefer to read articles having heavy terms and their explanation. :-( Since credit cards are common among all. So this information is available for people in interest of keeping knowledge about credit card payment. :-)

I’ll update you soon with some interactive ways for credit card selection.

Minimum payment

Minimum payment is a required by the bank sum, that is determinate by percentage of the borrowed amounts from balance of the credit card and stands at usually 2-5%. As standard do banks require between 2 to 5% of the outstanding balance to be paid on the monthly basis along with interest or it can also be a fixed amount of dollar for a low balance, which as standard is $15.00 for US and Canada and about £5.00 on most credit cards in UK, usually depends on whichever is greater.

Ways of calculating a minimum payment is pretty simple is to multiply the balance on the minimum percentage (2-5%) required paying, which is greater than the sum of interest to cover partial principal payment. The calculator above has an option to define a minimum only or a minimum plus interest ways to pay.

credit card
Fixed Payments on Low Balance

Fixed Payments on Low Balance is paid when the minimum payment, which usually between 2 and 5% of the balance are lower than that fixed payment amount, which is $15.00 for US and Canada or £5.00 for UK on most Credit Cards. In other words the minimum amount required to be paid towards principal is between 2 to 5% of the balance of the credit card. The fixed amount will be paid only when the minimum amount, calculated as percentage of the balance will become equal to or lower than that fixed payment amount.

Principal Payment Distribution.

This is defined as distribution of the principal payment on two lines of credit described as balance on purchases and cash balance of the credit card. Because of the difference in interests for this balances, most banks usually leave cash balance payments right until the very end of clearance of the balance on purchases or may only allocate a very little portion of principal towards those cash balance repayments. You can change this by changing the value of the cell named “Principal Payment Distribution” by changing the percentage of allocation that it usually varies between 0% and 15% depending on your credit cards agreement.

Fixed amount and Additional Payment.

Fixed amount can be any amount that has been decided to pay, but it must be equal or above than the first month payment amount. Making fixed monthly payments will make a significant difference on the number of payments and total interest paid, this will let you pay your credit card balance much sooner and for sure save some interest too. Do not get confused by definition of a Fixed Payment and Fixed Payment on low balance, since this two are completely different payments.

Additional payments are usually the payments that are made occasionally. Depending on the sums paid this can also be a big difference to the paid interest amounts as well as reduction of the number of payments. Both methods can be used with our calculator.

Payment Protection Insurance Payments.

Payment Protection Insurance, also known as PPI is a product that is being sold to you by your bank when you take a loan or credit card. Depending on the agreement PPI will either be deducted from your credit card balance or can be added to your monthly payment. There is a big difference in between, if your PPI premium is deducted from your credit card balance, which is as usual considered as a standard purchase with your credit card as if you were shopping with it, which means that you will also be charged an interest for this and if you are making only a minimum payments you will not be able to cover your credit card balance at all. If you PPI is added to the monthly payment then your monthly total payment will be higher, but at least you can avoid spending your credit card balance and pay extra in interest. PPI offered by any bank is almost always lot higher than if purchased identical product from an independent insurance broker, just remember to read a small print on your credit card agreement to make a right decision before purchasing.

Credit card interest rates are higher than loans secured with collateral.
Please note this
Above calculation may vary with time and place.
Categories: How & Why Tags:

How to calculate Interest on balances of the Credit Card?

January 19th, 2011 512 views No comments

There are some terms and calculations you must know before paying off credit card bill. Although these terms would be crystal clear to either a financial student or bank employees :-)

What is APR and EAR?

APR (Annual Percentage Rate) is a rate provided to consumer for any balance borrowed from Credit Card. Most common way used to calculate your interest is a daily compounding of the interest based on daily closing balance. This explains the fact about why your interest differ from month to month.

EAR (Effective Annual Rate) is more direct reference for the one-year rate of interest. The formula to calculate EAR is: EAR=((1+APR/N)^N)-1 where N is the number of compounding periods. Lets say that the interest is compounded daily and APR is 16.9% than EAR will look like this EAR=((1+16.9%/365)^365)-1 and willbe 18.41% or if the interest is compounded monthly then EAR=((1+16.9%/12)^12)-1 and will be 18.27%.

credit card

Methods of Calculating Interest

Average Daily Balance

There are few ways to calculate an Interest on the credit cards, but most commonly use is an Average Daily Balance method, which is a sum of the daily balances divided on the number of days within that charging cycle to get an average daily balance, which is then multiplied by an APR divided on the number of cycles within a year which is usually 12.

Monthly Interest Charge=Average Daily Balance * (APR / 12)

This is a pretty good way to calculate your monthly interest, but may not be exact reflection of what you get on your monthly statements.

Daily Accrual

There is also a Daily Accrual method that is commonly used in the UK. This method is similar to the one explained above with difference of calculating interest for the daily balance and compounding it to a periodic (usually monthly) charge. In this method each days closing balance is multiplied on the APR divided on 365 days to calculate daily interest charges. Then all of the daily interest sums are added together.

Formula to calculate daily accrual interest for the period looks like this:

Monthly Interest = (Closing balance day 1 * (APR/365)) + … + (Closing balance day 30 * (APR/365))

Calculation of the monthly interest charges with this method will depend on the number of days within a billing cycle, changes in daily balance and APR.

The calculator above allows for two lines of a credit and therefore calculation of the interest also spreads on two lines, that is calculation of interest on the balance on purchases plus interest calculation on the cash balance, which is usually much higher.

Credit card interest rates are higher than loans secured with collateral.
Please note this
Above calculation may vary with time and place.
Categories: How & Why Tags:

Before choosing credit card

January 13th, 2011 7 views No comments

There are some presentations which can help you opting correct credit card as per your need.

Never forget to read faster way to pay off credit card bill.

Categories: How & Why Tags: ,

What project you are planning to develop in this semester

January 11th, 2011 133 views No comments

I observed that in most of the colleges, distribution of projects (as a college assignment) is very much similar every year, as it is given below.

Project Name Group size Popularity in %
Library Management 4 20
Hotel Management 3-4 15
HR Management 7-8 30
Cyber cafe Management 2 5
Transportation management 2 5
Other application like antivirus, dictionary etc 2 each 3 – 5
Other Management projects 3-4 each 20-30
Inventory management 3-4 20
Payroll management 2-3 15
School or college management 3-4 20

*This table is applicable only for computer branch students. And it might not be fit for some colleges.

All the projects which I mentioned are generally developed every year. And their understanding and documents flow from seniors to juniors like heirloom.

Ideas for project planning

Why don’t you try something different in this semester?

If you are deeply interested to design only management projects, It is not necessary that your project must have database. You may go beyond of this.

  • Make a network based application like a chat messenger which supports video chatting.
  • Or a FTP client that let you uploads & downloads files from a server.
  • You may either go for your own SMTP server or a mail server.

If you had set up your mind for standalone applications but not network based application then you may refer these topics as well

  • Mobile based dictionary
  • Or mobile based local bus timetable.
  • You also can develop a rich text editor
  • Or a traffic monitor system

Have a look on some web based applications

  • Develop a web based application to manage your appointments. Who can remind you and can present a calendar view.
  • You can develop an application which let user submit their message to various online social networking sites.
  • You can redesign your college website. So that it can be controlled fully from the back end.

Why to develop management type of project

These projects increase your understanding in a particular domain. You can highlight your domain knowledge in your resume. Further you can easily join a firm or an organization belongs to a particular domain like banking, finance or something else. All management based application use database. So their development shall increase your database knowledge as well. Database knowledge is primary to get selected in an offline campus. I’ll support if you do some certification in a particular domain parallel with your study. It’ll definitely help you in project development and campus selection as well.

Why not to develop management type of project

Application like network or mobile based applications, increases your knowledge in a particular technology. They give you confidence to work independently. You can make many of open source applications to weight up your resume. Moreover, If you are working on something different application or project then it’ll definitely fetch attention of your whole class and teachers as well.

Had you fade up with new google image search? Switch to classic style

January 10th, 2011 188 views No comments

Google has changed its display style for image search. They had adopted BING style with popping up images in addition. It displays more result when you scroll down.

Don’t you feel this search is slower than older one? Although their internal searching speed is as usual high but displaying result in front of end-user had become slow. Especially if you are working on a slow machine then you need to switch to classic view.

To switch google’s classic view of image search result, you just need to put “&sout=1” at the end of URL in your address bar. For example; if you are searching images for article-stack, you’ll find following URL in address bar


http://www.google.co.in/images?q=article-stack&oe=utf-8&rls=org.mozilla:en-US:official&client=firefox-a&um=1&ie=UTF-8&source=og&sa=N&hl=en&tab=wi&biw=1224&bih=514

google image search new style

Now to switch to classic view just add &sout=1 in last. You new URL would like to be


http://www.google.co.in/images?q=article-stack&oe=utf-8&rls=org.mozilla:en-US:official&client=firefox-a&um=1&ie=UTF-8&source=og&sa=N&hl=en&tab=wi&biw=1224&bih=514&sout=1

google image search classic

How to preview documents before downloading

December 28th, 2010 86 views No comments

Last day while searching some PDF files, I felt need to review them before downloading. So I can save bandwidth of my internet speed. And I would not have to collect garbage. At the time I remembered my one of the article about how to embed documents on a web page. So that readers can read documents directly.


Online document viewer to save downloading time

This is very good trick. You just find out some document file over the net. And paste your link in address bar of internet browser after the below link

 http://docs.google.com/viewer?url= 

For example:
Your searched link is “xxx” then your final link would be this

 http://docs.google.com/viewer?url=xxx 
It’ll not only save your time of downloading. But it’ll let you preview all the pages from right side panel.

Only front page and one two more pages are loaded in advance for reading. Rest are cached at google’s server. Which would be loaded once you scroll down the document.

How to remove multiple blank lines from a document in 2 minutes

December 25th, 2010 1040 views No comments

This is very small trick I tried yesterday while creating a PDF file from a document file containing one blank line after a line containing text.

Well!! If you already had read my article about regular expression then it’ll seem very easy for you. Otherwise you just use it as it is without scrubbing your head. I’ll suggest you to read my articles over regular expression. So that you can create such tricks yourself.

What you have to do:

I am using TextPad for this purpose. You can use any test editor which supports regular expression like TextPad or NotePad++, EditPlus.

Copy paste contents in editor. Open “Find & Replace” dialog box from “Edit” menu. If you are using TextPad then you can press F8 to launch this dialog box.

Paste following text into Find text box

\n[ \t]*\n

And replace it with new line character “\n”. Remember that there is a space before “\t”. In the same way if you want to remove multiple blank lines then use “\n” just after “\t”.


textpad find and replace box

Embed Everything

December 13th, 2010 78 views No comments

Many visitors are never interested to download the contents first then check them. They want to take snapshot about the contents from your site/article/post itself. You must help them to view documents online instead of downloading any document to their local PC or to installing any plugin. It’ll remove an overhead from your visitor and will increase hits on your site.


noticeboard embed everything to a webpage

What you need to embed

  1. Word document
  2. Power point presentation
  3. Excel worksheet
  4. PDF documents
  5. Video

I already had suggested about how to embed documents using google . But if you want to avoid any manual intervention then TGN plugin (for wordpress users) would be a good option.

How to use TGN

While writing an article, you can use short code to embed any document on your page. TGN must be installed in advance.

YouTube
[ youtube article-stack]

VideoReadr
[ videoreadr article-stack]

PDF
[ pdf article-stack]

PowerPoint
[ powerpoint article-stack]

Microsoft Word
[ word article-stack]

Note that: remember to replace “article-stack” keyword with valid link for your documents or video ID.

Let visitors read documents without downloading

December 13th, 2010 34 views No comments

There is a very simple solution to display word documents , presentations, excel files etc on your own webpage itself. So people can read them directly without downloading the article and installing any plugin. You can take the help of google for this purpose.

noticeboard embed

For this,

  1. Either upload the documentation file on your server or arrange a link of any other server
  2. Place your link after the given link
    http://docs.google.com/viewer?url=

    For example;

    http://docs.google.com/viewer?url=http%3A%2F%2Fwww.jvds.nl%2Fclimateuncertaintyethics.ppt&embedded=true

Definitely, you would have to use “iframe” tag for this purpose. Read article Highly searched keywords in year 2010 for live demo.


Tip

Instead, if you are willing to display a website, document etc in a popup like thickbox then read the power of wordpress inbuilt thickbox. You can do it without installing any extra plugin.

Use the power of wordpress inbuilt thickbox

December 12th, 2010 170 views No comments

Many people search for plugins to add support of jquery based thickbox. But do you know this is already included in your wordpress bundle. Let’s try
article-stack in wordpress inbuilt jquery thickbox

Suppose you want to open a webpage into thickbox. Just add following code at the end of last link we made above

&amp;embedded=true&amp;KeepThis=true&amp;TB_iframe=true&amp;height=400&amp;width=650

And add following code to your anchor tag.

  class=&quot;thickbox&quot;

For Example

For more guidance, refer jquery thickbox