RSS

Monthly Archives: February 2013

Eclipse IDE Shortcuts – More

Hi folks,

Posting some more eclipse IDE short cuts. Hope this will reduce development time for some extent.

eclipse_shortcuts

Enjoy coding 🙂

Get glue for more updates.

Have a nice day 🙂

 
Leave a comment

Posted by on February 27, 2013 in Uncategorized

 

Core Java Tutor

Hi folks,

Here is the good Core Java tutorial with explanation and sample examples. Hope this site will helps you.

http://devmanuals.com/tutorials/java/corejava/index.html

–> Its good start for the beginners to learn each and every concept of corejava with example code.

–> For experience folks, it helps to brushup the concept once.

Happy Learning!

Have a nice day 🙂

 
Leave a comment

Posted by on February 27, 2013 in Uncategorized

 

Proper Use of SecureRandom – Java

Hi folks,

This is the continuation of my earlier post on Secure Random Number generation. This post gives you the indepth knowledge on

1. How to use SecureRandom
2. When to use SecureRandom

— When generating random numbers in Java for cryptographic purposes, many developers often use the java.security.SecureRandom class. And while the java.security.SecureRandom class is designed to generate cryptographically secure random numbers, there are a few subtleties in the API, and if it is used improperly the output can become predictable. At Cigital we have witnessed a number of cases where this is true. The following is a guide to the proper use of Java’s java.security.SecureRandom class.

— First, let’s take a quick look at how the java.security.SecureRandom API works. The java.security.SecureRandom class does not actually implement a pseudorandom number generator (PRNG) itself. It uses PRNG implementations in other classes to generate random numbers. A number of actual PRNGs may actually be used when an instance of java.security.SecureRandom is created. The PRNGs are part of Java cryptographic service providers (CSPs).

— In Sun’s Java implementation, the SUN CSP is used by default. On Windows, the SUN CSP uses the SHA1PRNG implemented in sun.security.provider.SecureRandom by default. On Solaris and Linux, the SUN CSP default is to use sun.security.provider.NativePRNG which simply provides the output of the /dev/urandom PRNG provided by the operating system. If however, on Solaris/Linux, the java.security configuration file in the JRE is modified such that securerandom.source is set to something other than file:/dev/urandom, then the SHA1PRNG implemented in sun.security.provider.SecureRandom is used, as on Windows. Of course, an application can choose not to use the defaults, and can always specify a particular PRNG implemented by a particular cryptographic provider. In Cigital’s experience, most Java applications that use java.security.SecureRandom actually use the SHA1PRNG provided by the SUN CSP under the cover.

Now, an application will end up with an instance of SHA1PRNG implemented in sun.security.provider.SecureRandom using the following calls:

SecureRandom sr1 = new SecureRandom();

// The following will create SUN SHA1PRNG if the highest
// priority CSP is SUN
SecureRandom sr2 = SecureRandom.getInstance(“SHA1PRNG”);

// The following will always create SUN SHA1PRNG
SecureRandom sr3 = SecureRandom.getInstance(“SHA1PRNG”, “SUN”);

-> Note that according to Sun’s documentation, the returned java.security.SecureRandom instance is not seeded by any of these calls. If after one of these calls, java.security.SecureRandom.nextBytes(byte[]) is called, then the PRNG is seeded using a secure mechanism provided by the underlying operating system (starting with JRE 1.4.1 in Windows and JRE 1.4.2 in Linux and Solaris). If java.security.SecureRandom.setSeed(long) or java.security.SecureRandom.setSeed(byte[]) is called before a call to java.security.SecureRandom.nextBytes(byte[]), then the internal seeding mechanism is bypassed, and only the provided seed is used to generate random numbers.

-> For those who are not familiar with the inner workings of cryptographic PRNGs, their job is to take a relatively small random seed and use it to produce deterministic output that seems random to anybody that does not know what the seed is. The PRNG tries to ensure that the output does not reveal any information about the seed, and that somebody observing the output cannot predict future outputs without knowing the seed.

-> By bypassing the internal secure seeding mechanism of the SHA1PRNG, you may compromise the security of your PRNG output. If you seed it with anything that an attacker can potentially predict (e.g. the time when the PRNG instance was created), then using java.security.SecureRandom may not provide the level of security that you need.

-> Finally, regardless of how well the PRNG is seeded, it should not be used indefinitely without reseeding. There are two approaches that can be used for longer-term security of PRNG output:

-> Periodically throw away the existing java.security.SecureRandom instance and create a new one. This will generate a new instance with a new seed.
Periodically add new random material to the PRNG seed by making a call to java.security.SecureRandom.setSeed(java.security.SecureRandom.generateSeed(int)).
In summary, keep the following in mind when using java.security.SecureRandom:

