July 26, 2018

Prime number in python

A python program to find prime number

Program


num = int(input("Enter a number : "))
print("Prime numbers from {} to {} are ".format(1, num))
for i in range(2, num):
    for j in range(2, i):
        if i % j == 0:
            break
    else:
        print(i, end=" ")

Output


July 25, 2018

Okhttp 3 SSL handshake Exception solved

Okhttp 3 SSL handshake issue solved


When negotiating a connection to an HTTPS server, OkHttp needs to know which TLS versions and cipher suites to offer

package com.belazy.okhttp;

import java.io.IOException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;

import javax.net.ssl.SSLContext;

import okhttp3.CipherSuite;
import okhttp3.ConnectionSpec;
import okhttp3.OkHttpClient;
import okhttp3.OkHttpClient.Builder;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.TlsVersion;

/**
 * Alan john
 *
 */
public class OkhttpSSLExample {
public static void main(String[] args) {
try {
OkHttpClient client = new OkHttpClient();
client = OkhttpSSLExample.enableTls12OVersion(client).build();
RequestBody body = RequestBody.create(null, new byte[] {});
Request request = new Request.Builder()
.url("https://freesourcecode.okhttp.com/posts/sample")
.post(body).build();
Response response = client.newCall(request).execute();
System.out.println(response.body().string());
} catch (IOException e) {
e.printStackTrace();
}
}
public static OkHttpClient.Builder enableTls12OVersion(OkHttpClient okHttpClient) {
OkHttpClient.Builder client = okHttpClient.newBuilder();
try {
client.connectTimeout(120, TimeUnit.SECONDS).writeTimeout(120,
TimeUnit.SECONDS).readTimeout(130, TimeUnit.SECONDS).build();
SSLContext sc = SSLContext.getInstance("TLSv1.2");
sc.init(null, null, null);
client.sslSocketFactory(new Tls12SocketFactory(sc.getSocketFactory()));

List<CipherSuite> customCipherSuites = Arrays.asList(CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256,
CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
CipherSuite.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
CipherSuite.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384);

ConnectionSpec connectionSpec = new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS)
.tlsVersions(TlsVersion.TLS_1_2).cipherSuites(customCipherSuites.toArray(new CipherSuite[0]))
.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;
}
}


Use this code instead

ConnectionSpec connectionSpec = new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS)
     .tlsVersions(TlsVersion.TLS_1_2).cipherSuites(customCipherSuites.toArray(new CipherSuite[0]))
     .allEnabledTlsVersions().supportsTlsExtensions(false).allEnabledCipherSuites().build();

Okhttp works on java 1.7 or above.
API is designed in builder pattern.


OkHttp Interceptors

SLF4J with Logback to create a static singleton HttpLoggingInterceptor

private static final Logger log = LoggerFactory.getLogger(HttpClient.class);
log.debug("interceptor");
OkHttpClient interceptorClient = new OkHttpClient.Builder()
    .addInterceptor(HttpClient.getLoggingInterceptor())
    .build();


content type x-www-form-urlencoded

public static final MediaType FORM = MediaType.parse("multipart/form-data");

RequestBody formBody = new FormBody.Builder().add("likes", "Zombie movies").build();
Request request = new Request.Builder().url("https://datascientist/chippu/chunkz.php").post(formBody).build();
Response response = client.newCall(request).execute();



To enable cache

