Showing posts with label Java8. Show all posts
Showing posts with label Java8. Show all posts

Wednesday, 23 August 2017

Validate JWT token and Secret Key

What is JSON Web Token?

JSON Web Token (JWT) is an open standard (RFC 7519) that defines a compact and self-contained way for securely transmitting information between parties as a JSON object. This information can be verified and trusted because it is digitally signed. JWTs can be signed using a secret (with the HMAC algorithm) or a public/private key pair using RSA.

When should you use JSON Web Tokens?

Here are some scenarios where JSON Web Tokens are useful:
  • Authentication: This is the most common scenario for using JWT. Once the user is logged in, each subsequent request will include the JWT, allowing the user to access routes, services, and resources that are permitted with that token. Single Sign On is a feature that widely uses JWT nowadays, because of its small overhead and its ability to be easily used across different domains.
  • Information Exchange: JSON Web Tokens are a good way of securely transmitting information between parties. Because JWTs can be signed—for example, using public/private key pairs—you can be sure the senders are who they say they are. Additionally, as the signature is calculated using the header and the payload, you can also verify that the content hasn't been tampered with.
Click here to learn more about JWT.

Sample Java code to validate JWT token and secret key.

Add below maven dependency to your pom.xml

Tuesday, 4 July 2017

Currency converter service

I am attaching simple program about, How to write Simple Currency Converter using Java Program. The program was written using Fixer Currency Converter Webservice. In this example, I am using Gson 2.8.0 API to convert JSON to Object in Java. you can download API from here.

CurrencyConversionResponse.java

package com.kishore.generic;

import java.util.Map;
import java.util.TreeMap;

public class CurrencyConversionResponse {

    private String base;
    private String date;

    private Map<String, String> rates = new TreeMap<String, String>();

    public Map<String, String> getRates() {
        return rates;
    }

    public void setRates(Map<String, String> rates) {
        this.rates = rates;
    }

    public String getBase() {
        return base;
    }

    public void setBase(String base) {
        this.base = base;
    }

    public String getDate() {
        return date;
    }

    public void setDate(String date) {
        this.date = date;
    }

}

CurrencyConvertor.java

package com.kishore.generic;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Scanner;

import com.google.gson.Gson;

public class CurrencyConvertor {

    // API Provider URL
    private static final String API_PROVDIER = "http://api.fixer.io/";

    public static double convert(String fromCurrencyCode, String toCurrencyCode) {

        if ((fromCurrencyCode != null && !fromCurrencyCode.isEmpty())
                && (toCurrencyCode != null && !toCurrencyCode.isEmpty())) {

            CurrencyConversionResponse response = getResponse(API_PROVDIER
                    + "/latest?base=" + fromCurrencyCode);

            if (response != null) {

                String rate = response.getRates().get(toCurrencyCode);

                double conversionRate = Double.valueOf((rate != null) ? rate: "0.0");

                return conversionRate;
            }

        }

        return 0.0;
    }

    // Method to get the response from API
    private static CurrencyConversionResponse getResponse(String strUrl) {

        CurrencyConversionResponse response = null;

        Gson gson = new Gson();
        StringBuffer sb = new StringBuffer();

        if (strUrl == null || strUrl.isEmpty()) {

            System.out.println("Application Error");
            return null;
        }

        URL url;
        try {
            url = new URL(strUrl);

            HttpURLConnection connection = (HttpURLConnection) url
                    .openConnection();

            InputStream stream = connection.getInputStream();

            int data = stream.read();

            while (data != -1) {

                sb.append((char) data);

                data = stream.read();
            }

            stream.close();

            response = gson.fromJson(sb.toString(),
                    CurrencyConversionResponse.class);

        } catch (MalformedURLException e) {

            System.out.println(e.getMessage());
            e.printStackTrace();

        } catch (IOException e) {

            System.out.println(e.getMessage());
            e.printStackTrace();
        }

        return response;
    }

    public static void main(String[] args) throws IOException {

        Scanner scanner = new Scanner(System.in);

        System.out.println("What is your currency code ?");
        String fromCurrencyCode = scanner.next();

        System.out.println("Enter the Amount :");
        double amount = scanner.nextDouble();

        System.out
                .println("Enter the Currency Code that you want to covert : ");
        String toCurrencyCode = scanner.next();

        fromCurrencyCode = fromCurrencyCode.toUpperCase();
        toCurrencyCode = toCurrencyCode.toUpperCase();

        // Currency Conversion
        double coversionRate = convert(fromCurrencyCode, toCurrencyCode);

        System.out.println("Hi, The " + amount + " " + fromCurrencyCode
                + " is equivalent to " + (coversionRate * amount) + " "
                + toCurrencyCode + " today.");

        scanner.close();
    }

}