-> Always specify the exact PRNG and provider that you wish to use. If you just use the default PRNG, you may end up with different PRNGs on different installations of your application that may need to be called differently in order to work properly. Using the following code to get a PRNG instance is appropriate:

SecureRandom sr = SecureRandom.getInstance(“SHA1PRNG”, “SUN”);

-> When using the SHA1PRNG, always call java.security.SecureRandom.nextBytes(byte[]) immediately after creating a new instance of the PRNG. This will force the PRNG to seed itself securely. If for testing purposes, you need predictable output, ignoring this rule and seeding the PRNG with hard-coded/predictable values may be appropriate.
Use at least JRE 1.4.1 on Windows and at least JRE 1.4.2 on Solaris and Linux. Earlier versions do not seed the SHA1PRNG securely.
Periodically reseed your PRNG as observing a large amount of PRNG output generated using one seed may allow the attacker to determine the seed and thus predict all future outputs.

Happy Learning!.

Get glued to know more updates.

Have a nice day:-)

 

 
Leave a comment

Posted by on February 26, 2013 in Uncategorized

 

How to Validate input XML with XSD using Java SAXParser

Hi folks,

Today i am posting an intresting topic on Java SAXParser with example coding.

Requirement : Parsing input XML with XSD using Java SAXParser

Solution:

Using SAXParserFactory and SchemaFactory, we can successfully achive the above requirement. Below is the working code posted for your reference. Hope this code saves your development time to some extent.

XMLParser.java

import java.io.IOException;
import javax.xml.XMLConstants;
import javax.xml.bind.JAXBException;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.SchemaFactory;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;

