Spiga

Playing Around With Frequently Changing String Tokenizer


Playing Around With Frequently Changing String Tokenizer

Recently I was working on one of my Project Module. I had to use some data from the other module and they were sending this in the form of String Tokens, like "element_1;element_2;element_3;element_4;". So, as normal I did the normal tokenize code and break this tokens to use the values. Now they changed the token order, so I would have to do all the rework.
After that I came up with some solutions so that my code rework can be minimised even if the  token orders are changed. So I did the following:
1) Add all the tokens in the List. Let’s say, in the tokenizer parser method, just add all the token in the List.
2) Do not write any core logic in the token parser method.
3) Now create a enum or any such structure which will hold the token position. In my case I use the enum.
                e.g.
public enum ElementPositionEnum {
       ELEMENT_1(0), ELEMENT_2(1), ELEMENT_3(2), ELEMENT_4(3);
       private int position;
       ElementPositionEnum(int position) {
              this.position = position;
       }
       public int getPosition() {
              return this.position;
      }
}
4) Now while creating the object or setting the value to my object, just fetch the elements from the List based upon the Enum position.
                E.g. If I have to fetch the value,  I will do it like this:
                String myVal = List.get(MyElementPositionEnum.ELEMENT_1.getPosition());
5) So, even if the tokens sequence is changed, then  we only need to change the enum's value. Rest of the code will be same.
Java Code for Same :
public class TokenizerParser {
       public TokenElementTO parseToken(String token)
       {
              List listOfTOken = new ArrayList();
              String[] tokens = token.split(";");
              for(String val : tokens)
              {
                     listOfTOken.add(val);
              }
              return createTokenElementObject(listOfTOken);
       }
        private TokenElementTO createTokenElementObject(List listOfTOken)           {
              TokenElementTO to = new TokenElementTO();
              if(listOfTOken.size() > ElementPositionEnum.ELEMENT_1.getPosition())
                     to.setElement_1(listOfTOken.getElementPositionEnum.ELEMENT_1.getPosition()));
              if(listOfTOken.size() > ElementPositionEnum.ELEMENT_2.getPosition())
                     to.setElement_2(listOfTOken.get(ElementPositionEnum.ELEMENT_2.getPosition()));
              if(listOfTOken.size() > ElementPositionEnum.ELEMENT_3.getPosition())
                     to.setElement_3(listOfTOken.get(ElementPositionEnum.ELEMENT_3.getPosition()));
              if(listOfTOken.size() > ElementPositionEnum.ELEMENT_4.getPosition())
                     to.setElement_4(listOfTOken.get(ElementPositionEnum.ELEMENT_4.getPosition()));
               return to;
       }
 
       public static void main(String[] args)
       {
              TokenizerParser main = new TokenizerParser();
              String tokens = "AAA;BBB;CCC;DDDD";
              main.parseToken(tokens);
       }
}
 
public class TokenElementTO {
 
       private String element_1;
       private String element_2;
       private String element_3;
       private String element_4;
 
       public String getElement_1() {
              return element_1;
       }
       public void setElement_1(String element_1) {
              this.element_1 = element_1;
       }
       public String getElement_2() {
              return element_2;
       }
       public void setElement_2(String element_2) {
              this.element_2 = element_2;
       }
       public String getElement_3() {
              return element_3;
       }
       public void setElement_3(String element_3) {
              this.element_3 = element_3;
       }
       public String getElement_4() {
              return element_4;
       }
       public void setElement_4(String element_4) {
              this.element_4 = element_4;
       }
}


Create JavaOutOfMemory Crash Dump

Create JavaOutOfMemory Crash Dump:


Sometime Java Application crashes due to out of memory exception. If we don't have the proper logging mechanism, we won't be able to find out why the application has crashed. We can use the Jconsole or Jprofiler to debug the memory leak. But if our application crashes after running for 3-4 hours, it will be difficult to debug without having proper dump.
Java provides some useful arguments, using which we can create the core dump using very few arguments.
We can add below arguments in the JVM to get the dump:
                java -ms32m -mx512m -XX:+HeapDumpOnOutOfMemoryError.
By adding the above argument, when the application crashes, It will create the dump with name : java_pid.hprof

ALGORITHM TO DETERMINE STRING CONTAINS UNIQUE CHARACTER

Implement an algorithm to determine if a string has all unique characters. With and without using extra additional data structures