Output

What is your currency code ?
USD
Enter the Amount :
1
Enter the Currency Code that you want to covert : 
GBP
Hi, The 1.0 USD is equivalent to 0.77341 GBP today.



Monday, 3 July 2017

Java code to format date

Sample code to format date
package com.kishore.samples;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 *
 * Java program to show how to format date in Java using SimpleDateFormat
 * Examples. Java allows to include date, time and timezone information
 * while formatting dates in Java.
 *
 */
public class DateFormatExample {

    public static void main(String args[]) {
      
        // This is how to get today's date in Java
        Date today = new Date();
      
        //If you print Date, you will get un formatted output
        System.out.println("Today is : " + today);
      
        //formatting date in Java using SimpleDateFormat
        SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("dd-MM-yyyy");
        String date = DATE_FORMAT.format(today);
        System.out.println("Today in dd-MM-yyyy format : " + date);
      
        //Another Example of formatting Date in Java using SimpleDateFormat
        DATE_FORMAT = new SimpleDateFormat("dd/MM/yy");
        date = DATE_FORMAT.format(today);
        System.out.println("Today in dd/MM/yy pattern : " + date);
      
        //formatting Date with time information
        DATE_FORMAT = new SimpleDateFormat("dd-MM-yy:HH:mm:SS");
        date = DATE_FORMAT.format(today);
        System.out.println("Today in dd-MM-yy:HH:mm:SS : " + date);
      
        //SimpleDateFormat example - Date with timezone information
        DATE_FORMAT = new SimpleDateFormat("dd-MM-yy:HH:mm:SS Z");
        date = DATE_FORMAT.format(today);
        System.out.println("Today in dd-MM-yy:HH:mm:SSZ : " + date);      
    }   
}

Output:

Today is : Mon Jul 03 23:16:17 IST 2017
Today in dd-MM-yyyy format : 03-07-2017
Today in dd/MM/yy pattern : 03/07/17
Today in dd-MM-yy:HH:mm:SS : 03-07-17:23:16:95
Today in dd-MM-yy:HH:mm:SSZ : 03-07-17:23:16:95 +0530

Format currency in Java

Sample code to format currency in java
package com.kishore.samples;

import java.text.NumberFormat;
import java.util.Locale;

/**
 * * How to format Number to different currency in Java. Following Java program
 * * will show you, how you can display double value in different currency e.g.
 * * USD, GBP and JPY. This example show price in multiple currency. 
 */
public class CurrencyFormater {
    public static void main(String args[]) {
        double price = 100.25;
        showPriceInUSD(price, getExchangeRate("USD"));
        showPriceInGBP(price, getExchangeRate("GBP"));
        showPriceInJPY(price, getExchangeRate("JPY"));
    }

    /** * Display price in US Dollar currency * * @param price * @param rate */
    public static void showPriceInUSD(double price, double rate) {
        double priceInUSD = price * rate;
        NumberFormat currencyFormat = NumberFormat
                .getCurrencyInstance(Locale.US);
        System.out.printf("Price in USD : %s %n",
                currencyFormat.format(priceInUSD));
    }

    /** * Display prince in British Pound * * @param price * @param rate */
    public static void showPriceInGBP(double price, double rate) {
        double princeInGBP = price * rate;
        NumberFormat GBP = NumberFormat.getCurrencyInstance(Locale.UK);
        System.out.printf("Price in GBP : %s %n", GBP.format(princeInGBP));
    }

    /** * Display prince in Japanese Yen * * @param price * @param rate */
    public static void showPriceInJPY(double price, double rate) {
        double princeInJPY = price * rate;
        NumberFormat currency = NumberFormat.getCurrencyInstance(Locale.JAPAN);
        System.out.printf("Price in JPY : %s %n", currency.format(princeInJPY));
    }

    /** * @return FX exchange rate for USD * @param currency */
    public static double getExchangeRate(String currency) {
        switch (currency) {
        case "USD":
            return 1;
        case "JPY":
            return 102.53;
        case "GBP":
            return 0.60;
        case "EURO":
            return 0.73;
        default:
            throw new IllegalArgumentException(String.format(
                    "No rates available for currency %s %n", currency));
        }
    }
}

Output:

Price in USD : $100.25 
Price in GBP : £60.15 
Price in JPY : ?10,279 


Display number in different number patterns with locale

Sample code to display numbers in different pattern with locale like en_US
package com.kishore.samples;

import java.util.*;
import java.text.*;
 
public class DecimalFormatDemo {
 
   static public void customFormat(String pattern, double value ) {
      DecimalFormat myFormatter = new DecimalFormat(pattern);
      String output = myFormatter.format(value);
      System.out.println(value + " ===> " + pattern + " ===> " + output);
   }
 
   static public void localizedFormat(String pattern, double value, 
                                      Locale loc ) {
      NumberFormat nf = NumberFormat.getNumberInstance(loc);
      DecimalFormat df = (DecimalFormat)nf;
      df.applyPattern(pattern);
      String output = df.format(value);
      System.out.println(pattern + " ===> " + output + " ===> " + loc.toString());
   }
 
   static public void main(String[] args) {
       System.out.println("Number formats without Locale");
      customFormat("###,###.###", 123456.789);
      customFormat("###.##", 123456.789);
      customFormat("000000.000", 123.78);
      customFormat("$###,###.###", 12345.67);
      customFormat("\u00a5###,###.###", 12345.67);
 
      Locale currentLocale = new Locale("en", "US");
 
      DecimalFormatSymbols unusualSymbols = 
         new DecimalFormatSymbols(currentLocale);
      unusualSymbols.setDecimalSeparator('|');
      unusualSymbols.setGroupingSeparator('^');
      String strange = "#,##0.###";
      DecimalFormat weirdFormatter = new DecimalFormat(strange, unusualSymbols);
      weirdFormatter.setGroupingSize(4);
      String bizarre = weirdFormatter.format(12345.678);
      System.out.println(bizarre);
 
      Locale[] locales = {
         new Locale("en", "US"),
         new Locale("de", "DE"),
         new Locale("fr", "FR")
      };
      System.out.println("Number formats with Locale");
      for (int i = 0; i < locales.length; i++) {
         localizedFormat("###,###.###", 123456.789, locales[i]);
      }
 
   }
}

Output:

Number formats without Locale
123456.789 ===> ###,###.### ===> 123,456.789
123456.789 ===> ###.## ===> 123456.79
123.78 ===> 000000.000 ===> 000123.780
12345.67 ===> $###,###.### ===> $12,345.67
12345.67 ===> ¥###,###.### ===> ¥12,345.67
1^2345|678
Number formats with Locale
###,###.### ===> 123,456.789 ===> en_US
###,###.### ===> 123.456,789 ===> de_DE
###,###.### ===> 123 456,789 ===> fr_FR

Reference:
https://docs.oracle.com/javase/tutorial/i18n/format/decimalFormat.html

Display number in different number patterns

You can use the java.text.DecimalFormat class to control the display of leading and trailing zeros, prefixes and suffixes, grouping (thousands) separators, and the decimal separator. DecimalFormat offers a great deal of flexibility in the formatting of numbers, but it can make your code more complex.
The example that follows creates a DecimalFormat object, myFormatter, by passing a pattern string to the DecimalFormat constructor. The format() method, which DecimalFormat inherits from NumberFormat, is then invoked by myFormatter—it accepts a double value as an argument and returns the formatted number in a string:
Here is a sample program that illustrates the use of DecimalFormat:
import java.text.*;

public class DecimalFormatDemo {

   static public void customFormat(String pattern, double value ) {
      DecimalFormat myFormatter = new DecimalFormat(pattern);
      String output = myFormatter.format(value);
      System.out.println(value + " ===> " + pattern + " ===> " + output);
   }

   static public void main(String[] args) {

      customFormat("###,###.###", 123456.789);
      customFormat("###.##", 123456.789);
      customFormat("000000.000", 123.78);
      customFormat("$###,###.###", 12345.67);  
   }
}

The output is:
123456.789 ===> ###,###.### ===> 123,456.789
123456.789 ===> ###.## ===> 123456.79
123.78 ===> 000000.000 ===> 000123.780
12345.67 ===> $###,###.### ===> $12,345.67

Reference:

Saturday, 10 June 2017

Remove duplicate user defined objects from an ArrayList

To remove duplicate user defined objects we need to override hashCode() and equals() methods and update the comparison logic accordingly.

I had a scenario where I had a list of objects, I need to remove duplicates from the list. I have overrided hashcode() and equals() method. When the duplicate object is encountered, the hashcode value will be same, then equals method is executed. If both objects are equal then it returns true and object will not be added to HashSet.

package com.kishore.samples;

import java.util.ArrayList;
import java.util.HashSet;

public class RemoveDuplicates {

    public static void main(String a[]) {

        ArrayList<Price> listOfBlogs = new ArrayList<>();
        listOfBlogs.add(new Price("aaa", 20));
        listOfBlogs.add(new Price("22", 40));
        listOfBlogs.add(new Price("333", 30));
        listOfBlogs.add(new Price("aaa", 200));

        HashSet<Price> set = new HashSet(listOfBlogs);
        for (Price pr : set) {
            System.out.println(pr);
        }

    }
}

