Sunday, June 26, 2011

C3P0 DataSource Config (Connection-Pool) !

<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
    <property name="driverClass" value="${jdbc.driverClassName}"></property>
    <property name="jdbcUrl" value="${jdbc.url}" />
    <property name="user" value="${jdbc.username}" />
    <property name="password" value="${jdbc.password}" />
    <property name="initialPoolSize" value="5"></property>
    <property name="minPoolSize" value="5"></property>
    <property name="maxPoolSize" value="15" />
    <property name="checkoutTimeout" value="1000" /> <!-- Wartezeit auf freie Pool-Connection -->
    <property name="maxStatements" value="50"></property>
    <property name="automaticTestTable" value="C3P0_TEST_TABLE"></property>
    <property name="testConnectionOnCheckin" value="true"></property>
    <property name="idleConnectionTestPeriod" value="60"></property> <!-- in Sekunden -->
</bean>

programmatically compiling a Java source file..!

  /**
     * compiles a java source file with the given <code>fileName</code>
     *
     * @param fileName
     */
    @SuppressWarnings({ "rawtypes", "unchecked" })
    public void compile(String fileName)
    {
        /*
         * the compiler will send its messages to this listener
         */
        DiagnosticListener listener = new DiagnosticListener()
        {
            public void report(Diagnostic diagnostic)
            {
                System.err.println("gond: " + diagnostic.getMessage(null));
                System.err.println("sor: " + diagnostic.getLineNumber());
                System.err.println(diagnostic.getSource());
            }
        };
       
        // getting the compiler object
        JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
        StandardJavaFileManager manager = compiler.getStandardFileManager(null, null, null);
       
        Iterable<? extends JavaFileObject> files = manager.getJavaFileObjects(fileName);
       
        JavaCompiler.CompilationTask task = compiler.getTask(null, manager, listener, null, null, files);
       
        // the compilation occures here
       
        task.call();
    }

Read a web page with Java !

public String readURL(String address) throws Exception
    {
        URL url = new URL(address);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setReadTimeout(5000);
        conn.setConnectTimeout(5000);
       
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        byte[] buff = new byte[1024];
        InputStream in = conn.getInputStream();
        int read;
       
        while ((read = in.read(buff)) != -1)
            out.write(buff, 0, read);
       
        return out.toString().replaceAll("[\\s]+", " ");
    }


Shortest Java program to do wget:

 public static void main(String[] args) throws Exception
    {
        String s;
        BufferedReader r = new BufferedReader(new InputStreamReader(new URL(args[0]).openStream()));
        while ((s = r.readLine()) != null)
        {
            System.out.println(s);
        }
    }

ScreenShots in Java.!

import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.File;

import javax.imageio.ImageIO;

import org.apache.log4j.Logger;

import com.mt.classification.InterfaceAudience;
import com.mt.classification.InterfaceStability;

/**
 * TODO Description go here.
 *
 * @author Varra
 * @version 1.0
 *
 */
@InterfaceAudience.Public
@InterfaceStability.Evolving
public class Screen2Image
{
  
    /** The logger to log the debugging messages as application runs. */
    private static final Logger logger = Logger.getLogger(Screen2Image.class);
  
    public static void main(String[] args) throws Exception
    {
        Robot robot = new Robot();
        BufferedImage screenShot = robot.createScreenCapture(new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()));
        ImageIO.write(screenShot, "JPG", new File("screenShot.jpg"));
    }
}

Thursday, June 23, 2011

javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target!


javax.net.ssl.SSLHandshakeException:
sun.security.validator.ValidatorException: PKIX path building failed:
sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
Are you getting this error? 

This simply means that the web server or the URL you are connecting to does not have a valid certificate from an authorized CA.
But however, being a programmer you would want to find out the alternative way
to solve this issue.
What you need to do is to import the server certificate and install it in your JDK's keystore. If I am talking greek, its ok. I too just leant this.

Just follow these steps and you will be able to get rid of that error.

1. First of all you copy the URL that you are connecting to and paste it in your browser. Let us say you are using IE. Just paste the url in the address bar and press enter.

2. You will now probably see a dialog box warning you about the certificate. Now click on the 'View Certificate' and install the certificate. Ignore any warning messages.

3. Now that the server certificate is installed in your computer, your browser will not warn you when you visit the same site again. But however your JRE dumb as it is does not yet know about this certificate's existence until you add it to its keystore. Usually you will use the keytool to manage certificates.
Keytool is a command-line utility with numerous arguments that allow you to create and manage keystores for housing digital certificates. For the complete documentation of keytool,
 http://java.sun.com/j2se/1.3/docs/tooldocs/win32/keytool.html

4. You can list the current certificates contained within a keystore using they keytool -list command. The initial password for the cacerts keystore is changeit. For example:
    /home/krishna/java/jdk1.6/jre/bin>keytool -list -keystore ..\lib\security\cacerts Enter keystore password: changeit You will then see the something like this: Keystore type: jks Keystore provider: SUN Your keystore contains 11 entries: engweb, Wed Apr 11 16:22:49 EDT 2001, trustedCertEntry, Certificate fingerprint (MD5): 8C:24:DA:52:7A:4A:16:4B:8E:FB:67:44:C9:D2:E4:16 thawtepersonalfreemailca, Fri Feb 12 15:12:16 EST 1999, trustedCertEntry, Certificate fingerprint (MD5): 1E:74:C3:86:3C:0C:35:C5:3E:C2:7F:EF:3C:AA:3C:D9 thawtepersonalbasicca, Fri Feb 12 15:11:01 EST 1999, trustedCertEntry, Certificate fingerprint (MD5): E6:0B:D2:C9:CA:2D:88:DB:1A:71:0E:4B:78:EB:02:41 verisignclass3ca, Mon Jun 29 13:05:51 EDT 1998, trustedCertEntry, Certificate fingerprint (MD5): 78:2A:02:DF:DB:2E:14:D5:A7:5F:0A:DF:B6:8E:9C:5D thawteserverca, Fri Feb 12 15:14:33 EST 1999, trustedCertEntry, Certificate fingerprint (MD5): C5:70:C4:A2:ED:53:78:0C:C8:10:53:81:64:CB:D0:1D thawtepersonalpremiumca, Fri Feb 12 15:13:21 EST 1999, trustedCertEntry, Certificate fingerprint (MD5): 3A:B2:DE:22:9A:20:93:49:F9:ED:C8:D2:8A:E7:68:0D
      verisignclass4ca, Mon Jun 29 13:06:57 EDT 1998, trustedCertEntry, Certificate fingerprint (MD5): 1B:D1:AD:17:8B:7F:22:13:24:F5:26:E2:5D:4E:B9:10 verisignclass1ca, Mon Jun 29 13:06:17 EDT 1998, trustedCertEntry, Certificate fingerprint (MD5): 51:86:E8:1F:BC:B1:C3:71:B5:18:10:DB:5F:DC:F6:20
    verisignserverca, Mon Jun 29 13:07:34 EDT 1998, trustedCertEntry, Certificate fingerprint (MD5): 74:7B:82:03:43:F0:00:9E:6B:B3:EC:47:BF:85:A5:93 thawtepremiumserverca, Fri Feb 12 15:15:26 EST 1999, trustedCertEntry, Certificate fingerprint (MD5): 06:9F:69:79:16:66:90:02:1B:8C:8C:A2:C3:07:6F:3A verisignclass2ca, Mon Jun 29 13:06:39 EDT 1998, trustedCertEntry, Certificate fingerprint (MD5): EC:40:7D:2B:76:52:67:05:2C:EA:F2:3A:4F:65:F0:D8