/**
* Implement an algorithm to determine if a string has all unique characters.
* With and without using extra additional data structures?
*
@author Sonu Mishra
*/
public class StringContainsUniqueCharacter {
/**
* Without using extra DS.
*  Ignoring int variable. Time complexity is
* O(n), where n is the length of the string, and space complexity is O(n).
* We can reduce our space usage a little bit by using a bit vector.We will
* assume, in the below code, that the string is only lower case ‘a’ through
* ‘z’.This will allow us to use just a single int
*
@param str: String to check
@return : true/false
*/

Not Accessible Due To Restriction On Required Library

Not Accessible Due To Restriction On Required Library

Today, I was working on some java project in my favourite Eclipse editor, when I encountered some unknown problem. It was throwing some error that the calss cannot be accessed due to restriction on required library. This type of error occurs when some classes cannot be loaded into the projects since some restriction rules are being imposed on those classes. Similarly, I got the error like this:




How To solve this Exception:

As this error is coming because of some setting where we are excluding some files. So we need to change that settings. For that, click on the 'Windows' --> 'Preference' and then go to 'Java'-->Compiler-->'Error/Warnings' tab. You will find 'Forbidden reference (access rules):' and its value has been set to 'Error'. So we only need to do is, to change the 'Error' to 'Warning', and all is done.


Swapping the Variables Without Using Third Variables

Swapping the Variables Without Using Third Variables Using Java

In this post, we will see, how to swap the variables. There are different ways to swap the variables. The major swap algorithms are:
1) Swapping using the third varaibles.
2) Swapping using the Bitwise Operator. This is only for the Integer. This doesn't use the third variables.
3) Swapping using the Arithmetic Operations. This is also, only for the Integer. This also, doesn't use the
    third variables.
4) Swapping the Strings without using the third variables. This is little bit tricky. The logic is similar to the
    above one, i.e. Arithmetic Operations. But the Strings are immutable in the Java, so, externally we are not
    using the third variables, but internally, this uses the third variables.

Below, we have the Java Program to discuss all the above methods in details.

