All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.undefinedlabs.scope.network.HttpClientUtils Maven / Gradle / Ivy

package com.undefinedlabs.scope.network;

import okhttp3.RequestBody;
import okhttp3.Response;
import com.undefinedlabs.scope.logger.ScopeLogger;
import com.undefinedlabs.scope.logger.ScopeLoggerResolver;
import com.undefinedlabs.scope.utils.StringUtils;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;

public enum HttpClientUtils {
  INSTANCE;

  private static final ScopeLogger LOGGER = ScopeLoggerResolver.INSTANCE.get();

  void logRequestExecutionDuration(
      final String idReq,
      final String url,
      final long startReqTimestamp,
      final RequestBody body,
      final Response response) {
    final long endReqTimestamp = System.currentTimeMillis();
    final String durationReq =
        (endReqTimestamp > 0) && (startReqTimestamp > 0)
            ? String.valueOf(endReqTimestamp - startReqTimestamp)
            : "";
    final String responseBody =
        response != null && response.code() >= 400 ? extractBody(response) : "";
    final long requestContentLength = extractContentLength(body);

    final StringBuilder sb = new StringBuilder();
    if (response != null) {
      sb.append("[HTTP ").append(response.code()).append("] ");
      sb.append(StringUtils.isNotEmpty(response.message()) ? response.message() : "");
      sb.append(": ").append(responseBody);
    } else {
      sb.append("response null");
    }

    final String msg =
        "[idReq:"
            + idReq
            + "] ScopeAgent --> Backend ("
            + url
            + ") ["
            + durationReq
            + " ms] ["
            + requestContentLength
            + " bytes] "
            + sb.toString();
    if (response == null || response.code() >= 400) {
      LOGGER.error(msg);
    } else {
      LOGGER.trace(msg);
    }
  }

  long extractContentLength(final RequestBody body) {
    if (body == null) {
      return 0L;
    }

    try {
      final long length = body.contentLength();
      return length >= 0 ? length : 0;
    } catch (final IOException e) {
      return 0;
    }
  }

  String extractBody(final Response response) {
    if (response == null || response.body() == null) {
      return null;
    }

    try {
      return response.body().string();
    } catch (final IOException e) {
      return null;
    }
  }

  URL createUrl(final String baseUrl, final String path) {
    try {
      return new URL(new URL(baseUrl), path);
    } catch (final MalformedURLException e) {
      throw new RuntimeException(e);
    }
  }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy