retrofit.converter.JacksonConverter Java Examples

The following examples show how to use retrofit.converter.JacksonConverter. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: GithubConfig.java    From echo with Apache License 2.0 6 votes vote down vote up
@Bean
public GithubService githubService(
    Endpoint githubEndpoint, Client retrofitClient, RestAdapter.LogLevel retrofitLogLevel) {
  log.info("Github service loaded");

  GithubService githubClient =
      new RestAdapter.Builder()
          .setEndpoint(githubEndpoint)
          .setConverter(new JacksonConverter())
          .setClient(retrofitClient)
          .setLogLevel(RestAdapter.LogLevel.FULL)
          .setLog(new Slf4jRetrofitLogger(GithubService.class))
          .build()
          .create(GithubService.class);

  return githubClient;
}
 
Example #2
Source File: GitHubConfig.java    From fiat with Apache License 2.0 6 votes vote down vote up
@Bean
public GitHubClient gitHubClient(OkHttpClientProvider clientProvider) {
  BasicAuthRequestInterceptor interceptor =
      new BasicAuthRequestInterceptor().setAccessToken(gitHubProperties.getAccessToken());

  return new RestAdapter.Builder()
      .setEndpoint(Endpoints.newFixedEndpoint(gitHubProperties.getBaseUrl()))
      .setRequestInterceptor(interceptor)
      .setClient(
          new Ok3Client(
              clientProvider.getClient(
                  new DefaultServiceEndpoint("github", gitHubProperties.getBaseUrl()))))
      .setConverter(new JacksonConverter())
      .setLogLevel(retrofitLogLevel)
      .setLog(new Slf4jRetrofitLogger(GitHubClient.class))
      .build()
      .create(GitHubClient.class);
}
 
Example #3
Source File: FiatAuthenticationConfig.java    From fiat with Apache License 2.0 6 votes vote down vote up
@Bean
@ConditionalOnMissingBean(FiatService.class) // Allows for override
public FiatService fiatService(
    FiatClientConfigurationProperties fiatConfigurationProperties,
    SpinnakerRequestInterceptor interceptor,
    OkHttpClientProvider okHttpClientProvider) {
  // New role providers break deserialization if this is not enabled.
  val objectMapper = new ObjectMapper();
  objectMapper.enable(DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_AS_NULL);
  objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);

  OkHttpClient okHttpClient =
      okHttpClientProvider.getClient(
          new DefaultServiceEndpoint("fiat", fiatConfigurationProperties.getBaseUrl()));

  return new RestAdapter.Builder()
      .setEndpoint(Endpoints.newFixedEndpoint(fiatConfigurationProperties.getBaseUrl()))
      .setRequestInterceptor(interceptor)
      .setClient(new Ok3Client(okHttpClient))
      .setConverter(new JacksonConverter(objectMapper))
      .setLogLevel(retrofitLogLevel)
      .setLog(new Slf4jRetrofitLogger(FiatService.class))
      .build()
      .create(FiatService.class);
}
 
Example #4
Source File: IgorConfig.java    From echo with Apache License 2.0 6 votes vote down vote up
@Bean
public IgorService igorService(
    Endpoint igorEndpoint,
    OkHttpClientProvider clientProvider,
    LogLevel retrofitLogLevel,
    SpinnakerRequestInterceptor spinnakerRequestInterceptor) {
  log.info("igor service loaded");
  return new Builder()
      .setEndpoint(igorEndpoint)
      .setConverter(new JacksonConverter())
      .setClient(
          new Ok3Client(
              clientProvider.getClient(
                  new DefaultServiceEndpoint("igor", igorEndpoint.getUrl()))))
      .setRequestInterceptor(spinnakerRequestInterceptor)
      .setLogLevel(retrofitLogLevel)
      .setLog(new Slf4jRetrofitLogger(IgorService.class))
      .build()
      .create(IgorService.class);
}
 
Example #5
Source File: BackendUpdater.java    From kayenta with Apache License 2.0 6 votes vote down vote up
boolean run(
    RetrofitClientFactory retrofitClientFactory,
    ObjectMapper objectMapper,
    OkHttpClient okHttpClient) {
  RemoteService remoteService = new RemoteService();
  remoteService.setBaseUrl(uri);
  BackendsRemoteService backendsRemoteService =
      retrofitClientFactory.createClient(
          BackendsRemoteService.class,
          new JacksonConverter(objectMapper),
          remoteService,
          okHttpClient);
  try {
    List<Backend> backends = AuthenticatedRequest.allowAnonymous(backendsRemoteService::fetch);
    backendDatabase.update(backends);
  } catch (RetrofitError e) {
    log.warn("While fetching atlas backends from " + uri, e);
    return succeededAtLeastOnce;
  }
  succeededAtLeastOnce = true;
  return true;
}
 
Example #6
Source File: AtlasStorageUpdater.java    From kayenta with Apache License 2.0 6 votes vote down vote up
boolean run(
    RetrofitClientFactory retrofitClientFactory,
    ObjectMapper objectMapper,
    OkHttpClient okHttpClient) {
  RemoteService remoteService = new RemoteService();
  remoteService.setBaseUrl(uri);
  AtlasStorageRemoteService atlasStorageRemoteService =
      retrofitClientFactory.createClient(
          AtlasStorageRemoteService.class,
          new JacksonConverter(objectMapper),
          remoteService,
          okHttpClient);
  try {
    Map<String, Map<String, AtlasStorage>> atlasStorageMap =
        AuthenticatedRequest.allowAnonymous(atlasStorageRemoteService::fetch);
    atlasStorageDatabase.update(atlasStorageMap);
  } catch (RetrofitError e) {
    log.warn("While fetching atlas backends from " + uri, e);
    return succeededAtLeastOnce;
  }
  succeededAtLeastOnce = true;
  return true;
}
 
Example #7
Source File: RemoteJudge.java    From kayenta with Apache License 2.0 6 votes vote down vote up
@Override
public CanaryJudgeResult judge(
    CanaryConfig canaryConfig,
    CanaryClassifierThresholdsConfig scoreThresholds,
    List<MetricSetPair> metricSetPairList) {

  OkHttpClient okHttpClient = new OkHttpClient();
  okHttpClient.setConnectTimeout(30, TimeUnit.SECONDS);
  okHttpClient.setReadTimeout(90, TimeUnit.SECONDS);

  RemoteJudgeService remoteJudge =
      retrofitClientFactory.createClient(
          RemoteJudgeService.class,
          new JacksonConverter(kayentaObjectMapper),
          endpoint,
          okHttpClient);

  RemoteJudgeRequest judgeRequest =
      RemoteJudgeRequest.builder()
          .canaryConfig(canaryConfig)
          .metricSetPairList(metricSetPairList)
          .scoreThresholds(scoreThresholds)
          .build();

  return remoteJudge.judge(judgeRequest);
}
 
Example #8
Source File: DryRunConfig.java    From echo with Apache License 2.0 6 votes vote down vote up
@Bean
DryRunNotificationAgent dryRunNotificationAgent(
    Front50Service front50,
    OkHttpClientProvider clientProvider,
    RestAdapter.LogLevel retrofitLogLevel,
    Endpoint dryRunEndpoint,
    DryRunProperties properties) {
  log.info("Pipeline dry runs will execute at {}", dryRunEndpoint.getUrl());
  OrcaService orca =
      new RestAdapter.Builder()
          .setEndpoint(dryRunEndpoint)
          .setConverter(new JacksonConverter())
          .setClient(
              new Ok3Client(
                  clientProvider.getClient(
                      new DefaultServiceEndpoint("orca", dryRunEndpoint.getUrl()))))
          .setLogLevel(retrofitLogLevel)
          .setLog(new Slf4jRetrofitLogger(OrcaService.class))
          .build()
          .create(OrcaService.class);
  return new DryRunNotificationAgent(front50, orca, properties);
}
 
Example #9
Source File: Front50Config.java    From echo with Apache License 2.0 6 votes vote down vote up
@Bean
public Front50Service front50Service(
    Endpoint front50Endpoint,
    OkHttpClientProvider clientProvider,
    LogLevel retrofitLogLevel,
    SpinnakerRequestInterceptor spinnakerRequestInterceptor) {
  log.info("front50 service loaded");

  return new Builder()
      .setEndpoint(front50Endpoint)
      .setConverter(new JacksonConverter())
      .setClient(
          new Ok3Client(
              clientProvider.getClient(
                  new DefaultServiceEndpoint("front50", front50Endpoint.getUrl()))))
      .setRequestInterceptor(spinnakerRequestInterceptor)
      .setLogLevel(retrofitLogLevel)
      .setLog(new Slf4jRetrofitLogger(Front50Service.class))
      .build()
      .create(Front50Service.class);
}
 
Example #10
Source File: JiraConfig.java    From echo with Apache License 2.0 5 votes vote down vote up
@Bean
JiraService jiraService(
    JiraProperties jiraProperties, Client retrofitClient, RestAdapter.LogLevel retrofitLogLevel) {
  if (x509ConfiguredClient != null) {
    LOGGER.info("Using X509 Cert for Jira Client");
    retrofitClient = x509ConfiguredClient;
  }

  RestAdapter.Builder builder =
      new RestAdapter.Builder()
          .setEndpoint(newFixedEndpoint(jiraProperties.getBaseUrl()))
          .setConverter(new JacksonConverter())
          .setClient(retrofitClient)
          .setLogLevel(retrofitLogLevel)
          .setLog(new Slf4jRetrofitLogger(JiraService.class));

  if (x509ConfiguredClient == null) {
    String credentials =
        String.format("%s:%s", jiraProperties.getUsername(), jiraProperties.getPassword());
    final String basic =
        String.format("Basic %s", Base64.encodeBase64String(credentials.getBytes()));
    builder.setRequestInterceptor(
        request -> {
          request.addHeader("Authorization", basic);
          request.addHeader("Accept", "application/json");
        });
  }

  return builder.build().create(JiraService.class);
}
 
Example #11
Source File: PagerDutyConfig.java    From echo with Apache License 2.0 5 votes vote down vote up
@Bean
PagerDutyService pagerDutyService(
    Endpoint pagerDutyEndpoint, Client retrofitClient, RestAdapter.LogLevel retrofitLogLevel) {
  log.info("Pager Duty service loaded");

  return new RestAdapter.Builder()
      .setEndpoint(pagerDutyEndpoint)
      .setConverter(new JacksonConverter())
      .setClient(retrofitClient)
      .setLogLevel(retrofitLogLevel)
      .setLog(new Slf4jRetrofitLogger(PagerDutyService.class))
      .build()
      .create(PagerDutyService.class);
}
 
Example #12
Source File: BooksAuthorsRobospiceRequest.java    From android-atleap with Apache License 2.0 5 votes vote down vote up
@Override
public void setUrl(String url) {
    ObjectMapper objectMapper = new ObjectMapper();
    //objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    //objectMapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);

    RestAdapter restAdapter = new RestAdapter.Builder()
            //.setConverter(new GsonConverter(new Gson()))
            .setConverter(new JacksonConverter(objectMapper))
            .setEndpoint(url)
            .build();


    this.service = restAdapter.create(BooksRetrofitService.class);
}
 
