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

com.groupbyinc.common.directbeacon.DirectBeaconClientTask Maven / Gradle / Ivy

There is a newer version: 198
Show newest version
package com.groupbyinc.common.directbeacon;

import com.groupbyinc.common.jackson.Mappers;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.SocketTimeoutException;
import java.net.URI;
import java.nio.charset.Charset;

@SuppressWarnings("WeakerAccess")
public class DirectBeaconClientTask implements Runnable {

  private static final transient Logger LOG = LoggerFactory.getLogger(DirectBeaconClientTask.class);
  private static final Charset UTF8 = Charset.forName("UTF-8");
  private static final String APPLICATION_JSON = "application/json";

  private final URI uri;
  private final HttpClient httpClient;
  private final String authToken;
  private DirectBeacon beacon;

  public DirectBeaconClientTask(HttpClient httpClient, URI uri, DirectBeacon beacon, String authToken) {
    this.uri = uri;
    this.httpClient = httpClient;
    this.beacon = beacon;
    this.authToken = authToken;
  }

  public void run() {
    HttpEntity responseEntity = null;
    try {
      String json = Mappers.writeValueAsString(beacon);
      StringEntity entity = new StringEntity(json, UTF8);
      entity.setContentType(APPLICATION_JSON);

      HttpPost post = new HttpPost(uri);
      post.setEntity(entity);
      post.setHeader("Authorization", authToken);

      HttpResponse response = httpClient.execute(post);
      responseEntity = response.getEntity();

      StatusLine statusLine = response.getStatusLine();
      LOG.trace("Got: {}", statusLine.getStatusCode());
    } catch (SocketTimeoutException e) {
      LOG.trace("Dropped beacon: {}", e.getMessage());
    } catch (Exception e) {
      LOG.warn("Could not send beacon", e);
    } finally {
      if (responseEntity != null) {
        EntityUtils.consumeQuietly(responseEntity);
      }
    }
  }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy