Search This Blog

Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Wednesday, March 29, 2017

Simple JAVA : How to convert a List to String

Use following sample code to quick convert List to String with concatenation, power of StringUtil (apache ;))

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;

public class Test {

public static void main(String[] args) {

List a = new ArrayList();
a.add("tom");
a.add("jerry");
a.add("fun");
String s = StringUtils.join(a.toArray(),",");
System.out.println(s);

}

}

Out Put : tom,jerry,fun

Cheers,
Kapil

Friday, May 16, 2014

How to know the compile JDK version for any JAVA class



Following command will help to give version number :

javap -verbose classname | find "major"

Cheers,

Kapil 

Friday, December 21, 2012

Exploring treeset

Exporing treeset in following case study  :

Step 1 :  Just write a simple program which has main method as  below:
package com.examples.coll.set.treeset;

import java.util.Set;
import java.util.TreeSet;

public class TestTreeSet {

    public static void main(String args[]) {
        TestTreeSet t = new TestTreeSet();
        Set treeSet = new TreeSet(); // Declare Treeset of type intree
        intree tree1 =t.new intree("tree1");
        treeSet.add(tree1);// added one object into treeset
        for (intree t1 : treeSet) {
            t1.show(); // To print name
        }
    }
    class intree { // inner class , object of this class is added into treeset
        String name;
        intree(String name){ //Constructor
            this.name = name;
        }
        void show(){
            System.out.print(name); // to print name
        }
    }
}

Step 2 : Compile this program ... no compilation error ...hmmmm we are good to go then .
Let's try to run this ...
java TestTreeSet
Output : tree1

wow it is simple ... we have successfully added one object of "intree" into treeset. it means one object can be easily added into treeset and we will definatly get successfull result .

Step 3 : Not let's go to next step further , try to add some more objects of same type into tree..

package com.examples.coll.set.treeset;

import java.util.Set;
import java.util.TreeSet;

public class TestTreeSet {

    public static void main(String args[]) {
        TestTreeSet t = new TestTreeSet();
        Set treeSet = new TreeSet(); // Declare Treeset of type intree
        intree tree1 =t.new intree("tree1");
        intree tree2 =t.new intree("tree2");
        intree tree3 =t.new intree("tree3");
        treeSet.add(tree1);// added 1st object into treeset
        treeSet.add(tree2);// added 2nd object into treeset
        treeSet.add(tree3);// added 3rd object into treeset
        for (intree t1 : treeSet) {
            t1.show(); // To print name
        }
    }
    class intree { // inner class , object of this class is added into treeset
        String name;
        intree(String name){ //Constructor
            this.name = name;
        }
        void show(){
            System.out.print(name); // to print name
        }
    }
}

Run step 2 first to run the program :

Ouptut :
Exception in thread "main" java.lang.ClassCastException: com.examples.coll.set.treeset.TestTreeSet$intree cannot be cast to java.lang.Comparable
    at java.util.TreeMap.put(Unknown Source)
    at java.util.TreeSet.add(Unknown Source)
    at com.examples.coll.set.treeset.TestTreeSet.main(TestTreeSet.java:28)


Grrrrrrrrrrr error ..... something worng but what :-) .. let me go to api what jdk say about this ..
searching apiiiiiiii wait.........ohh got one rule and root cause of this error :



Rule : A TreeSet instance performs all element comparisons using its compareTo (or compare) method, so two elements that are deemed equal by this method are, from the standpoint of the set, equal.

And as per above rule let us  change the program ....

Step 4 : Impelemtes comparable interface and compareTo into the class of which object need to add into treeset as shown below .

package com.examples.coll.set.treeset;

import java.util.Set;
import java.util.TreeSet;

public class TestTreeSet {