Example #13
Source File: PipelineTriggerConfiguration.java    From echo with Apache License 2.0 5 votes vote down vote up
private <T> T bindRetrofitService(final Class<T> type, final String endpoint) {
  log.info("Connecting {} to {}", type.getSimpleName(), endpoint);

  return new RestAdapter.Builder()
      .setClient(
          new Ok3Client(clientProvider.getClient(new DefaultServiceEndpoint("orca", endpoint))))
      .setRequestInterceptor(requestInterceptor)
      .setConverter(new JacksonConverter(EchoObjectMapper.getInstance()))
      .setEndpoint(endpoint)
      .setLogLevel(LogLevel.BASIC)
      .setLog(new Slf4jRetrofitLogger(type))
      .build()
      .create(type);
}
 
Example #14
Source File: KeelConfig.java    From echo with Apache License 2.0 5 votes vote down vote up
@Bean
public KeelService keelService(
    Endpoint keelEndpoint, OkHttpClientProvider clientProvider, LogLevel retrofitLogLevel) {
  return new RestAdapter.Builder()
      .setEndpoint(keelEndpoint)
      .setConverter(new JacksonConverter())
      .setClient(
          new Ok3Client(
              clientProvider.getClient(
                  new DefaultServiceEndpoint("keel", keelEndpoint.getUrl()))))
      .setLogLevel(retrofitLogLevel)
      .setLog(new Slf4jRetrofitLogger(KeelService.class))
      .build()
      .create(KeelService.class);
}
 
Example #15
Source File: Daemon.java    From halyard with Apache License 2.0 5 votes vote down vote up
private static DaemonService createService(boolean log) {
  return new RestAdapter.Builder()
      .setEndpoint(GlobalOptions.getGlobalOptions().getDaemonEndpoint())
      .setClient(new OkClient())
      .setConverter(new JacksonConverter(getObjectMapper()))
      .setLogLevel(log ? RestAdapter.LogLevel.FULL : RestAdapter.LogLevel.NONE)
      .build()
      .create(DaemonService.class);
}
 
Example #16
Source File: ResourcesConfig.java    From fiat with Apache License 2.0 5 votes vote down vote up
@Bean
@ConditionalOnProperty("services.igor.enabled")
IgorApi igorApi(@Value("${services.igor.base-url}") String igorEndpoint) {
  return new RestAdapter.Builder()
      .setEndpoint(Endpoints.newFixedEndpoint(igorEndpoint))
      .setClient(
          new Ok3Client(
              clientProvider.getClient(new DefaultServiceEndpoint("igor", igorEndpoint))))
      .setConverter(new JacksonConverter(objectMapper))
      .setLogLevel(retrofitLogLevel)
      .setLog(new Slf4jRetrofitLogger(IgorApi.class))
      .build()
      .create(IgorApi.class);
}
 
Example #17
Source File: ResourcesConfig.java    From fiat with Apache License 2.0 5 votes vote down vote up
@Bean
ClouddriverApi clouddriverApi() {
  return new RestAdapter.Builder()
      .setEndpoint(Endpoints.newFixedEndpoint(clouddriverEndpoint))
      .setClient(
          new Ok3Client(
              clientProvider.getClient(
                  new DefaultServiceEndpoint("clouddriver", clouddriverEndpoint))))
      .setConverter(new JacksonConverter(objectMapper))
      .setLogLevel(retrofitLogLevel)
      .setLog(new Slf4jRetrofitLogger(ClouddriverApi.class))
      .build()
      .create(ClouddriverApi.class);
}
 
Example #18
Source File: ResourcesConfig.java    From fiat with Apache License 2.0 5 votes vote down vote up
@Bean
Front50Api front50Api() {
  return new RestAdapter.Builder()
      .setEndpoint(Endpoints.newFixedEndpoint(front50Endpoint))
      .setClient(
          new Ok3Client(
              clientProvider.getClient(new DefaultServiceEndpoint("front50", front50Endpoint))))
      .setConverter(new JacksonConverter(objectMapper))
      .setLogLevel(retrofitLogLevel)
      .setLog(new Slf4jRetrofitLogger(Front50Api.class))
      .build()
      .create(Front50Api.class);
}
 
Example #19
Source File: RetrofitHelper.java    From android-atleap with Apache License 2.0 5 votes vote down vote up
public static RestAdapter.Builder createBaseRestAdapter(RestAdapter.Builder builder) {
    if (builder == null)
        builder = new RestAdapter.Builder();

    builder.setConverter(new JacksonConverter(new ObjectMapper()));

    if (BuildConfig.DEBUG) {
        builder.setLogLevel(RestAdapter.LogLevel.FULL);
    } else {
        builder.setLogLevel(RestAdapter.LogLevel.NONE);
    }

    return builder;
}
 
Example #20
Source File: AbstractManagementApiFactory.java    From apiman-cli with Apache License 2.0 5 votes vote down vote up
/**
 * @param apiClass     the Class for which to build a client
 * @param username     the management API username
 * @param password     the management API password
 * @param debugLogging whether debug logging should be enabled
 * @return an API client for the given Class
 */
protected A buildClient(Class<A> apiClass, String endpoint, String username, String password, boolean debugLogging) {
    final RestAdapter.Builder builder = new RestAdapter.Builder() //
            .setConverter(new JacksonConverter(JSON_MAPPER))
            .setEndpoint(endpoint)
            .setRequestInterceptor(request -> {
                request.addHeader(HEADER_AUTHORIZATION, AuthUtil.buildAuthString(username, password));
            });

    if (debugLogging) {
        builder.setLogLevel(RestAdapter.LogLevel.FULL);
    }

    return builder.build().create(apiClass);
}
 
Example #21
Source File: AptoideSpiceHttpService.java    From aptoide-client with GNU General Public License v2.0 5 votes vote down vote up
@Override
protected Converter createConverter() {

    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);

    return new JacksonConverter(objectMapper);
}
 
Example #22
Source File: AptoideSpiceHttpsService.java    From aptoide-client with GNU General Public License v2.0 5 votes vote down vote up
@Override
protected Converter createConverter() {

    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);

    return new JacksonConverter(objectMapper);
}
 
Example #23
Source File: HttpService.java    From aptoide-client with GNU General Public License v2.0 5 votes vote down vote up
@Override
protected Converter createConverter() {

    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);

    return new JacksonConverter(objectMapper);
}
 
Example #24
Source File: OauthErrorHandler.java    From aptoide-client with GNU General Public License v2.0 5 votes vote down vote up
public static Converter createConverter() {

        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);

        return new JacksonConverter(objectMapper);
    }
 
Example #25
Source File: DatadogConfiguration.java    From kayenta with Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
public static DatadogRemoteService createDatadogRemoteService(
    RetrofitClientFactory retrofitClientFactory,
    ObjectMapper objectMapper,
    RemoteService endpoint,
    OkHttpClient okHttpClient) {

  return retrofitClientFactory.createClient(
      DatadogRemoteService.class, new JacksonConverter(objectMapper), endpoint, okHttpClient);
}
 
Example #26
Source File: RepoManager.java    From dhis2-android-dashboard with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
private static Converter provideJacksonConverter() {
    return new JacksonConverter(ObjectMapperProvider.getInstance());
}
 
Example #27
Source File: RestConfig.java    From echo with Apache License 2.0 4 votes vote down vote up
@Bean
RestUrls restServices(
    RestProperties restProperties,
    RestClientFactory clientFactory,
    RestAdapter.LogLevel retrofitLogLevel,
    RequestInterceptorAttacher requestInterceptorAttacher,
    HeadersFromFile headersFromFile) {

  RestUrls restUrls = new RestUrls();

  for (RestProperties.RestEndpointConfiguration endpoint : restProperties.getEndpoints()) {
    RestAdapter.Builder restAdapterBuilder =
        new RestAdapter.Builder()
            .setEndpoint(newFixedEndpoint(endpoint.getUrl()))
            .setClient(clientFactory.getClient(endpoint.insecure))
            .setLogLevel(retrofitLogLevel)
            .setLog(new Slf4jRetrofitLogger(RestService.class))
            .setConverter(new JacksonConverter());

    Map<String, String> headers = new HashMap<>();

    if (endpoint.getUsername() != null && endpoint.getPassword() != null) {
      String basicAuthCreds = endpoint.getUsername() + ":" + endpoint.getPassword();
      String auth = "Basic " + Base64.encodeBase64String(basicAuthCreds.getBytes());
      headers.put("Authorization", auth);
    }

    if (endpoint.getHeaders() != null) {
      headers.putAll(endpoint.headers);
    }

    if (endpoint.getHeadersFile() != null) {
      headers.putAll(headersFromFile.headers(endpoint.getHeadersFile()));
    }

    if (!headers.isEmpty()) {
      RequestInterceptor headerInterceptor = request -> headers.forEach(request::addHeader);
      requestInterceptorAttacher.attach(restAdapterBuilder, headerInterceptor);
    }

    RestUrls.Service service =
        RestUrls.Service.builder()
            .client(restAdapterBuilder.build().create(RestService.class))
            .config(endpoint)
            .build();

    restUrls.getServices().add(service);
  }

  return restUrls;
}
 
Example #28
Source File: NewRelicConfiguration.java    From kayenta with Apache License 2.0 4 votes vote down vote up
@Bean
MetricsService newrelicMetricsService(
    NewRelicConfigurationProperties newrelicConfigurationProperties,
    RetrofitClientFactory retrofitClientFactory,
    ObjectMapper objectMapper,
    OkHttpClient okHttpClient,
    AccountCredentialsRepository accountCredentialsRepository) {

  NewRelicMetricsService.NewRelicMetricsServiceBuilder metricsServiceBuilder =
      NewRelicMetricsService.builder();

  for (NewRelicManagedAccount account : newrelicConfigurationProperties.getAccounts()) {
    String name = account.getName();
    List<AccountCredentials.Type> supportedTypes = account.getSupportedTypes();

    NewRelicCredentials credentials =
        NewRelicCredentials.builder()
            .apiKey(account.getApiKey())
            .applicationKey(account.getApplicationKey())
            .build();

    RemoteService endpoint = account.getEndpoint();

    if (endpoint == null) {
      endpoint = new RemoteService().setBaseUrl("https://insights-api.newrelic.com");
    }

    NewRelicNamedAccountCredentials.NewRelicNamedAccountCredentialsBuilder
        accountCredentialsBuilder =
            NewRelicNamedAccountCredentials.builder()
                .name(name)
                .endpoint(endpoint)
                .credentials(credentials);

    if (!CollectionUtils.isEmpty(supportedTypes)) {
      if (supportedTypes.contains(AccountCredentials.Type.METRICS_STORE)) {
        accountCredentialsBuilder.newRelicRemoteService(
            retrofitClientFactory.createClient(
                NewRelicRemoteService.class,
                new JacksonConverter(objectMapper),
                endpoint,
                okHttpClient));
      }
      accountCredentialsBuilder.supportedTypes(supportedTypes);
    }

    accountCredentialsRepository.save(name, accountCredentialsBuilder.build());
    metricsServiceBuilder.accountName(name);
  }

  log.info(
      "Configured the New Relic Metrics Service with the following accounts: {}",
      newrelicConfigurationProperties.getAccounts().stream()
          .map(NewRelicManagedAccount::getName)
          .collect(Collectors.joining(",")));

  return metricsServiceBuilder.build();
}
 
Example #29
Source File: GraphiteConfiguration.java    From kayenta with Apache License 2.0 4 votes vote down vote up
@Bean
MetricsService graphiteMetricsService(
    GraphiteConfigurationProperties graphiteConfigurationProperties,
    RetrofitClientFactory retrofitClientFactory,
    ObjectMapper objectMapper,
    OkHttpClient okHttpClient,
    AccountCredentialsRepository accountCredentialsRepository)
    throws IOException {
  GraphiteMetricsService.GraphiteMetricsServiceBuilder graphiteMetricsServiceBuilder =
      GraphiteMetricsService.builder();

  for (GraphiteManagedAccount account : graphiteConfigurationProperties.getAccounts()) {
    String accountName = account.getName();
    List<AccountCredentials.Type> supportedTypes = account.getSupportedTypes();

    GraphiteCredentials credentials = GraphiteCredentials.builder().build();

    GraphiteNamedAccountCredentials.GraphiteNamedAccountCredentialsBuilder
        accountCredentialsBuilder =
            GraphiteNamedAccountCredentials.builder()
                .name(accountName)
                .endpoint(account.getEndpoint())
                .credentials(credentials);
    if (!CollectionUtils.isEmpty(supportedTypes)) {
      if (supportedTypes.contains(AccountCredentials.Type.METRICS_STORE)) {
        accountCredentialsBuilder.graphiteRemoteService(
            retrofitClientFactory.createClient(
                GraphiteRemoteService.class,
                new JacksonConverter(objectMapper),
                account.getEndpoint(),
                okHttpClient));
      }

      accountCredentialsBuilder.supportedTypes(supportedTypes);
    }

    accountCredentialsRepository.save(accountName, accountCredentialsBuilder.build());
    graphiteMetricsServiceBuilder.accountName(accountName);
  }

  log.info(
      "Populated GraphiteMetricsService with {} Graphite accounts.",
      graphiteConfigurationProperties.getAccounts().size());
  return graphiteMetricsServiceBuilder.build();
}
 
Example #30
Source File: PrometheusResponseConverter.java    From kayenta with Apache License 2.0 4 votes vote down vote up
@Override
public Object fromBody(TypedInput body, Type type) throws ConversionException {
  if (type == PrometheusMetricDescriptorsResponse.class) {
    return new JacksonConverter(kayentaObjectMapper).fromBody(body, type);
  } else {
    try (BufferedReader reader = new BufferedReader(new InputStreamReader(body.in()))) {
      String json = reader.readLine();
      Map responseMap = kayentaObjectMapper.readValue(json, Map.class);
      Map data = (Map) responseMap.get("data");
      List<Map> resultList = (List<Map>) data.get("result");
      List<PrometheusResults> prometheusResultsList =
          new ArrayList<PrometheusResults>(resultList.size());

      if (CollectionUtils.isEmpty(resultList)) {
        log.warn("Received no data from Prometheus.");
        return null;
      }

      for (Map elem : resultList) {
        Map<String, String> tags = (Map<String, String>) elem.get("metric");
        String id = tags.remove("__name__");
        List<List> values = (List<List>) elem.get("values");
        List<Double> dataValues = new ArrayList<Double>(values.size());

        for (List tuple : values) {
          String val = (String) tuple.get(1);
          if (val != null) {
            switch (val) {
              case "+Inf":
                dataValues.add(Double.POSITIVE_INFINITY);
                break;
              case "-Inf":
                dataValues.add(Double.NEGATIVE_INFINITY);
                break;
              case "NaN":
                dataValues.add(Double.NaN);
                break;
              default:
                dataValues.add(Double.valueOf(val));
            }
          }
        }

        long startTimeMillis =
            doubleTimestampSecsToLongTimestampMillis(values.get(0).get(0) + "");
        // If there aren't at least two data points, consider the step size to be zero.
        long stepSecs =
            values.size() > 1
                ? TimeUnit.MILLISECONDS.toSeconds(
                    doubleTimestampSecsToLongTimestampMillis(values.get(1).get(0) + "")
                        - startTimeMillis)
                : 0;
        long endTimeMillis = startTimeMillis + values.size() * stepSecs * 1000;

        prometheusResultsList.add(
            new PrometheusResults(
                id, startTimeMillis, stepSecs, endTimeMillis, tags, dataValues));
      }

      return prometheusResultsList;
    } catch (IOException e) {
      e.printStackTrace();
    }

    return null;
  }
}