/**
* This class will reverse the two variables.
* Here we will see how to swap the variables using or without using the third variables.
* @author Sonu Mishra
*/
public class SwapVariables {
/**
* Swapping using the third variable and without the third variables.
* Swap two variables using the temporary variables or the third variable.
* @param a The first variable.
* @param b The Second variable.
*/

Basic TreeNode Structure in Java using Generics

Basic TreeNode Structure Using Generics

This is the basic block for creating the binary tree. We generally call this block or the structure as a Node. So this is how a single node is created. This in itself is a tree and when we pile the number of nodes, it become a big tree.

Here is the code, to create the TreeNode.

/**
* Basic Structure of the Tree. Or the Single unit of a tree.
* @author Sonu Mishra
* @param Type of the Node for the tree. Like. String, Integer
*/
TreeNode< E extends Comparable<? super E>>
{
public TreeNode< E > left;
public TreeNode< E > right;
E value;
public TreeNode(TreeNode< E > left, TreeNode< E > right, E value) {
this.left = left;
this.right = right;
this.value = value;
}
/**
* If a node doesn't have left and right child, it is leaf node.
* @param node check whether this node is leaf node or not.
* @return either true or false
*/

JAVA WAY TO WRITE TREE

JAVA WAY TO WRITE BINARY SEARCH TREE

A binary search tree (BST),is a node-based data structure in which each node has no more than two child nodes. Each child must either be a leaf node or the root of another binary search tree. The left sub-tree contains only nodes with keys less than the parent node; the right sub-tree contains only nodes with keys greater than the parent node.BST is also known as an ordered binary tree.
BST
Here is the Code to create a binary search tree in java.

import java.util.LinkedList;
import java.util.NoSuchElementException;
import java.util.Queue;
import java.util.Stack;
/**
* Creates a Binary Search Tree.
* @author Sonu Mishra
*/
public class BinarySearchTree<E extends Comparable<? super E>>
{
private TreeNode<E> root = null;
public BinarySearchTree() {
root = new TreeNode(null, null, null);
}
public BinarySearchTree(E value) {
root = new TreeNode(null, null, value);
}
public void add(E value) {
addBefore(value, this.root);
}

How To Sort a File On the basis of the column Using Java

How To Sort a File On the basis of the column Using Java

Java Program to sort the file.
In the earlier post we have seen how to sort the CSV file. Now, we will see the generalised java code to sort the file on the basis of particular column. This code can be used for any type of files, like csv, txt etc. This can be useful to sort the big files on the basis of the column. For using this code, we need to take care of few things:
The format of the file should be like in this format:
The header or the column should be there and should be the first line of the file, else we will missed the first line.
Header/Col1: Header/Col2 : Header/Col3
a : c : e
s : a  : d
.. : .. : ...
Algorithm Used:
It’s not the rocket science, we have keep it simple and have used the simple algorithm. The each row has been considered as one java object. The column on which we have to sort is taken as the key and against this key we have the associated row data java objects as values. We sort the key and display the respective values.
For example: If we have to sort the above file on column 2, we will create two java objects which will have values:
Java@Obj1: a,c,e
Java@Obj2: s,a,d

Now, we are sorting on column 2, so for first row, key will be c and c will be mapped with the value Java@Obj1: a,c,e and for the second row: key will be a and a will be mapped with the value Java@Obj2: s,a,d. Now we will sort the keys, i.e. c and a and then we will display the mapped value for the sorted keys.

Here is the Java Class Example:

Default Author Name in Eclipse

Default Author Name in Eclipse


By default, the Eclipse show the file author name as the Windows Id name. This is because, the eclipse read the ${user} variables value from the environment variables and display that variables. So we can change that default values in different name.

Different Ways:
1) By changing the eclipse setting for that. Go to the
  Window -->Preferences -->Java -->Code Style -->Code Templates -->Comments
  Change the Comments format over there, like
  If it is like this:
  /**
  * @author ${user}
  *
  * ${tags}
  */
  Romove this with:
  /**
  * @author Sonu Mishra
  *
  * ${tags}
  */

2) Use the VM arguments -Duser.name=Sonu Mishra. You can set this in the eclipse.ini files of eclipse.

Difference Between Eclipse Ganymede/Galileo/Helios/Indigo

Difference Between Eclipse Ganymede/Galileo/Helios/Indigo

What  is the difference between Eclipse Ganymede/Galileo/Helios/Indigo?
Basically those are just the different versions or the major release  of the eclipse.  So, instead of using the version number, they are using the name like helios or indigo. Since 2006, the Eclipse Foundation has coordinated an annual Simultaneous Release. So the different versions of eclipse till now are:


Copy Paste In DOS Command Prompt Using Mouse

Copy Paste In DOS Command Prompt Using Mouse

Copy/Paste in the DOS and Command Console is not easy. First you have to do the right-click and then select the data and then again do the right click and then paste the data. Now, in this post we will see the easier way that will allow the copy paste using the mouse.
After the trick, You will be able to select the data by highlighting the area by mouse and hitting the ‘Enter’ button will copy that highlighted area. To paste the copied thing, just right click the mouse and that will paste the thing.
Follow the Below steps to configure the Console.
1. Open a Command Prompt/Command Console.
2. Right-click on the title bar.
3. Select Properties.
4. Select QuickEdit Mode.
5. Select Save Properties for future windows with same title if you want to make this a permanent change. Select Apply Properties for current window only if you only want to enable QuickEdit for this session.
6. Click OK.

How To Sort The CSV File

How To Sort The CSV File:
Always we came across at some point where we want to sort the data, or we want to compare similar kind of data. So, in this post, we will focus on some of the quick ways to sort the data of the CSV file. Windows provide the SORT command, and using that command we can sort the data of the files.
Sorting Using Windows SORT Command
1)      You can use the sort command to sort the files. In the command prompt, type following:
a.       Sort  Input_filename  : This will sort the file and will display the output on the console. This will sort the file on the basis of first column. Let’s suppose your input is :
Input:
1              g              k
3              f              d
2              c              a
                                             Output will be:
sort Book.csv
1,g,k
2,c,a
3,f,d
b.      Sort  Input filename Output Filename : This will sort the input file data and will store the result in the OutputFile.
Example:     sort Book.csv  outputBook.csv
c.       Sort  Input_filename Output_Filename /+Column_Number: This will sort the file on the basis of column number. If we provide column number as 2, it will sort the file on the basis of column 2nd column. E.g.:
sort Book.csv /+2
2,c,a
3,f,d
1,g,k
2)      You can write the Customized java written program also to sort as per requirement. In the next post we will see the customized Java Program to sort the files. This one is my favourite.
3)      There are several software’s available in the market for this and as well as other purposes.