    public static void main(String args[]) {
        TestTreeSet t = new TestTreeSet();
        Set treeSet = new TreeSet(); // Declare Treeset of type intree
        intree tree1 =t.new intree("tree1");
        intree tree2 =t.new intree("tree2");
        intree tree3 =t.new intree("tree3");
        treeSet.add(tree1);// added 1st object into treeset
        treeSet.add(tree2);// added 2nd object into treeset
        treeSet.add(tree3);// added 3rd object into treeset
        for (intree t1 : treeSet) {
            t1.show(); // To print name
        }
    }
    class intree implements Comparable{ // inner class , object of this class is added into treeset
        String name;
        intree(String name){ //Constructor
            this.name = name;
        }
        void show(){
            System.out.print(name); // to print name
        }
        @Override
        public int compareTo(Object arg0) {
            return 0;
        }
    }
}

Run step 2 first to run the program :
Ouput  : tree1

hurreyy.... successfully ran this program ... but .... wait ... I was expecting three records .. and it is showing only one ... grrrrrrrrrrr something wrong again but what ....let me go to api againn what jdk says about this ..
searching apiiiiiiii wait.........ohh got the problem .. compareTo method is returning always "0" ...h,, new rule :
Ruel2 : During add of another object into tree set it calls to compareTo method and should check object equality. if it returns false or "0" it will not add object into treeset.
Here all comparison returns "0" means all other objects can not be added and treeset contains only first one ..hence resulted as "tree1".   

Step 5 :  Let's modify compareTo method in following way to resolve above problem :

package com.examples.coll.set.treeset;

import java.util.Set;
import java.util.TreeSet;

public class TestTreeSet {

    public static void main(String args[]) {
        TestTreeSet t = new TestTreeSet();
        Set treeSet = new TreeSet(); // Declare Treeset of type intree
        intree tree1 =t.new intree("tree1");
        intree tree2 =t.new intree("tree2");
        intree tree3 =t.new intree("tree3");
        treeSet.add(tree1);// added 1st object into treeset
        treeSet.add(tree2);// added 2nd object into treeset
        treeSet.add(tree3);// added 3rd object into treeset
        for (intree t1 : treeSet) {
            t1.show(); // To print name
        }
    }
    class intree implements Comparable{ // inner class , object of this class is added into treeset
        String name;
        intree(String name){ //Constructor
            this.name = name;
        }
        void show(){
            System.out.print(name); // to print name
        }
        @Override
        public int compareTo(Object arg0) {
            if (name.equals(((intree)arg0).name)) {
                return 0;
            }
            return 1;
        }
    }
}

Run the step 2 again ..
Output : tree1tree2tree3

hurrayyyyy we got the expected result here . It means now if name string matches then object will not add into treeset otherwise it will.

Step 6 : Let's try how can we avoid null object into treeset ..

change compareTo as below :

package com.examples.coll.set.treeset;

import java.util.Set;
import java.util.TreeSet;

public class TestTreeSet {

    public static void main(String args[]) {
        TestTreeSet t = new TestTreeSet();
        Set treeSet = new TreeSet(); // Declare Treeset of type intree
        intree tree1 =t.new intree("tree1");
        intree tree2 =t.new intree("tree2");
        intree tree3 =t.new intree("tree3");
        intree tree4 = t.new intree(null); // line 26
        treeSet.add(tree1);// added 1st object into treeset
        treeSet.add(tree2);// added 2nd object into treeset
        treeSet.add(tree3);// added 3rd object into treeset
        treeSet.add(tree4); // line 31
        for (intree t1 : treeSet) {
            t1.show(); // To print name
        }
    }
    class intree implements Comparable{ // inner class , object of this class is added into treeset
        String name;
        intree(String name){ //Constructor
            this.name = name;
        }
        void show(){
            System.out.print(name); // to print name
        }
        @Override
        public int compareTo(Object arg0) {
            if (name == null || ((intree)arg0).name == null)
            {
                return 1; // or return 0 @ line 61
            }
            else if (name.equals(((intree)arg0).name)) {
                return 0;
            }
            return 1;
        }
    }
}

Observe line 26 , 31 and 61
run the step 2 again :

Ouput : tree1tree2tree3null

And if we do the change at line 61 to "return 0" it will never allow to add null..and output in this case ..

Output : tree1tree2tree3

Rule 3 : null can be allowd into treeset but it is based on implementation . put a check for null to avoid null pointer and handle it gracefully . which can be done by compareTo.

Rule 4 :  Remeber if only one object is adding into treeset.. then call will never go compareTo method . It also happens if more than one object need to add into treeset. Please check step 1.

Cheers

Kapil


Tuesday, April 26, 2011

Java Date Format is not synchronized - Be carefull in Multi threading applications

JAVA Tips:

Date formats are not synchronized.

It is recommended to create separate format instances for each thread. If multiple threads access a format concurrently, it must be synchronized externally.

Ref: http://download.oracle.com/javase/1.4.2/docs/api/java/text/DateFormat.html

Tuesday, March 15, 2011

Initialize the log4j config with JVM configuration

Following JVM args can easily help to configure the your customized log4j properties for logging purpose

-Dlog4j.configuration=file:/E:/myWorkSpace/Practice/src/config/log4j.properties

Cheers

Tuesday, January 11, 2011

Create P12 from JKS - An enhancement in JDK1.6

Simple command is as follow:

keytool -importkeystore -srckeystore common.jks -destkeystore mystore.p12 -srcstoretype JKS -deststoretype PKCS12 -srcstorepass abc123 -deststorepass abc123 -srcalias fsf-wsweb-cert -destalias fsf-wsweb-cert -srckeypass password -destkeypass password -noprompt

Ignore the warning ...


Cheers

Kapil

Sunday, June 6, 2010

java.lang.ClassCastException: weblogic.net.http.SOAPHttpsURLConnection - Weblogic

While making a HTTP(s) connection to external resource from weblogic server following exception comes because underline API uses weblogic implemntation ..

Caught Exception creating connection: java.lang.ClassCastException: weblogic.net.http.SOAPHttpsURLConnection

to avoid this problem ..

set following flag in the JVM args ..

-DUseSunHttpHandler=true

It will prefer to use sun implementation..

Sunday, March 28, 2010

How to create min JS version using JAVA

Thnx to Yahoo Developer Network : YUI Compressor

following link can help to find the java utility to create compress version of js and css

http://developer.yahoo.com/yui/compressor/#work

Wednesday, February 24, 2010

Java Code to download attachments or any file from the database

Recently I got a requirement to save attachments into database and download it from UI (Inbox like yahoo or google ). And download attachment which received with the message , I did some research and write following java code as below to implement :

// content from BLOB
BlobDto dto = model.getFileContent();

// set header type
servletResponse.setHeader("Pragma", "");
servletResponse.setHeader("Cache-Control", "");
servletResponse.setHeader("Content-disposition",
"attachment; filename=" + model.getFileName());

// need to do proper content type , a check for content type
if (model.getFileType().equals("pdf"))
{
servletResponse.setContentType("application/pdf");
}
else if (model.getFileType().equals("xls")
|| model.getFileType().equals("csv"))
{
servletResponse.setContentType("application/vnd.ms-excel");
}
else
{
servletResponse.setContentType("application/octet-stream");
}

InputStream is = null;
try
{
OutputStream os = servletResponse.getOutputStream();
is = dto.getInputStream();
byte[] buf = new byte[1024];
int len;
while ((len = is.read(buf, 0, buf.length)) > 0)
{
os.write(buf, 0, len); // will give download window to save attachment
}
}
catch (FileNotFoundException e)
{
logger.error(e);
}
catch (IOException e)
{
logger.error(e);
}
finally
{
if (is != null)
{
try
{
is.close();
}
catch (IOException e)
{
logger.error("Failed to close InputStream", e);
}
}
}

Wednesday, February 10, 2010

How to read cert from trust store (jks) and use for TLS check with HttpsURLConnection

Following code can help to create SSLSocketfactory for trusted cert by reading custom JKS (If you don't want to put cert in default trust store(cacrets) or don't want to set java system property).

This piece of code will be specific to your application and will not affect other applications if running in same JVM ...

private static String trustStorePasswd = "pass123";
private static String keyfactoryAlgorithm = "SunX509";
private static String sslContextProtocol = "SSL";

SSLContext sslCtx = SSLContext.getInstance(sslContextProtocol);

String sslTrustStore = "./setup/mytrust.jks"; // trust store file

