Tuesday, 31 January 2017

Calling Https url from Java Code

Java code snipet for hitting Https url from Java code ::

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.security.cert.X509Certificate;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

public class TestHitSSL {

    public static void main(String[] args) throws Exception {
        // Need to 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(X509Certificate[] certs, String authType) {
            }
            public void checkServerTrusted(X509Certificate[] certs, String authType) {
            }
        } };
        // Installing the all-trusting trust manager
        final SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
        // Create all-trusting host name verifier
        HostnameVerifier allHostsValid = new HostnameVerifier() {
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        };

        // Installing the all-trusting host verifier
        HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);

        URL url = new URL("https://www.google.com"); // test https url
        URLConnection con = url.openConnection();  //opening the url connection to test url
     
        final Reader reader = new InputStreamReader(con.getInputStream());
        final BufferedReader br = new BufferedReader(reader);      
        String message = "";
        while ((message = br.readLine()) != null) // reading the line from InputStream
    {
            System.out.println(message );
        }      
        br.close(); //closing the BufferedReader
    }
}

Monday, 30 January 2017

Yesterday's Date using Java code

Java code snipet for Yesterday's Date :

We can use Calendar class to do this job.

                                Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, -1);
SimpleDateFormat df2 = new SimpleDateFormat("yyyy-MM-dd");
Date date = cal.getTime();
System.out.println(df2.format(date));
String dateForConsultation = df2.format(date);

Sunday, 29 January 2017

MD5 Hash Code Encription

Java Code Snipet for MD5 Encription :

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public  String md5(final String s) {
        final String MD5 = "MD5";
        try {
            // Create MD5 Hash
            MessageDigest digest = java.security.MessageDigest
                    .getInstance(MD5);
            digest.update(s.getBytes());
            byte messageDigest[] = digest.digest();

           // Create Hex String
            StringBuilder hexString = new StringBuilder();
            for (byte aMessageDigest : messageDigest) {
                String h = Integer.toHexString(0xFF & aMessageDigest);
                while (h.length() < 2)
                    h = "0" + h;
                hexString.append(h);
            }
            return hexString.toString();

       } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return "";
    }

Base64 Decode and Encode

Java Code snipet for Base64 Encode and Decode

import org.apache.commons.codec.binary.Base64;

// Encode data on your side using BASE64
byte[]   bytesEncoded = Base64.encodeBase64(str .getBytes());
System.out.println("ecncoded value is " + new String(bytesEncoded ));

// Decode data on other side, by processing encoded data
byte[] valueDecoded= Base64.decodeBase64(bytesEncoded );
System.out.println("Decoded value is " + new String(valueDecoded));


Maven Dependencies :
<!-- https://mvnrepository.com/artifact/commons-codec/commons-codec -->
<dependency>
    <groupId>commons-codec</groupId>
    <artifactId>commons-codec</artifactId>
    <version>1.9</version>
</dependency>