June 23, 2018

Java RegExp to parse currency and amount

package com.belazy.rest;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegexSample {

 static String testStr = "PER 20 COUPON CHARGE GBP 30.00.";

 public static void main(String[] args) {
  // PER COUPON CHARGE GBP 30.00.
  String str = "(^|\\s+|[^a-zA-Z0-9]+)";
  String str2 = "([^a-zA-Z0-9]+|\\s+|$)";
  Pattern p = Pattern.compile(str + "([a-zA-Z]{3})" + str2);
  Matcher m = p.matcher(testStr);
  List<String> allMatches = new ArrayList<String>();

  Pattern p1 = Pattern.compile("[a-zA-Z]{3}");
  while (m.find()) {
   // allMatches.add(m.group());
   Matcher m1 = p1.matcher(m.group());
   while (m1.find()) {
    allMatches.add(m1.group());
   }
  }
  System.out.println(allMatches);

  // PER COUPON CHARGE GBP 30.00.
  Pattern p3 = Pattern.compile("(\\d+(?:[.]\\d+)?)");
  Matcher m3 = p3.matcher(testStr);
  List<String> allMatches3 = new ArrayList<String>();

  // Pattern p4 = Pattern.compile("\\d?");
  while (m3.find()) {
   allMatches3.add(m3.group());
   // Matcher m4 = p4.matcher(m3.group());
   // while (m4.find())
   // allMatches.add(m4.group());
  }
  System.out.println(allMatches3);
 }

 private static boolean getcurrency(String currency) {
  List<String> currencyList = new ArrayList<String>();
  currencyList.add("AED");
  currencyList.add("USD");
  currencyList.add("INR");
  currencyList.add("GBP");
  currencyList.add("EUR");
  currencyList.add("MUR");

  // List<String> currencies =

  if (currencyList.contains(currency))
   return true;
  return false;
 }

}

// Credit to Tech Arch  #bestie

May 14, 2018

okhttp 3 ssl handshake exception

Dealing with ssl handshake exception in okhttp


javax.net.ssl.SSLHandshakeException: Handshake failed
       at com.android.org.conscrypt.OpenSSLSocketImpl.startHandshake(OpenSSLSocketImpl.java:374)


Solution


SampleTransferLayerSecurity

/**
 *
 */
package com.belazy.okhttp;

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

import javax.net.ssl.SSLContext;

import okhttp3.ConnectionSpec;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.TlsVersion;

/**
 * @author secure socket layer
 *
 */
public class SampleTransferLayerSecurity {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub

OkHttpClient client = new OkHttpClient();
client = SampleTransferLayerSecurity.enableTls12OVersion(client).build();
Response response = client.newCall("httpUrl").execute();

}

public static OkHttpClient.Builder enableTls12OVersion(OkHttpClient okHttpClient) {
OkHttpClient.Builder client = okHttpClient.newBuilder();
try {
SSLContext sc = SSLContext.getInstance("TLSv1.2");
sc.init(null, null, null);
client.sslSocketFactory(new Tls12SocketFactory(sc.getSocketFactory()));
ConnectionSpec connectionSpec = new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS)
.tlsVersions(TlsVersion.TLS_1_2).build();
List<ConnectionSpec> specs = new ArrayList<>();
specs.add(connectionSpec);
specs.add(ConnectionSpec.COMPATIBLE_TLS);
specs.add(ConnectionSpec.CLEARTEXT);
client.connectionSpecs(specs);
} catch (Exception exc) {
exc.printStackTrace();
}
return client;
}

}


Tls12SocketFactory.java

package com.belazy.okhttp;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;

import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;

/**
 * Enables TLS v1.2 when creating SSLSockets.
 * <p/>
 * For some reason, android supports TLS v1.2 from API 16, but enables it by
 * default only from API 20.
 * @link https://developer.android.com/reference/javax/net/ssl/SSLSocket.html
 * @see SSLSocketFactory
 */
public class Tls12SocketFactory extends SSLSocketFactory {
    private static final String[] TLS_V12_ONLY = {"TLSv1.2"};

    final SSLSocketFactory delegate;

    public Tls12SocketFactory(SSLSocketFactory base) {
        this.delegate = base;
    }

    @Override
    public String[] getDefaultCipherSuites() {
        return delegate.getDefaultCipherSuites();
    }

    @Override
    public String[] getSupportedCipherSuites() {
        return delegate.getSupportedCipherSuites();
    }

    @Override
    public Socket createSocket(Socket s, String host, int port, boolean autoClose) throws IOException {
        return patch(delegate.createSocket(s, host, port, autoClose));
    }

    @Override
    public Socket createSocket(String host, int port) throws IOException, UnknownHostException {
        return patch(delegate.createSocket(host, port));
    }

    @Override
    public Socket createSocket(String host, int port, InetAddress localHost, int localPort) throws IOException, UnknownHostException {
        return patch(delegate.createSocket(host, port, localHost, localPort));
    }

    @Override
    public Socket createSocket(InetAddress host, int port) throws IOException {
        return patch(delegate.createSocket(host, port));
    }

    @Override
    public Socket createSocket(InetAddress address, int port, InetAddress localAddress, int localPort) throws IOException {
        return patch(delegate.createSocket(address, port, localAddress, localPort));
    }