int cacheSize = 10 * 512 * 512; // 5MB
OkHttpClient.Builder builder = new OkHttpClient.Builder()
        .cache(new Cache(context.getCacheDir(), cacheSize)



July 20, 2018

Custom annotation Tax VAT GST calculation

Java Program for Custom annotation VAT calculation



This is a sample java program for custom annotation , showing vat calculation.

MainClass



public class Main {
public static void main(String[] args) throws SecurityException, NoSuchFieldException, NoSuchMethodException {
Insurance axa = new Insurance();
axa.setMaketPrice(200);
PriceModification priceModification = new PriceModification();
axa = (Insurance) priceModification.calculateTax(axa);
System.out.println(" supplier price : "+axa.getMaketPrice());
}
}


Price Modification class - Using reflection , based on the annotated value the tax and gst is calculated here



/**
 *
 */
package com.belazy.tax;

import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @author gosling
 *
 */
public class PriceModification {
public Object calculateTax(Insurance axa) {
try {
Class refClass = axa.getClass();
Annotation taxAnno;
Method[] methods = refClass.getMethods();
for (Method thisMethod : methods) {
String methodName = thisMethod.getName();
if (thisMethod.getAnnotations().length > 0
&& methodName.startsWith("get")) {
for (Annotation annotation : thisMethod.getAnnotations()) {
if (annotation instanceof Tax) {
taxAnno = thisMethod.getAnnotation(Tax.class);
Tax tax = (Tax) taxAnno;
System.out.println(" *** "
+ thisMethod.invoke(axa, new Object[] {}));
double price = (Double) thisMethod.invoke(axa,
new Object[] {});
double supplierPrice = 0;
String setMethodName = null;
switch (tax.mode()) {
case PERCENTAGE:
double taxPrice = price * tax.amount() / 100;
supplierPrice = price + taxPrice;
setMethodName = methodName
.replace("get", "set");
Method ss1Method = refClass.getMethod(
setMethodName, double.class);
ss1Method.invoke(axa,
new Object[] { supplierPrice });
break;
case AMOUNT:
supplierPrice = price + tax.amount();
setMethodName = methodName
.replace("get", "set");
Method ss1Method1 = refClass.getMethod(
setMethodName, double.class);
ss1Method1.invoke(axa,
new Object[] { supplierPrice });
break;
default:
break;
}
}
}
}
}
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return axa;
}

}


Insurance.java - A Model POJO class



/**
 *
 */
package com.belazy.tax;

/**
 * @author asif rajguru
 *
 */
public class Insurance {
private String name;
private double supplierPrice;
private double maketPrice;
private double basePrice;
private double profit;
private double commision;

/**
* @return the name
*/
public String getName() {
return name;
}

/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}

/**
* @return the supplierPrice
*/
public double getSupplierPrice() {
return supplierPrice;
}

/**
* @param supplierPrice the supplierPrice to set
*/

public void setSupplierPrice(double supplierPrice) {
this.supplierPrice = supplierPrice;
}

/**
* @return the maketPrice
*/
@Tax(name="VAT",amount =5, mode=TaxMode.PERCENTAGE, type=TaxTypes.INCLUSIVE)
public double getMaketPrice() {
return maketPrice;
}

/**
* @param maketPrice the maketPrice to set
*/
public void setMaketPrice(double maketPrice) {
this.maketPrice = maketPrice;
}

/**
* @return the basePrice
*/
@Tax(name="VAT",amount =5, mode=TaxMode.PERCENTAGE, type=TaxTypes.INCLUSIVE)
public double getBasePrice() {
return basePrice;
}

/**
* @param basePrice the basePrice to set
*/
public void setBasePrice(double basePrice) {
this.basePrice = basePrice;
}

/**
* @return the profit
*/
@Tax(name="VAT",amount =100, mode=TaxMode.AMOUNT, type=TaxTypes.EXCLUSIVE)
public double getProfit() {
return profit;
}

/**
* @param profit the profit to set
*/
public void setProfit(double profit) {
this.profit = profit;
}

/**
* @return the commision
*/
@Tax(name="VAT",amount =1, mode=TaxMode.PERCENTAGE, type=TaxTypes.EXCLUSIVE)
public double getCommision() {
return commision;
}

/**
* @param commision the commision to set
*/
public void setCommision(double commision) {
this.commision = commision;
}

}

TaxType Enum 


/**
 * 
 */
package com.belazy.tax;

/**
 * @author jovil
 *
 */
public enum TaxTypes {
INCLUSIVE,EXCLUSIVE;

}


TaxMode Enum


/**
 * 
 */
package com.belazy.tax;

/**
 * @author jobit
 *
 */
public enum TaxMode {

AMOUNT,PERCENTAGE;
}

Tax annotation class - Custom annotation class


/**
 * 
 */
package com.belazy.tax;

import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * @author alan jhon
 * 
 */
@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.TYPE, ElementType.FIELD, ElementType.METHOD })
public @interface Tax {
public String name();
public double amount();
public TaxMode mode() default TaxMode.PERCENTAGE;
public TaxTypes type() default TaxTypes.INCLUSIVE;
}


