Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * Copyright 2015 Attribyte, LLC
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   * http://www.apache.org/licenses/LICENSE-2.0
   *
  * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and limitations under the License.
  *
  */
 
 package org.attribyte.essem.reporter;
 
 
 import java.net.URI;
 import java.net.URL;
 import java.util.Map;
A scheduled metric reporter that reports over HTTP(s) using the "essem" protocol.
 
 public class EssemReporter extends ScheduledReporter implements MetricSet {

   
Creates a builder.

Parameters:
uri The URI to report to.
registry the registry to report
Returns:
The builder.
 
    public static Builder newBuilder(final URI urifinal MetricRegistry registry) {
       return new Builder(uriregistry);
    }
 
    public static class Builder {

      
Creates a builder.

Parameters:
uri The essem endpoint URI.
registry The registry to report.
 
       private Builder(final URI urifinal MetricRegistry registry) {
          this. = uri;
          this. = registry;
          this. = Clock.defaultClock();
          this. = .;
          this. = .;
          this. = .;
          this. = null;
          this. = null;
          this. = null;
       }

      
Configures the clock.

Parameters:
clock The clock.
Returns:
A self-reference.
 
       public Builder withClock(final Clock clock) {
          this. = clock;
          return this;
       }

      
Sets the application name.

Parameters:
application The application name.
Returns:
A self-reference.
      public Builder forApplication(final String application) {
         this. = application;
         return this;
      }

      
Sets the host.

Parameters:
host The host.
Returns:
A self-reference.
      public Builder forHost(final String host) {
         this. = host;
         return this;
      }

      
Sets the instance name.

Parameters:
instance The instance name.
Returns:
A self-reference.
      public Builder forInstance(final String instance) {
         this. = instance;
         return this;
      }

      
Configures the rate conversion. Default is seconds.

Parameters:
rateUnit The rate unit.
Returns:
A self-reference.
      public Builder convertRatesTo(final TimeUnit rateUnit) {
         this. = rateUnit;
         return this;
      }

      
Configures the duration conversion. Default is milliseconds.

Parameters:
durationUnit The duration unit.
Returns:
A self-reference.
      public Builder convertDurationsTo(final TimeUnit durationUnit) {
         this. = durationUnit;
         return this;
      }

      
Applies a filter to the registry before reporting.

Parameters:
filter The filter.
Returns:
A self-reference.
      public Builder filter(final MetricFilter filter) {
         this. = filter;
         return this;
      }

      
Sets a value to be sent as the value of the Authorization header.

Parameters:
authValue The authorization header value.
Returns:
A self-reference.
      public Builder withAuthorization(final String authValue) {
         this. = authValue;
         return this;
      }

      
Configures HTTP Basic auth.

Parameters:
username The username.
password The password.
Returns:
A self-reference.
      public Builder withBasicAuthorization(final String usernamefinal String password) {
         if(username != null && password != null) {
            byte[] up = (username + ":" + password).getBytes(.);
            return withAuthorization("Basic " + BaseEncoding.base64().encode(up));
         } else {
            return this;
         }
      }

      
Configures 'deflate' of sent reports.

Parameters:
deflate Should deflate be used?
Returns:
A self-reference.
      public Builder withDeflate(final boolean deflate) {
         this. = deflate;
         return this;
      }

      
Builds an immutable reporter instance.

Returns:
The immutable reporter.
      public EssemReporter build() {
         return new EssemReporter(,
                 );
      }
      private final URI uri;
      private final MetricRegistry registry;
      private String authValue;
      private Clock clock = Clock.defaultClock();
      private String application;
      private String host;
      private String instance;
      private boolean deflate;
      private TimeUnit rateUnit = .;
      private TimeUnit durationUnit = .;
      private MetricFilter filter;
   }
   protected EssemReporter(final URI uri,
                           final String authValue,
                           final boolean deflate,
                           final MetricRegistry registry,
                           final Clock clock,
                           final String application,
                           final String host,
                           final String instance,
                           final MetricFilter filter,
                           final TimeUnit rateUnit,
                           final TimeUnit durationUnit) {
      super(registry"essem-reporter"filterrateUnitdurationUnit);
      this. = uri;
      this. = authValue;
      this. = deflate;
      this. = clock;
      this. = application;
      this. = host;
      this. = instance;
      this. = rateUnit;
      this. = durationUnit;
   }

   
Builds a report for a specified registry.

Parameters:
registry The registry.
Returns:
The report.
   public ReportProtos.EssemReport buildReport(final MetricRegistry registry) {
      return buildReport(registry.getGauges(),
              registry.getCounters(),
              registry.getHistograms(),
              registry.getMeters(),
              registry.getTimers());
   }

   
Builds a report for a registry.

Parameters:
registry The registry.
filter A filter.
Returns:
The report.
   public ReportProtos.EssemReport buildReport(final MetricRegistry registry,
                                               final MetricFilter filter) {
      return buildReport(registry.getGauges(filter),
              registry.getCounters(filter),
              registry.getHistograms(filter),
              registry.getMeters(filter),
              registry.getTimers(filter));
   }
                                                SortedMap<StringCountercounters,
                                                SortedMap<StringHistogramhistograms,
                                                SortedMap<StringMetermeters,
                                                SortedMap<StringTimertimers) {
      ReportProtos.EssemReport.Builder builder = ReportProtos.EssemReport.newBuilder();
      builder.setTimestamp(.getTime());
      builder.setDurationUnit(toProto());
      builder.setRateUnit(toProto());
      if( != nullbuilder.setApplication();
      if( != nullbuilder.setHost();
      if( != nullbuilder.setInstance();
      for(Map.Entry<StringGaugegauge : gauges.entrySet()) {
         Object val = gauge.getValue().getValue();
         ReportProtos.EssemReport.Gauge.Builder gaugeBuilder = builder.addGaugeBuilder();
         gaugeBuilder.setName(gauge.getKey());
         if(val instanceof Number) {
            gaugeBuilder.setValue(((Number)val).doubleValue());
         } else {
            gaugeBuilder.setComment(val.toString());
         }
      }
      for(Map.Entry<StringCountercounter : counters.entrySet()) {
         builder.addCounterBuilder()
                 .setName(counter.getKey())
                 .setCount(counter.getValue().getCount());
      }
      for(Map.Entry<StringMeternv : meters.entrySet()) {
         Meter meter = nv.getValue();
         builder.addMeterBuilder()
                 .setName(nv.getKey())
                 .setCount(meter.getCount())
                 .setOneMinuteRate(convertRate(meter.getOneMinuteRate()))
                 .setFiveMinuteRate(convertRate(meter.getFiveMinuteRate()))
                 .setFifteenMinuteRate(convertRate(meter.getFifteenMinuteRate()))
                 .setMeanRate(convertRate(meter.getMeanRate()));
      }
      for(Map.Entry<StringHistogramnv : histograms.entrySet()) {
         Histogram histogram = nv.getValue();
         Snapshot snapshot = histogram.getSnapshot();
         builder.addHistogramBuilder()
                 .setName(nv.getKey())
                 .setCount(histogram.getCount())
                 .setMax(snapshot.getMax())
                 .setMin(snapshot.getMin())
                 .setMedian(snapshot.getMedian())
                 .setMean(snapshot.getMean())
                 .setStd(snapshot.getStdDev())
                 .setPercentile75(snapshot.get75thPercentile())
                 .setPercentile95(snapshot.get95thPercentile())
                 .setPercentile98(snapshot.get98thPercentile())
                 .setPercentile99(snapshot.get99thPercentile())
                 .setPercentile999(snapshot.get999thPercentile());
      }
      for(Map.Entry<StringTimernv : timers.entrySet()) {
         Timer timer = nv.getValue();
         Snapshot snapshot = timer.getSnapshot();
         builder.addTimerBuilder()
                 .setName(nv.getKey())
                 .setOneMinuteRate(convertRate(timer.getOneMinuteRate()))
                 .setFiveMinuteRate(convertRate(timer.getFiveMinuteRate()))
                 .setFifteenMinuteRate(convertRate(timer.getFifteenMinuteRate()))
                 .setMeanRate(convertRate(timer.getMeanRate()))
                 .setCount(timer.getCount())
                 .setMax(convertDuration(snapshot.getMax()))
                 .setMin(convertDuration(snapshot.getMin()))
                 .setMedian(convertDuration(snapshot.getMedian()))
                 .setMean(convertDuration(snapshot.getMean()))
                 .setStd(convertDuration(snapshot.getStdDev()))
                 .setPercentile75(convertDuration(snapshot.get75thPercentile()))
                 .setPercentile95(convertDuration(snapshot.get95thPercentile()))
                 .setPercentile98(convertDuration(snapshot.get98thPercentile()))
                 .setPercentile99(convertDuration(snapshot.get99thPercentile()))
                 .setPercentile999(convertDuration(snapshot.get999thPercentile()));
      }
      return builder.build();
   }
   public void report(SortedMap<StringGaugegauges,
                      SortedMap<StringCountercounters,
                      SortedMap<StringHistogramhistograms,
                      SortedMap<StringMetermeters,
                      SortedMap<StringTimertimers) {
      Timer.Context ctx = .time();
      try {
         int responseCode = send(buildReport(gaugescountershistogramsmeterstimers));
         if(responseCode / 100 != 2) {
            .warn("EssemReporter: Unable to report (" + responseCode + ")");
         } else {
            .debug("EssemReporter: Reported (" + responseCode + ")");
         }
      } catch(IOException ioe) {
         ioe.printStackTrace();
         .warn("Unable to report to Essem"ioe);
         .mark();
      } finally {
         ctx.stop();
      }
   }
   private int send(final URI urifinal ReportProtos.EssemReport reportthrows IOException {
      HttpURLConnection conn = null;
      InputStream is = null;
      try {
         URL url = uri.toURL();
         conn = (HttpURLConnection)url.openConnection();
         if(conn != null) {
            conn.setRequestMethod("PUT");
            if(!Strings.isNullOrEmpty()) {
               conn.setRequestProperty();
            }
            conn.setDoOutput(true);
            conn.setInstanceFollowRedirects(false);
            byte[] reportBytes = report.toByteArray();
            if() {
               conn.setRequestProperty();
               reportBytes = deflate(reportBytes);
            }
            conn.setFixedLengthStreamingMode(reportBytes.length);
            .update(reportBytes.length);
            conn.connect();
            OutputStream os = conn.getOutputStream();
            os.write(reportBytes);
            os.flush();
            os.close();
            int code = conn.getResponseCode();
            is = code / 100 == 2 ? conn.getInputStream() : conn.getErrorStream();
            discardInputAndClose(is);
            is = null;
            return code;
         } else {
            throw new IOException("Unable to 'PUT' to " + uri.toString());
         }
      } catch(IOException ioe) {
         if(conn != null && is == nulldiscardInputAndClose(conn.getErrorStream());
         throw ioe;
      } finally {
         if(conn != null) {
            conn.disconnect();
         }
      }
   }

   
Converts time units to the proto enum.

Parameters:
timeUnit The time unit.
Returns:
The protobuf enum value.
   protected ReportProtos.EssemReport.TimeUnit toProto(final TimeUnit timeUnit) {
      switch(timeUnit) {
         case return ...;
         case return ...;
         case return ...;
         case return ...;
         case return ...;
         case return ...;
         case return ...;
         defaultthrow new AssertionError();
      }
   }

   
Reads and discards all input from a stream.

Parameters:
is The input stream.
Throws:
java.io.IOException on read error.
   private void discardInputAndClose(final InputStream isthrows IOException {
      if(is != null) {
         ByteStreams.toByteArray(is);
         try {
            is.close();
         } catch(IOException ioe) {
            //Ignore
         }
      }
   }

   
Deflates bytes.

Parameters:
b The bytes to deflate.
Returns:
The deflated bytes.
   private static byte[] deflate(final byte[] b) {
      try {
         Deflater deflater = new Deflater(.false); //nowrap = false
         ByteArrayOutputStream baos = new ByteArrayOutputStream();
         DeflaterOutputStream dos = new DeflaterOutputStream(baosdeflater);
         dos.write(b);
         dos.close();
         return baos.toByteArray();
      } catch(IOException ioe) {
         throw new AssertionError("I/O exception on in-memory stream");
      }
   }

   
The authorization header.
   public static final String AUTHORIZATION_HEADER = "Authorization";

   
The content type header.
   public static final String CONTENT_TYPE_HEADER = "Content-Type";

   
The protocol buffer content type (application/x-protobuf).
   public static final String PROTOBUF_CONTENT_TYPE = "application/x-protobuf";

   
The content encoding header.
   public static final String CONTENT_ENCODING_HEADER = "Content-Encoding";

   
The 'deflate' content type.
   public static final String DEFLATE_ENCODING = "deflate";

   
The default logger.
   private static final Logger LOGGER = LoggerFactory.getLogger(EssemReporter.class);
   private final String application;
   private final String host;
   private final String instance;
   private final Clock clock;
   private final URI uri;
   private final TimeUnit rateUnit;
   private final TimeUnit durationUnit;
   private final String authValue;
   private final boolean deflate;
   private final Timer sendTimer = new Timer();
   private final Meter sendErrors = new Meter();
   private final Histogram reportSize = new Histogram(new ExponentiallyDecayingReservoir());
   private final ImmutableMap<StringMetricmetrics =
           ImmutableMap.<StringMetric>of(
                   "reports",
                   "failed-reports",
                   "report-size-bytes"
           );
   public Map<StringMetricgetMetrics() {
      return ;
   }
New to GrepCode? Check out our FAQ X