View Match Live Online

There are different websites which provide the luxury to watch the live matches online.
Here are few links. If you dont have the tv, don't worry, this will help you watch the matches live.

1) http://www.ipl.indiatimes.com/            Provides Video
     This is one over slower then live.
2) http://www.crictime.com/watch-live-cricket-streaming.htm         Provides Video
     This is faster one.
3) youtube.com
4) cricbuzz.com         Only Webpage  faster one
5) cricinfo.com          Only Webpage 

Note:- This review is based on my experiances.

How To Bookmark WebPage In Browser

How To Bookmark WebPage In Browser


This is quite simple but always we forgot to do this. In this post we will recall how to add the webpage to the bookmark or to add to favourites. By doing this, we save the link of the webpage for future reference. Here are the steps to do this:


1) Go to the page you want to bookmark/add to your favourites.
2) Click Favorites in the top menu bar then Add to Favorites.

Also you can use the Ctrl+D button to bring the pop up in front.

3)The Add Favorite dialogue box appears. The title from the web page will be in the name box. Click the Create In button
4) You can click OK button or can customize as per requirement.

BlackBerry Storm Hangs

BlackBerry Storm Hangs

The Blackberry Storm has one one drawback, it consumes the application memory too much. Because of this the application memory becomes zero, and the mobile hangs too much. Atleast I have experienced this problem on my Storm.

Problem:
===========
1) Mobile Hangs.
2) Take too much time to open any application.


Reason:
===========
1) The Application memory is consumed and there is 0mb for Application memory.
     You can check the application memory by navigating to :
                   Options------>Memory
2) Even after uninstalling the applications, it doesn't increase the application memory.

Solution:
========
1) Remove the battery of the blackberry storm for some time and then put it back and then restart the Storm.
2) Problem is solved.
If u have some better sol, please post it back.. 

How To Resolve Argument Too Long Error In Unix

How To Resolve Argument Too Long Error In Unix

Sometime, when we fire some commands in the unix, then it gives the 'Argument Too Long Error' on the console. We get this error when there is lots of file, suppose there are 15k files and we want to move those file or delete those files, then it gives the same error.

How To Resolve:

To resolve these error, we will use the find commands and will pass the remove command as a argument to the find command.

find . -name '*.*' xargs rm

.           : is directory name
-name  : is type of file that we want to delete.
xargs    : is Linux command that makes passing a number of arguments to a command easier.

Hope, this will solve your problem.

New Malware That Empty Your Bank Account

New Malware That Empty Your Bank Account

New Malware has been created by the hackers that can steal usernames and passwords and defeat common methods of user authentication employed by financial institutions. The important point is that it updates the bank account transaction virtually and it becomes really impossible for the account holder to know if the account has been hacked or not, as it doesn't show any changes in the transaction.

How it Works:
Through the fake mail like for job email, free game download or get unsolicited e-mail from NACHA, the Federal Reserve, or the FDIC telling him or her that there is a problem with his or her bank account or a recent ACH (Automated Clearing House) transaction. The message includes a link in the e-mail that will supposedly help resolve whatever the issue is."Unfortunately, the link goes to a phony website, and once you’re there, you inadvertently download the Gameover malware, which promptly infects your computer and steals your banking information," the FBI said.

Prevent:
The best way to prevent this fraud way of money laundering is to keep your eyes open. Don't ever clicked on any email link from unknown source or if it is asking for bank information. Verify before clicking the link. Don't disclose your Bank related Information on the internet.
Have A Happy Internet Banking :)

Java Unsupported Class Version Error-II

Java Unsupported Class Version Error - II

In the last post we have seen about the Java Unsupported Class Version. In this post we will see more on that.

What is UnSupportedClassVersionError in Java?

Java.lang.UnsupportedClassVersionError is a subclass of java.lang.ClassFormatError. This is a kind of linking error which occurs during linking phase accordingly java.lang.ClassFormatError has also derived from java.lang.LinkageError. As the name suggests "UnSupportedClassVersionError" so it’s related to unsupported class version, now questions comes what is class version in Java? Well every source file is compiled into class file and each class file has two versions associated with it, major version and minor version. Version of class file is represented as major_version.minor_version. This version is used to determine format of class file in Java.
According to Java Virtual Machine specification, “A JVM implementation can support a class file format of version v if and only if v lies in some contiguous range Mi.0 v Mj.m. Only Sun can specify what range of versions a JVM implementation conforming to a certain release level of the Java platform may support.” For example: JDK 1.2 supports class file formats from version 45.0 to version 46.0 inclusive. So if a class file has version 48.0 it means that major version of class file is "48" and minor version is "0", which tells us that JDK 1.4 has been used to compile and generate that class file


How to fix UnSupportedClassVersionError

Now we know the root cause of UnSupportedClassVersionError that we are using a lower JVM for running the program. But major problem is that stack trace of UnSupportedClassVersionError will not tell you for which class it’s coming. So if you are using multiple third party jars in your application you find that it comes at a particular part when JVM tries to load a class from a particular jar. anyway we all know that latest version of JDK is 1.6 so maximum version of class file could be generated by JDK 6, so by using JDK 6 we can solve UnSupportedClassVersionError, but many times its not easy to just move to higher JDK version. So I would suggest:
1) Find out due to which jar or class file this UnSupportedClassVersionError is coming?
2) Try to compile source code of that jar with the JDK version you are using to run your program, if source is available.
3) If you don't have source try to find the compatible version of that library.
4) Increase the JRE version you are using to run your program.

When UnSupportedClassVersionError in Java comes:


So now we got the theory behind class file format and major and minor version of class file in Java. Now a million dollar question is when UnSupportedClassVersionError in Java does occur? precise answer of this is "When JVM tries to load a class and found that class file version is not supported it throws UnSupportedClassVersionError and it generally occurs if a higher JDK version is used to compile the source file and a lower JDK version is used to run the program. for example if you compile your java source file in JDK 1.5 and you will try to run it on JDK 1.4 you will get error "java.lang.UnsupportedClassVersionError: Bad version number in .class file [at java.lang.ClassLoader.defineClass1(Native Method)]".
But its important to note is that vice-versa is not true "you can compile your program in J2SE 1.4 and run on J2SE 1.5 and you will not get any UnSupportedClassVersionError". When a higher JDK is used for compilation it creates class file with higher version and when a lower JDK is used to run the program it found that higher version of class file not supported at JVM level and results in java.lang.UnsupportedClassVersionError

Major Class Versions of Various JDK
Following are the major version of class file format in standard JDK environment.
JDK 1.1 = 45
JDK 1.2 = 46
JDK 1.3 = 47
JDK 1.4 = 48
JDK 1.5 = 49
JDK 1.6 = 50

Java Unsupported Class Version Error

Java Unsupported Class Version Error

Java Unsupported Class Version Error occurs when we try to compile the class which has a jar file attached in its classpath and that jar file has been compiled with higher version of java then the one with which  we are trying to compile the class.

This error comes on using different java versions for compilation and execution of java program. Therefore set the path of one java version and use it for compilation and execution.

java.lang.UnsupportedClassVersionError: XXXX (Unsupported major.minor version 49.0)

        at java.lang.ClassLoader.defineClass0(Native Method)
        at java.lang.ClassLoader.defineClass(ClassLoader.java:539)
        at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:123)
        at java.net.URLClassLoader.defineClass(URLClassLoader.java:251)
        at java.net.URLClassLoader.access$100(URLClassLoader.java:55)
        at java.net.URLClassLoader$1.run(URLClassLoader.java:194)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.net.URLClassLoader.findClass(URLClassLoader.java:187)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:289)
        at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:274)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:235)
        at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:302)

 If you get the above errors, do the following:
       1) Check the jar file attached in the classpath.
       2) Use the higher version (or equal but not lesser) of java for compiling the class then used for creating  the jar.
      3) Set the path of one java version and use it for compilation and execution.

Speed Up The File Search Indexing

Speed Up The File Search Indexing

We can configure the indexing of windows to make the search fast. We can exclude the zip file while searching. We can do this in following ways:

From the Start menu's Run dialog, enter this command:

                         regsvr32 /u zipfldr.dll.
then enter
                         regsvr32 /u cabview.dll.
Then restart the windows.

Completely Disable Indexing
If you’d prefer to completely disable the indexing service, you can disable it entirely by turning off the service.

Open up Services through control panel, or by typing services.msc into the start menu search box. Find “Windows Search” in the list of services and double-click on it to open it.Change the Startup type of the service to Disabled, and then click the Stop button to stop the service.