Output


input market price is 200
market price is : 210






July 10, 2018

My first custom annotation in java


package com.belazy.annotations;

import java.lang.reflect.Method;

public class Test {

public static void main(String[] args) {
Test t = new Test();
t.calcuate();
try {
Method method = new Test().getClass().getMethod("calcuate");
tax annotation = method.getAnnotation(tax.class);
System.out.println(annotation.type());
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

@tax(type="vat", value="5",mode ="percentage")
public void calcuate() {
// TODO Auto-generated method stub
System.out.println("calculate");

}

}


package com.belazy.annotations;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

@Retention(RetentionPolicy.RUNTIME)
public @interface tax {
   public String type ();
   public String value ();
   public String mode();
   }



://javabelazy.blogspot.in/

July 09, 2018

@Gzip compression annotation in java

package com.belazy.gzip;

import java.io.IOException;

public class Main {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String data = "hello world ";
try {
byte[] s = GzipAlgo.compress(data);
System.out.println(s);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

SamplePojo p =new SamplePojo();
GzipCompressor compressor = new GzipCompressor();
p=compressor.getCompressor(p);

}

}


/**
 *
 */
package com.belazy.gzip;

import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * @author belazy
 *
 */
@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.TYPE, ElementType.FIELD, ElementType.METHOD })
public @interface Gzip {
public String type();
}


package com.belazy.gzip;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

public class GzipAlgo {

public static byte[] compress(String data) throws IOException {
ByteArrayOutputStream bos = new ByteArrayOutputStream(data.length());
GZIPOutputStream gzip = new GZIPOutputStream(bos);
gzip.write(data.getBytes());
gzip.close();
byte[] compressed = bos.toByteArray();
bos.close();
return compressed;
}
public static String decompress(byte[] compressed) throws IOException {
ByteArrayInputStream bis = new ByteArrayInputStream(compressed);
GZIPInputStream gis = new GZIPInputStream(bis);
BufferedReader br = new BufferedReader(new InputStreamReader(gis, "UTF-8"));
StringBuilder sb = new StringBuilder();
String line;
while((line = br.readLine()) != null) {
sb.append(line);
}
br.close();
gis.close();
bis.close();
return sb.toString();
}
}


/**
 * 
 */
package com.belazy.gzip;

import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @author consumerfed itsection
 * phone : 8281808029
 * 
 */
public class GzipCompressor {

public SamplePojo getCompressor(SamplePojo axa) {
// TODO Auto-generated method stub
Class refClass = axa.getClass();
Annotation taxAnno;
Method[] methods = refClass.getMethods();

for (Method thisMethod : methods) {
String methodName = thisMethod.getName();
if (thisMethod.getAnnotations().length > 0) {
for (Annotation annotation : thisMethod.getAnnotations()) {
if (annotation instanceof Gzip) {
taxAnno = thisMethod.getAnnotation(Gzip.class);
Gzip zip = (Gzip) taxAnno;
try {
System.out.println(" *** "
+ thisMethod.invoke(axa, new String()));
String data  = (String)thisMethod.invoke(axa, new String());
byte[] b = GzipAlgo.compress(data);
System.out.println(b);
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}
}

}
}
return axa;
}

}
/**
 * 
 */
package com.belazy.gzip;

/**
 * @author consumerfed itsection
 * Phone : 0091 8281808029
 *
 */
public class SamplePojo {
private String data;

/**
* @return the data
*/
@Gzip(type="compression")
public String getData() {
return data;
}

/**
* @param data the data to set
*/
public void setData(String data) {
this.data = data;
}

}



July 02, 2018

java.lang.NumberFormatException: For input string

Exception in thread "main" java.lang.NumberFormatException: For input string: "100.0"

String s = "100.0";
Integer i = Integer.parseInt(s);
System.out.println(i);

Exception in thread "main" java.lang.NumberFormatException: For input string: "100.0"

Solution

String s = "100.0";
Double d = Double.parseDouble(s);
System.out.println(d.intValue());

Facebook comments