5. Now you have to add the previosly installed certificate to this keystore. To add, begin by exporting your CA Root certificate as a DER-encoded binary file and save it as /home/myCert.cer.
(you can view the installed certificates under Tools->'Internet Options'->Content->Certificates

Once you open the certificates, locate the one you just installed under 'Trusted Root Certification Authorities".
Select the right one and click on 'export'. You can now save it (DER encoded binary) under your /home/.

6. Then use the keytool -import command to import the file into your cacerts keystore. 
    For example: keytool -import -alias myCert -keystore ..\lib\security\cacerts -file /home/.cer
Enter keystore password: changeit
Owner: CN=Division name, OU=Department, O=Your
Company, L=Anytown,


ST=NC, C=US, EmailAddress=you@company.com
Issuer: CN=Division name, OU=Department,
O=Your Company, L=Anytown,

ST=NC, C=US, EmailAddress=you@company.com
Serial number:
79805d77eecfadb147e84f8cc2a22106

Valid from: Wed Sep 19 14:15:10 EDT 2001
until: Mon Sep 19 14:23:20 EDT 2101

Certificate fingerprints:
MD5:
B6:30:03:DC:6D:73:57:9B:F4:EE:13:16:C7:68:85:09

SHA1:
B5:C3:BB:CA:34:DF:54:85:2A:E9:B2:05:E0:F7:84:1E:6E:E3:E7:68


Trust this certificate? [no]: yes
Certificate was added to keystore
7. Now run keytool -list again to verify that your private root certificate was added:
    /home/krishna/java/jdk1.6/jre/bin>keytool -list -keystore ..\lib\security\cacerts

You will now see a list of all the certificates including the one you just added.
This confirms that your private root certificate has been added to the Extranet server cacerts keystore as a trusted certificate authority.

And then run your java program by setting the trustStroe to java App as given below.
java -Djavax.net.ssl.trustStore=/home/krishna/java/jdk1.6/jre/lib/security/cacerts -Djavax.net.ssl.trustStorePassword=changeit <your Program name>

If this tutorial doesn't answer your question, and you have a specific question.
Post your question to get a direct answer.


Wednesday, June 22, 2011

The best way to iterate through a HashMap in java.!

If you're only interested in the keys, you can iterate through the keySet() of the map:


Map<String, Object> map = ...;
for (String key : map.keySet()) {
    // ...
}
 
If you only need the values, use values():
 
for (Object value : map.values()) {
    // ...
}
 
Finally, if you want both the key and value, use entrySet():
 
for (Map.Entry<String, Object> entry : map.entrySet()) {
    String key = entry.getKey();
    Object value = entry.getValue();
    // ...
}
 
One caveat: if you want to remove items mid-iteration, you'll need to do so via an Iterator. However, changing item keys and values is OK (see Map.Entry).
 
        //Map -> Set -> Iterator -> Map.Entry -> troublesome
        Iterator iterator=map.entrySet().iterator();
        while(iterator.hasNext()) 
        {
            Map.Entry mapEntry=(Map.Entry)iterator.next();
            System.out.println("The key is: "+mapEntry.getKey() + ",value is :"+mapEntry.getValue());
        }
 
        //more elegant way
        for (Map.Entry<String, String> entry : map.entrySet()) 
       {
            System.out.println("Key : " + entry.getKey() + " Value : " + entry.getValue());
        }
 
        //weired way, but work anyway
        for (Object key: map.keySet()) 
{
            System.out.println("Key : " + key.toString() + " Value : " + map.get(key));
        }
 
Cheers,
varra
 
 

Difference between ConcurrentHashMap and Hashtable !

So what is the difference between Hashtable and ConcurrentHashMap?

both can be used in multithreaded environment but once the size of Hashtable becomes considerable large performance degrade because for iteration it has to be locked for longer duration.

Since ConcurrentHashMap introduced concept of segmentation , how large it becomes only certain part of it get locked to provide thread safety so many other readers can still access map without waiting for iteration to complete.

In Summary ConcurrentHashMap only locked certain portion of Map while Hashtable lock full map while doing iteration.

Create, Update, Remove the Symbolic links in Linux/Unix..!

Creating a symbolic link or symlink in UNIX:

Syntax:  ln -s {target-filename} {symbolic-filename}
Eg:         ln -s /krishna/firefox/firefox    /usr/bin/firefox
     -->   cd /usr/bin/
     -->   ls -lrt firefox
output:
             firefox ->  /krishna/firefox/firefox


Updating a symbolic link or symlink in UNIX:

Syntax:  ln -nsf {target-filename} {symbolic-filename}
Eg:         ln -nsf /krishna/newFirefox/firefox    /usr/bin/firefox
     -->   cd /usr/bin/
     -->   ls -lrt firefox
output:
             firefox ->  /krishna/newFirefox/firefox

 


Removing a symbolic link or symlink in UNIX:

Removing a symbolic link is similar to removing any file; 

You need to use “rm” UNIX command to remove any symlink. 

This will only removes symlink and not delete the source directory.

 

Syntax: rm {symbolic-filename}
Eg:        rm /usr/bin/firefox
     -->   cd /usr/bin/
     -->   ls -lrt firefox
output:
             ls: firefox: No such file or directory

Cheers,

Create user in linux with root privileges linux,unix.!

adduser -u 0 -o -g 0 -G 0,1,2,3,4,6,10 -M root2

adduser  : Command to create a user in linux
-u           : Set the value of user id to 0 which is generally root user id.
-o            : Set the value of user id to 0 which is generally root user id.
-g           :  Set the initial group number to to 0 generally root user group
-G           : Supplementary groups 0=root, 1=bin, 2= daemon, 3 = sys, 4=adm, 6=disk, 10 = wheel
-M          : 
User home directory will not be created




There are so many other ways too .. !!

Tuesday, June 21, 2011

Java Should Have Extended Enums!

At Devoxx09, Joe Darcy presented the status and future of the Coin project, and how changes to the language are selected and implemented (or vice versa).
During his talk, he showed the cost classification of a language change: trivial, small, medium, big, or huge, and emphasized the fact that each change is also a benefit (hard to measure a priori) that can be estimated as big, medium, or small.
For example, the new loop syntax introduced in Java5 was a small change with big benefits—a no "brainer", let's do it!

However, in his talk he showed how "Extended Enums" were at least medium cost with a small benefit.

I started working on "Extended Enums" (previously "abstract enum") since the release of OpenJDK and the launch of the now defunct KSL (Kitchen Sink Language) in 2006. From the amount of hits this blog is getting on "extended enums", I know this issue is of big concern for many Java developers. I developed a working solution, but stopped pushing for it for two main reasons:

  • This addition to the language is a change to the Java-type system. Moreover, it cannot be a small modification; it is at least a medium change.
  • Looking at Scala Traits or Fantom Mixin, I had the feeling that it was pushing Java too much, and perhaps in the wrong direction.

I talked with Joe Darcy at Devoxx09 about all the things I discovered implementing this change to the javac compiler (and other needed changes to the JDK classes). It was clear that the change is medium size, but I disagree that the benefits are small.
The benefits of "Extended enums" as implemented today:
  • Ability for enum declaration to extend an actual abstract class
    This is the evident benefit, and it is a small benefit. Using delegation and/or in-lined anonymous classes is not too verbose and provides the same benefits. Still it is nicer and cleaner to have the normal OO inheritance.
  • Ability to use Generics in Enum classes With "Extended enums" you can have code like this:
    public enum ActionQuery { ALL { public List getResults() {...} }, EDIT_ACTION { public List getResults() {...} }, VIEW_ACTION { public List getResults() {...} }; public abstract List getResults(); } I find "Extended enums" very useful in organizing SQL queries and their results, playing with properties and their types, and so on.
  • The most important feature and the reason why I developed "Extended enums" was to have the ability to define annotation enum parameters without having to specify their list of values in advance. You can already see this issue in today's JPA specification. There is an enum FetchType that is fixed in the spec to LAZY and EAGER, but Hibernate also supports SUBSELECT, which is approximately between LAZY and EAGER. To support SUBSELECT, you need to use the Hibernate specific annotation in combination with the standard one. If the FetchType was an abstract enum, the JPA specification does not need to enforce a well-defined list, but could have a proposed DefaultFetchType and let JPA implementation and application developers define a new enum with their desired list of FetchType. This already works great in the "abstract enum" implementation and provides me with great benefits in many other areas: (such as BindingType in JSR-299 Context and Dependency Injection, Cache declaration using enum instead of error prone string for region, Group in JSR-303 Bean Validation using user defined enums instead of empty interfaces, and more).

From my point of view (and I think/hope I'm not alone), Joe Darcy missed the benefit point of the extended enum. It is a big benefit to the Java language.
This was and is my position for some time. What pushed me to re-launch "Vote for Extended Enums for the Coin project!", is of course Christof May from soplets.org (which setup the extended-enums site: http://www.extended-enums.org/), and the fact that I found a way to make the change a "small" one. Until now, I was sure that to implement this correctly a new flag was needed in the class byte code, and many changes to the Java type management were necessary.

So, if you are interested or want to learn more please check the extended enums web site: http://www.extended-enums.org/
Article Type: 
Opinion/Editorial