public class XMLParser {
public static void main(String[] args) throws JAXBException {
try {
javax.xml.parsers.SAXParserFactory factory = javax.xml.parsers.SAXParserFactory.newInstance();
factory.setValidating(true);
factory.setNamespaceAware(true);
SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
factory.setSchema(schemaFactory.newSchema(new Source[] {new StreamSource(“contacts.xsd”)}));
SAXParser parser = factory.newSAXParser();
XMLReader reader = parser.getXMLReader();
reader.setErrorHandler(new SimpleErrorHandler());
// added below line to fix issue : Document root element “package”, must match DOCTYPE root “null”
reader.setFeature(“http://apache.org/xml/features/validation/dynamic”, true);
reader.parse(“contacts.xml”);
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}

SimpleErrorHandler.java

import org.xml.sax.ErrorHandler;
import org.xml.sax.SAXParseException;

public class SimpleErrorHandler implements ErrorHandler {
public void warning(SAXParseException e) {
System.out.println(e.getMessage());
e.printStackTrace();
}

public void error(SAXParseException e) {
System.out.println(e.getMessage());
e.printStackTrace();
}

public void fatalError(SAXParseException e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}

contacts.xsd

<?xml version=”1.0″ encoding=”UTF-8″?>
<xs:schema xmlns:xs=”http://www.w3.org/2001/XMLSchema”&gt;
<xs:element name=”contacts”>
<xs:complexType>
<xs:sequence>
<xs:element ref=”contact” />
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name=”contact”>
<xs:complexType>
<xs:sequence>
<xs:element name=”firstname” type=”xs:NCName” />
<xs:element name=”lastname” type=”xs:NCName” />
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>

contacts.xml

<contacts xsi:noNamespaceSchemaLocation=”contacts.xsd”
xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance”&gt;
<contact >
<firstname>Edwin</firstname>
<lastname>Dankert</lastname>
</contact>
</contacts>

Issue

When i ran the application using the above code, i got below exception

org.xml.sax.SAXParseException: Document root element “package”, must match DOCTYPE root “null”

Solution

To resolve this issue, enable dynamic validation to parse the XML file by adding below line in the code.

XMLReader.setFeature(“http://apache.org/xml/features/validation/dynamic&#8221;, true);

Happy Coding!..

Get glued to know more updates.

Have a nice day 🙂

 
Leave a comment

Posted by on February 26, 2013 in Uncategorized

 

Why SecureRandom instead Random

Hi folks,

Here is the elaborated post regarding why use SecureRandom class instead Random class.

The purpose of these tokens is fairly sensitive – used for session id, password reset links etc. So they do need to be cryptographically random to avoid somebody guessing them or brute force them feasibly. The token is a “long” so it is 64 bits long.

For security purposes, it is very necessary that we use an API that helps us generate random numbers that are unique in nature and cannot be guessed easily. If the random numbers that we use in our application is can be guessed, it creates a loophole in the security of the application.

Java provides 2 classes for generating random numbers:

java.util.Random
java.security.SecureRandom

Random:

As mentioned in the Javadocs: “An instance of this class is used to generate a stream of pseudorandom numbers. The class uses a 48-bit seed, which is modified using a linear congruential formula” and it’s also mentioned in the Javadocs that “If two instances of Random are created with the same seed, and the same sequence of method calls is made for each, they will generate and return identical sequences of numbers”.By default, the seed for the Random algorithm is the system time in milliseconds, making the random numbers guessable.

The code currently uses the java.util.Random class to generate these tokens. The documentation (http://docs.oracle.com/javase/7/docs/api/java/util/Random.html) for java.util.Random clearly states that “Instances of java.util.Random are not cryptographically secure. Consider instead using SecureRandom to get a cryptographically secure pseudo-random number generator for use by security-sensitive applications.”

SecureRandom:

“This class provides a cryptographically strong pseudo-random number generator (PRNG)”, as mentioned in the Javadocs. Since the random numbers generated by this class are cryptographically secure, it makes the random numbers non guessable and random in true sense.

It is also important to consider, in which areas of the application we should use SecureRandom class, as the SecureRandom class lowers the performance of the application. But where the security of the application is in question, for example; generating the sessionIds, we must always use the SecureRandom class.

Eg : SecureRandom secureRandom = new SecureRandom();
System.out.println(secureRandom.nextInt());

Happy Learning!

Get glued to know more.

Have a nice day 🙂

 
Leave a comment

Posted by on February 26, 2013 in Uncategorized

 

Eclipse IDE Shortcuts

Hi folks,

Today i am posting some eclipse ide shortcuts. Hope this will save some development time. Enjoy the work 🙂

S.No Key Description
1 Cltr + 1 Suggestions prompt box
2 Cltr + 3 Previous open files list
3 Cltr + 7 Comment / Uncomment Line of code
4 Cltr + F1 Help Content window
5 Cltr + F3 Show Inherited members
6 Cltr + F4 Close File or window
7 Cltr + F6 Show List of opened files in the middle of IDE
8 Cltr + F7 Shows List of Views
9 Cltr + F8 Shows List of Perspective
10 Cltr + F9 Open Active Task window
11 Cltr + F10 Toggle / Disable break point
12 Cltr + F11 Run Java Application
13 Shift + F1 Help Window
14 Shift + F10 Right Click menu
15 Cltr+shift+R Open Resource (tip to open file very fast)
16 Cltr+shift+O Organize imports in a Java File
17 Cltr+shift+A Open Plug-In Artifact
18 Cltr+shift+B Enable / Disable break point
19 Cltr+shift+C Comment Line
20 Cltr+shift+E Opens Switch to Editor window
21 Cltr+shift+H Open Type in Hierarchy window
 
Leave a comment

Posted by on February 25, 2013 in Uncategorized

 

Display list of files in the given directory

Hi folks,

Yesterday one of my colleague was aksing, how to get list of available .txt files from the given directory. Here is the post with code to fetch the list of files from the given path (list of files in the folder).

public class ListOfFilesDemo
{
public static void main(String[] args) {
// Directory path here
String path = “.”;
String fileName;
File folder = new File(path);
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++){
if (listOfFiles[i].isFile()) {
fileName = listOfFiles[i].getName(); // Line1
System.out.println(“Filename :: “+fileName);
}
}
}
}

If you want to list only .txt files, put the below code after Line1 in the above program:

if (fileName!= null && (fileName.endsWith(“.txt”) || fileName.toUpperCase().endsWith(“.TXT”))){
    System.out.println(fileName);
}

Happy Coding 🙂

Get glued to know more updates.

Have a nice day.

 
Leave a comment

Posted by on February 25, 2013 in Uncategorized

 

Singleton Design Pattern and Double-Checked Locking

Hi folks,

Today i am posting some interesting topic on Singleton design pattern and Double-Checked Locking concepts. Below is the detailed post.

The singleton pattern is one of the simplest java design pattern. It involves only one class which is responsible to instantiate itself, to make sure it creates not more than one instance, in the same time it provides a global point of access to that instance. In this case the same instance can be used from everywhere, being impossible to invoke directly the constructor each time.

Main Objective:

1. Ensure that only one instance of a class is created.
2. Provide a global point of access to the object.

Examples : Logger Classes, Configuration Classes, Accesing resources in shared mode and Factories implemented as Singletons.

Singleton Code :

public class Singleton {

private static Singleton instance;

private Singleton() {
// TODO Auto-generated constructor stub
}

public static synchronized Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}

Double-Checked Locking

In the above mentioned sample code, works fine for multithreaded access to the getInstance() method. However, when you analyze it you realize that synchronization is required only for the first invocation of the method. Subsequent invocations do not require synchronization because the first invocation is the only invocation that executes the code which is the only line that requires synchronization. All other invocations determine that instance is non-null and return it. Multiple threads can safely execute concurrently on all invocations However, because the method is synchronized, you pay the cost of synchronization for every invocation of the method, even though it is only required on the first invocation.

In an effort to make this method more efficient, an idiom called Double-Checked Locking was came in to the picture and created. The idea is to avoid the costly synchronization for all invocations of the method. The cost of synchronization differs from JVM to JVM. In the early days, the cost could be quite high. As more advanced JVMs have emerged, the cost of synchronization has decreased, but there is still a performance penalty for entering and leaving a synchronized method or block. Regardless of the advancements in JVM technology, programmers never want to waste processing time unnecessarily.

Best Singleton Code

private static Singleton instance;

private Singleton() {
// TODO Auto-generated constructor stub
}

public static Singleton getInstance() {
if (instance == null) {
synchronized (Singleton.class) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}

Below are some reference URLS to know more information about Double-Checked Locking.

http://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html

http://www.coderanch.com/t/233962/threads/java/Double-checked-locking-Singleton

Happy Learning!.

Have a nice day.:-)

Get glued to know more updates.

 
Leave a comment

Posted by on February 23, 2013 in Uncategorized

 

Single Quote is converting to some special characters

Hi folks,

Recently i have faced one special character issue in JSP and got fixed, sharing with you all. Hope this will helps you. Here is the post.

Requirement :

Storing the JSP page fields like Name, Address and Email values in the Page1 and passing all these values to the next Page2. I have to send all these param
values to the other system to display all these values in their system.

Issue :

When i am passing these field values with single quote (like Name is Tes’t and Email is Tes’t@test.com), single quote is converting to some special characters
(‘) when sending the values from Page1 to Page2. Due to this it is faling to hit the other system.

Solution:

I have added escapeXml=”false” in the JSP JSTL tag.

escapeXml=”false” : The attribute value which is a must attribute and escapeXml attribute which takes a boolean value and is used to check whether there is any need to
convert the &, <, > etc to their character encoding codes.

var name = “<c:out value=”${bean.name}” escapeXml=”false”/>”;
var emailId = “<c:out value=”${bean.emailId}” escapeXml=”false”/>”;

Afte adding this modification, it is working as expected (Name is Tes’t and Email is Tes’t@test.com).

My Intension is sharing this issue is to reduce the developers time.

Happy Coding!.

Have a nice day.:-)

 
Leave a comment

Posted by on February 23, 2013 in Uncategorized

 

Disable browser caching for a specific JSP using HTML meta tag

Hi folks,

Recently i have faced one JSP page caching issue and sharing with you all, so that other people can not seek for the solution and not to waste their valuable time.
Here is the detailed post.

Issue details :

When i login in to the application and clicking on the home page link at the bottom in the application with out clicking on the logout button, it will navigate to the home page of the appliciation. There i have logout button while clicking on the logout button, it will logout properly. Without closing the browser and paste the application URL it is not asking the login page, instead it is directly navigating to the application without login page. So it’s a highly security issue i.e other customers can see the details of the previous customer. To resolve this issue, i have made the below code changes it worked fine.

<meta http-equiv=”cache-control” content=”max-age=0″ />
<meta http-equiv=”cache-control” content=”no-cache” />
<meta http-equiv=”expires” content=”Sat, 01 Sep 2001 00:00:00 GMT” />
<meta http-equiv=”pragma” content=”no-cache” />

Note: Normally developers will try putting the expires content value to “-1” , it won’t work. You have to assign timestamp value to make work it out.

Some Other Information:

It is possible to keep the browser from caching a JSP page response. The following hints added to the response header seem to prevent most modern
browsers from pulling pages out of cache when the same URL is “hit”:

<%
response.setHeader( “Pragma”, “no-cache” );
response.setHeader( “Cache-Control”, “no-cache” );
response.setDateHeader( “Expires”, 0 );
%>

The same effect can be achieved by using meta tags in the HTML header:

<meta http-equiv=”cache-control” content=”max-age=0″ />
<meta http-equiv=”cache-control” content=”no-cache” />
<meta http-equiv=”expires” content=”Sat, 01 Sep 2001 00:00:00 GMT” />
<meta http-equiv=”pragma” content=”no-cache” />

The Cache-Control header was added in HTTP 1.1, while the other two were also present in HTTP 1.0.

Happy Coding!

Have a nice day 🙂

 
Leave a comment

Posted by on February 23, 2013 in Uncategorized