    private Socket patch(Socket s) {
        if (s instanceof SSLSocket) {
            ((SSLSocket) s).setEnabledProtocols(TLS_V12_ONLY);
        }
        return s;
    }
}


http://javabelazy.blogspot.in/

March 11, 2018

What is ANTLR

http://javabelazy.blogspot.in/

January 30, 2018

Simple example for break and continue in java

Simple example for break and continue in java




/**
 *
 */
package com.belazy.generics;

/**
 * @author belazy
 *
 * How break and continue works in java
 *
 */
public class ControlStructures {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub

int [] numbers = {1,2,3,4,5,6,7,8,9};

System.out.println("\n--- break ------------ ");

for(int number :numbers){

if(number ==5)
break;

System.out.print(number +" ");
}

System.out.println("\n--- continue ------------ ");

for(int number :numbers){

if(number ==5)
continue;

System.out.print(number +" ");
}


}

}

Output




--- break ------------
1 2 3 4
--- continue ------------
1 2 3 4 6 7 8 9




January 23, 2018

To remove a value from arraylist without iterating

/**
 * To remove a primitive data type for an Arraylist
 * without out iterating all the elements
 */
package com.belazy.generics;

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

/**
 * @author belazy
 *
 */
public class ArrayListRemoveSample {

/**
* @param args
*/
public static void main(String[] args) {

List<Integer> numberList = new ArrayList<Integer>();
numberList.add(1);
numberList.add(11);
numberList.add(2018);
numberList.add(911);
numberList.add(25);

System.out.println("--- before ---");
for(Integer thisNumber : numberList){
System.out.print(" "+thisNumber+" ");
}


numberList.remove(new Integer(911));

System.out.println("\n--- After ---");
for(Integer thisNumber : numberList){
System.out.print(" "+thisNumber+" ");
}
}

}

January 16, 2018

algorithm to split overlapping and merging consecutive dates in java

split overlapping and merging consecutive dates


/**
 * Conditions.java
 * Jan 14, 2018
 */
package com.belazy.algorithms;

/**
 * @author belazy
 *
 */
public class Conditions {

private long startDate = 0;
private long endDate = 0;
private double amount = 0;

/**
*
*/
public Conditions(long startDate, long endDate, double amount) {
// TODO Auto-generated constructor stub
this.startDate = startDate;
this.endDate = endDate;
this.amount = amount;
}

public long getStartDate() {
return startDate;
}
public void setStartDate(long startDate) {
this.startDate = startDate;
}
public long getEndDate() {
return endDate;
}
public void setEndDate(long endDate) {
this.endDate = endDate;
}
public double getAmount() {
return amount;
}
public void setAmount(double amount) {
this.amount = amount;
}


}


DateSplit.java


/**
 * DateSplit.java
 * Jan 16, 2018
 */
package com.belazy.algorithms;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

/**
 * @author belazy
 *
 */
public class DateSplit {

/**
* TODO Jan 16, 2018
* @param args
*            void
*
*/
public static void main(String[] args) {
// TODO Auto-generated method stub

List<Conditions> cancelConditions = new ArrayList<Conditions>();
cancelConditions.add(new Conditions(1, 8, 100));
cancelConditions.add(new Conditions(1, 8, 120));
cancelConditions.add(new Conditions(9, 12, 110));
cancelConditions.add(new Conditions(13, 20, 120));
cancelConditions.add(new Conditions(21, 30, 130));
cancelConditions.add(new Conditions(9, 18, 130));
cancelConditions.add(new Conditions(19, 30, 140));
cancelConditions.add(new Conditions(7, 18, 130));

Map<Long, Double> treeMap = new TreeMap<Long, Double>();
for(Conditions c :cancelConditions){
if(treeMap.containsKey(c.getEndDate())){
treeMap.put(c.getEndDate(), c.getAmount()+treeMap.get(c.getEndDate()));
}else{
treeMap.put(c.getEndDate(), c.getAmount());
}
}

System.out.println(" cancelCondition before : " + cancelConditions.size());

DateSplit d = new DateSplit();
d.splitDate(cancelConditions, treeMap);

}

/**
* TODO Jan 16, 2018
* @param cancelConditions
*            void
* @param treeMap2
*
*/
private void splitDate(List<Conditions> cancelConditions, Map<Long, Double> treeMap) {

for (long endDate : treeMap.keySet()) {
for (Conditions cond2 : cancelConditions) {
if (endDate > cond2.getStartDate() && endDate < cond2.getEndDate()) {
if (treeMap.containsKey(endDate)) {
double mapAmt = treeMap.get(endDate);
treeMap.put(endDate, cond2.getAmount() + mapAmt);
} else {
treeMap.put(endDate, cond2.getAmount());
}
}
}
}

System.out.println(" map : " + treeMap);

long startDate = 0;
long nextDate = 0;
for (Map.Entry<Long, Double> entry : treeMap.entrySet()) {
Long key = entry.getKey();
Double value = entry.getValue();
startDate = nextDate + 1;
nextDate = key;
System.out.println("startDate : " + startDate + " endDate : " + nextDate + " amount -->" + value);

}

}

}


Output





Facebook comments