29 Aralık 2019 Pazar

Lang3 StopWatch Sınıfı

Giriş
Şu satırı dahil ederiz.
import org.apache.commons.lang3.time.StopWatch;
Süreyi milisaniye olarak ölçer.

createStarted metodu
Şöyle yaparız. Çıktı olarak 00:00:02:072 alırız.
StopWatch stopwatch = StopWatch.createStarted()
...
System.out.println(stopwatch);
getTime metodu
Örnek
Şöyle yaparız.
public static void main(String[] args) {
  StopWatch stopwatch = new StopWatch();
  stopwatch.start();
  stopwatch.stop();
  long timeTaken = stopwatch.getTime();
  System.out.println(timeTaken);
}
getTime metodu - TimeUnit
Örnek
Şöyle yaparız
public boolean tryLock(){
  return spinTryLock (10,TimeUnit.SECONDS);
}

private boolean spinTryLock(long timeout,TimeUnit unit) {
  boolean locked = false;
  StopWatch stopWatch = StopWatch.createStarted();
  while (stopWatch.getTime(unit) <= timeout){
    if (someCondition()){
      locked = true;
      break;
    }
  }
  return locked;
}

23 Aralık 2019 Pazartesi

HttpEntity Sınıfı

setEntity metodu
Şöyle yaparız
HttpEntity entity = new ByteArrayEntity(array);
httpPost.setEntity(entity);

HttpComponents HttpClients Sınıfı

Giriş
Şu satırı dahil ederiz.
import org.apache.http.impl.client.HttpClients;
Bu sınıf sayesinde CloseableHttpClient yaratılır.  Bu sınıf ile gelen he şey senkron çalışır. Asenkron çalışmak için bir başka kütüphane olan HttpAsyncClients kullanılır

custom metodu
Eğer createDefault() metodu yerine özelleştirilmiş bir şey istiyorsak custom() metodu kullanılır. HttpClientBuilder nesnesi döndürür. Böylece özelleştirme yapılabilir.

createDefault metodu
Şöyle yaparız
CloseableHttpClient client = HttpClients.createDefault();
setConnectionManager metodu
Örnek
Şöyle yaparız
public static String trustedAllPost(final String url) {
  String result = null;
  try {
    // 1. Create SSLContextBuilder to trust in every host
    SSLContextBuilder builder = new SSLContextBuilder();
    builder.loadTrustMaterial(null, (chain, authType) -> true);
    // 2. Create a SSLConnectionSocketFactory to not verify any hostname
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build(),
      new NoopHostnameVerifier());
    HttpClientConnectionManager cm = PoolingHttpClientConnectionManagerBuilder.create()
      .setSSLSocketFactory(sslsf).build();
    // 3. Associate both configurations through HttpClientConnectionManager to the HTTP 
    // client
    try (CloseableHttpClient httpclient = HttpClients.custom().setConnectionManager(cm)
      .build()) {
      HttpPost method = new HttpPost(url);
      try (CloseableHttpResponse response = httpclient.execute(method)) {
        result = EntityUtils.toString(response.getEntity());
      }
    }
  } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException |
    IOException | ParseException e) {
    log.error(e.getMessage(), e);
  }
  return result;
}
setDefaultCredentialsProvider metodu
Örnek - username and password authentication
Şöyle yaparız
public static String getWithBasicAuth(String url, String user, String pass)
    throws URISyntaxException, IOException, ParseException {
  String result = null;
  URI uri = new URI(url);
  // 1. Create a Basic Credentials provider to authenticate the call
  BasicCredentialsProvider credsProvider = new BasicCredentialsProvider();
  AuthScope authScope = new AuthScope(uri.getHost(), uri.getPort());
  credsProvider.setCredentials(authScope, new UsernamePasswordCredentials(user,
    pass.toCharArray()));
  // 2. Add the credentials to the HHTP Client to use it in the call
  try (CloseableHttpClient httpclient = HttpClients.custom()
    .setDefaultCredentialsProvider(credsProvider).build()) {
    HttpGet httpget = new HttpGet(url);
    try (CloseableHttpResponse response = httpclient.execute(httpget)) {
      result = EntityUtils.toString(response.getEntity());
    }
  } catch (IOException | ParseException e) {
    log.error(e.getMessage(), e);
  }
  return result;
} 

setDefaultCookieStore metodu
Örnek
Şöyle yaparız
private static CookieStore cookieStore = new BasicCookieStore();
private static CloseableHttpClient httpclient = HttpClients.custom()
  .setDefaultCookieStore(cookieStore).build();
  
public static String postWithCookieStore(String url, String jsonBody) {
  // 1. Create HTTP Method
  HttpPost httpPost = new HttpPost(url);
  // 2. Set payload and content-type
  if (jsonBody != null) {
    httpPost.setEntity(new StringEntity(jsonBody, ContentType.APPLICATION_JSON));
  }
  String result = null;
  // 3. Create HTTP client
  try {
    // 4. Execute the method through the HTTP client
    try (CloseableHttpResponse response = httpclient.execute(httpPost)) {
      // 5. Read Response
      result = EntityUtils.toString(response.getEntity());
      log.info("Status Code: " + response.getCode() + " " + response.getReasonPhrase());
    }
  } catch (IOException | ParseException e) {
    log.error(e.getMessage(), e);
  }
  return result;
}

19 Aralık 2019 Perşembe

SevenZFile Sınıfı

Giriş
Şu satırı dahil ederiz.
import org.apache.commons.compress.archivers.sevenz.SevenZArchiveEntry;
import org.apache.commons.compress.archivers.sevenz.SevenZFile;
constructor - File
Şöyle yaparız.
public static void decompressSevenz(String in, File destination) throws IOException {
  //@SuppressWarnings("resource")
  SevenZFile sevenZFile = new SevenZFile(new File(in));
  SevenZArchiveEntry entry;
  while ((entry = sevenZFile.getNextEntry()) != null){
    if (entry.isDirectory()){
      continue;
    }
    File curfile = new File(destination, entry.getName());
    File parent = curfile.getParentFile();
    if (!parent.exists()) {
      parent.mkdirs();
    }
    FileOutputStream out = new FileOutputStream(curfile);
    byte[] content = new byte[(int) entry.getSize()];
    sevenZFile.read(content, 0, content.length);
    out.write(content);
    out.close();
    }
  sevenZFile.close();
}