class Price {

    private String item;
    private int price;

    public Price(String itm, int pr) {
        this.item = itm;
        this.price = pr;
    }

    public int hashCode() {
        System.out.println("In hashcode");
        int hashcode = 0;

        hashcode = item.hashCode();
        hashcode += item.hashCode();
        System.out.println("hash code value for " + item + " is " + hashcode);
        return hashcode;
    }

    public boolean equals(Object obj) {
        System.out.println("In equals");
        if (obj instanceof Price) {
            Price pp = (Price) obj;
            return (pp.item.equals(this.item));
        } else {
            return false;
        }
    }

    public String getItem() {
        return item;
    }

    public void setItem(String item) {
        this.item = item;
    }

    public int getPrice() {
        return price;
    }

    public void setPrice(int price) {
        this.price = price;
    }

    public String toString() {
        return "item: " + item + "  price: " + price;
    }
}

Output:

In hashcode
hash code value for aaa is 192642
In hashcode
hash code value for 22 is 3200
In hashcode
hash code value for 333 is 101286
In hashcode
hash code value for aaa is 192642
In equals
item: aaa  price: 20
item: 22  price: 40
item: 333  price: 30

Thursday, 13 April 2017

Encrypting and Decrypting String in Java

The Advanced Encryption Standard (AES), also known by its original name Rijndael (Dutch pronunciation: [ˈrɛindaːl]),[5][6] is a specification for the encryption of electronic data established by the U.S. National Institute of Standards and Technology (NIST) in 2001.[7]

Below is sample java code to encrypt and decrypt a string.


package com.kishore;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class Encrypt {

    protected final Logger LOGGER = LoggerFactory.getLogger(this.getClass());
    
    public static void main(String[] args) {
        String encryptString = "45634634";
        final String KEY = "kishore";
        Encrypt obj = new Encrypt();
        String encryptedString = obj.encrypt(encryptString, obj.encryptSecretKey(KEY));
        System.out.println("encryptedString: "+encryptedString);        
        String decyptedString = obj.decrypt(encryptedString, obj.encryptSecretKey(KEY));
        System.out.println("decyptedString: "+decyptedString);
    }
    public SecretKeySpec encryptSecretKey(final String secretKey) {
        MessageDigest sha = null;
        SecretKeySpec encryptApiSecret = null;
        try {
            byte[] key = secretKey.getBytes("UTF-8");
            sha = MessageDigest.getInstance("SHA-1");
            key = sha.digest(key);
            key = Arrays.copyOf(key, 16);
            encryptApiSecret = new SecretKeySpec(key, "AES");
        } catch (final NoSuchAlgorithmException e) {
            LOGGER.error("Exception occurred in encryptApiSecret",e);
        } catch (final UnsupportedEncodingException e) {
            LOGGER.error("Exception occurred in encryptApiSecret",e);
        }
        return encryptApiSecret;
    }
    
    public String decrypt(final String strToDecrypt, final SecretKeySpec secretKey) {
        String decryptedApiKey = "";
        try {
            final Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");
            cipher.init(Cipher.DECRYPT_MODE, secretKey);
            byte[] c = Base64.decodeBase64(strToDecrypt.getBytes("UTF-8"));
            decryptedApiKey = new String(cipher.doFinal(c));
        } catch (final Exception e) {
            LOGGER.error("Exception occurred in decrypt",e);
        }
        return decryptedApiKey;
    }

    public String encrypt(final String strToDecrypt, final SecretKeySpec secretKey) {
        String encryptedApiKey = "";
        try {
            final Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");
            cipher.init(Cipher.ENCRYPT_MODE, secretKey);
            byte[] c = cipher.doFinal(strToDecrypt.getBytes());
            encryptedApiKey = new String(Base64.encodeBase64(c));
        } catch (final Exception e) {
            LOGGER.error("Exception occurred in encrypt",e);
        }
        return encryptedApiKey;
    }

}


Tuesday, 6 September 2016

Issues while Migrating from Java6 to Java8 in AEM 6.1

Recently while working on AEM 6.1, I had to move from Java 6 to Java 8. Simply changing the Java version in POM led to some issues with OSGi services. Specifically, those services that were using @Reference annotation were not getting active and remained in “satistied” state.
Here are all the steps I followed firstly to change Java version and then fixing above mentioned issue:
1. To build an AEM project with Java8 as runtime environment, following configuration is required in pom.xml. The Compiler Plugin is added to the parent POM, it is used to compile the sources of your project.