// Create TrustManager
KeyStore trustKs = KeyStore.getInstance("JKS");
trustKs.load(new FileInputStream(sslTrustStore),
trustStorePasswd.toCharArray());
trustKs.load(is,
trustStorePasswd.toCharArray());

TrustManagerFactory tmf = TrustManagerFactory
.getInstance(keyfactoryAlgorithm);

tmf.init(trustKs);

sslCtx.init(null ,tmf.getTrustManagers(), null);

SSLSocketFactory socketFactory = sslCtx.getSocketFactory();


Now next step is to set socket factory into HttpsURLconnection :
HttpsURLconnection httpsconnections;
URL url = new URL("https://mysite.com:3434");
httpsconnections = (HttpsURLConnection) url.openConnection();
httpsconnections.setSSLSocketFactory(socketFactory);

now ur java code is ready to open connection to site and to use .. :)

cheers

Tuesday, February 9, 2010

Code to Disabling Certificate Validation in an HTTPS Connection HTTPSURLConnection

By default, accessing an HTTPS URL using the URL class results in an exception if the server's certificate chain cannot be validated has not previously been installed in the truststore. If you want to disable the validation of certificates for testing purposes, you need to override the default trust manager with one that trusts all certificates.

// Create a trust manager that does not validate certificate chains
TrustManager[] trustAllCerts = new TrustManager[]{
new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(
java.security.cert.X509Certificate[] certs, String authType) {
}
public void checkServerTrusted(
java.security.cert.X509Certificate[] certs, String authType) {
}
}
};

// Install the all-trusting trust manager
try {
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
} catch (Exception e) {
}

// Now you can access an https URL without having the certificate in the truststore
try {
URL url = new URL("https://hostname/index.html");
} catch (MalformedURLException e) {
}

Monday, January 25, 2010

Discard duplicate items from Array or List using Set

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

public class Main {
public static void main(String[] argv) throws Exception {
int[] arr = new int[5];

Set set = new HashSet(Arrays.asList(arr));
}
}

Saturday, October 10, 2009

How to compress a file in the GZIP format

try {
// Create the GZIP output stream
String outFilename = "outfile.gzip";
GZIPOutputStream out = new GZIPOutputStream(new FileOutputStream(outFilename));
// Open the input file
String inFilename = "infilename";
FileInputStream in = new FileInputStream(inFilename);
// Transfer bytes from the input file to the GZIP output stream
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
// Complete the GZIP file
out.finish();
out.close();
} catch (IOException e) {
}

Difference between empty and null check of JSTL Core tag

< c:if test="${param.name != null}">< /c:if>


The above tag is to check whether parameter name is null or not. If it is not null then it prints out the sentence and it prints nothing if the value is null.


< c:if test="${param.name ne null}">< /c:if>

A test shows that parameter name contains value of ${param.name} via "ne" operator

Above codes are working similarly with the previous codes. We just want to test JSP notation “ne” for not equal function as what “!=” does.


< c:if test="${not empty(param.name)}">< /c:if>



A test shows that parameter name contains value of ${param.name} via empty operator.

Above codes are another feature of JSP notation to check a value whether it is empty or not. It is basically pretty much the same as the second and third tag do. The difference lies on the value null and empty.
 
So What is the difference between empty and null?
 
Well, empty is not necessarily be null but null always be empty. Null means that the variable is simply not existed while empty means that the variable is existed and initialized but it contains nothing. Please be careful when dealing with null values as it may cause you the famous NullPointerException.

Wednesday, September 30, 2009

The Java serialization algorithm

Read this article of Java World to understand Java serialization in better way :) -


The Java serialization algorithm revealed

Serialization is the process of saving an object's state to a sequence of bytes; deserialization is the process of rebuilding those bytes into a live object.......


http://www.javaworld.com/community/node/2915

Monday, September 7, 2009

Email Pattern match in JAVA

Simple code for Email pattern match using JAVA :

String email = "kapilgupta273@gmail.com";
Pattern pattern = Pattern.compile("([A-Za-z0-9])*([$^#%<>*'()&\"])");
if(pattern.matcher(email ))
return true;
else
return false;

Popular Posts