Java – Apache HttpClient to access the self signed certification and no host verification

Below code comes from https://memorynotfound.com/ignore-certificate-errors-apache-httpclient/

package com.memorynotfound.httpclient;

import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ssl.*;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContextBuilder;
import javax.net.ssl.*;
import java.io.IOException;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;

/**
 * This example demonstrates how to ignore certificate errors.
 * These errors include self signed certificate errors and hostname verification errors.
 */
public class HttpClientAcceptSelfSignedCertificate {

    public static void main(String... args)  {

        try (CloseableHttpClient httpclient = createAcceptSelfSignedCertificateClient()) {
            HttpGet httpget = new HttpGet("https://example.com");
            System.out.println("Executing request " + httpget.getRequestLine());
            
            httpclient.execute(httpget);
            System.out.println("----------------------------------------");
        } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException | IOException e) {
            throw new RuntimeException(e);
        }
    }

    private static CloseableHttpClient createAcceptSelfSignedCertificateClient()
            throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException {

        // use the TrustSelfSignedStrategy to allow Self Signed Certificates
        SSLContext sslContext = SSLContextBuilder
                .create()
                .loadTrustMaterial(new TrustSelfSignedStrategy())
                .build();

        // we can optionally disable hostname verification. 
        // if you don't want to further weaken the security, you don't have to include this.
        HostnameVerifier allowAllHosts = new NoopHostnameVerifier();
        
        // create an SSL Socket Factory to use the SSLContext with the trust self signed certificate strategy
        // and allow all hosts verifier.
        SSLConnectionSocketFactory connectionFactory = new SSLConnectionSocketFactory(sslContext, allowAllHosts);
        
        // finally create the HttpClient using HttpClient factory methods and assign the ssl socket factory
        return HttpClients
                .custom()
                .setSSLSocketFactory(connectionFactory)
                .build();
    }
}
Advertisements
Posted in Programming, Java | Leave a comment

Java – Aspect based measuring the method execution time of function with annotation

Annotation definition.

@Target({ElementType.METHOD,
         ElementType.CONSTRUCTOR})
@Retention(RetentionPolicy.RUNTIME)
public @interface MeasureMethodTime {
}

Aspect advice implementation.

@Aspect
public class MeasureMethodLogger {
    private static Logger LOGGER = LoggerFactory.getLogger(MeasureMethodLogger.class);

    @Around("execution(@com.acrocontext.api.utils.MeasureMethodTime * *(..)) && @annotation(measureMethodTimeAnnotation)")
    public Object logDuration(ProceedingJoinPoint joinPoint,
                              MeasureMethodTime measureMethodTimeAnnotation)
            throws Throwable {

        long start = System.currentTimeMillis();
        Object result = joinPoint.proceed();
        LOGGER.info(
                String.format("[MEASURE]: %s in %d(msec)",
                joinPoint.getSignature().getName(),
                System.currentTimeMillis() - start));
        return result;
    }
}

Example

  @MeasureMethodTime
  public int test(int value) {
  }
Posted in Java, Programming | Leave a comment

Spring – CGLIB: High performance code generation library

Spring is heavily using the CGLIB for it’s framework implementation. CGLib is high performance code generation library. It is using to extend JAVA classes and implementation at runtime.

More details can be found in the below.
https://github.com/cglib/cglib/wiki

Posted in Java, Programming | Leave a comment

Cache – False sharing

As modern CPU shared memory architecture, false sharing is the major performance bottleneck on multi-thread application.
False sharing is caused by sharing the same cache line with multiple thread. In order to avoid this problem, it is important that local thread data should be away enough to data used by another thread.
The best way to achieve this is not to spread out data used by a thread. If all data used by a thread is close enough, processor will try to load them on the same cache line which each thread can localize the memory access on their cache line.

Posted in Performance, Programming | Leave a comment

Cassandra – Evolvement of Cassandra column oriented row

The following blog explain how Cassandra has been improved the column oriented row.

https://www.datastax.com/dev/blog/cql3-for-cassandra-experts

Posted in cassandra, Programming | Leave a comment

Java – Spring to inject multiple service instances having same interface

Create service for multiple name providers

interface NameProvider {
    String name();
}

@Service
public class SomeName implement NameProvider {
    public String name() { return "SomeName"; }
}

@Service
public class AnotherName implement NameProvider {
    public String name() { return "AnotherName"; }
}

NameService class can inject multiple NameProviders with the following constructor injection.

@Service
public class NameService {
    private List<NameProvider> nameProviders;

    NameService(List<NameService> nameProviders) {
        this.nameProviders = nameProviders;
    }
}
Posted in Java, Programming | Leave a comment

Java – Importance of final fields for immutable object

Java will guarantee that all thread will see correct values of final fields that were set by the constructor, regardless of how object is published.

Posted in Java, Programming | Leave a comment