Skip to content

Commit

Permalink
[HWKMETRICS-185] Rough translation of Async code to sync variant for …
Browse files Browse the repository at this point in the history
…REST handlers.
  • Loading branch information
Stefan Negrea committed Jul 27, 2015
1 parent aae8b97 commit a8a7d7c
Show file tree
Hide file tree
Showing 12 changed files with 362 additions and 281 deletions.
22 changes: 22 additions & 0 deletions api/metrics-api-jaxrs-1.1/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,12 @@
<version>${project.version}</version>
</dependency>

<dependency>
<groupId>org.hawkular.metrics</groupId>
<artifactId>hawkular-metrics-api-common</artifactId>
<version>${project.version}</version>
</dependency>

<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
Expand All @@ -66,6 +72,22 @@
<scope>provided</scope>
<version>2.3.10.Final</version>
</dependency>

<dependency>
<groupId>org.jboss.spec.javax.servlet</groupId>
<artifactId>jboss-servlet-api_3.0_spec</artifactId>
<version>1.0.2.Final</version>
</dependency>

<dependency>
<groupId>io.reactivex</groupId>
<artifactId>rxjava</artifactId>
</dependency>

<dependency>
<groupId>io.reactivex</groupId>
<artifactId>rxjava-math</artifactId>
</dependency>

<!-- documentation -->
<dependency>
Expand Down

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@
import static javax.ws.rs.core.MediaType.APPLICATION_XHTML_XML;
import static javax.ws.rs.core.MediaType.TEXT_HTML;

import com.wordnik.swagger.annotations.ApiOperation;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
Expand All @@ -29,8 +28,11 @@
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response;

import org.jboss.resteasy.spi.ResteasyProviderFactory;

import com.wordnik.swagger.annotations.ApiOperation;

/**
* @author mwringe
*/
Expand Down Expand Up @@ -70,14 +72,17 @@ private class HawkularMetricsBase {
String name = "Hawkular-Metrics";
String version;

@SuppressWarnings("unused")
public String getName() {
return name;
}

@SuppressWarnings("unused")
public void setVersion(String version) {
this.version = version;
}

@SuppressWarnings("unused")
public String getVersion() {
return version;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,7 @@

import static java.util.concurrent.TimeUnit.HOURS;
import static java.util.concurrent.TimeUnit.MILLISECONDS;

import static javax.ws.rs.core.MediaType.APPLICATION_JSON;

import static org.hawkular.metrics.api.jaxrs.filter.TenantFilter.TENANT_HEADER_NAME;
import static org.hawkular.metrics.api.jaxrs.util.ApiUtils.requestToCounterDataPoints;
import static org.hawkular.metrics.api.jaxrs.util.ApiUtils.requestToCounters;
Expand All @@ -29,7 +27,6 @@
import java.net.URI;
import java.util.List;

import javax.inject.Inject;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.HeaderParam;
Expand All @@ -38,15 +35,13 @@
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.container.AsyncResponse;
import javax.ws.rs.container.Suspended;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;

import org.hawkular.metrics.api.jaxrs.ApiError;
import org.hawkular.metrics.api.jaxrs.handler.observer.EntityCreatedObserver;
import org.hawkular.metrics.api.jaxrs.handler.observer.MetricCreatedObserver;
import org.hawkular.metrics.api.jaxrs.handler.observer.ResultSetObserver;
import org.hawkular.metrics.api.jaxrs.model.Counter;
import org.hawkular.metrics.api.jaxrs.model.CounterDataPoint;
import org.hawkular.metrics.api.jaxrs.model.GaugeDataPoint;
Expand Down Expand Up @@ -81,7 +76,6 @@ public class CounterHandler {

private static final long EIGHT_HOURS = MILLISECONDS.convert(8, HOURS);

@Inject
private MetricsService metricsService;

@HeaderParam(TENANT_HEADER_NAME)
Expand All @@ -102,15 +96,23 @@ public class CounterHandler {
@ApiResponse(code = 500, message = "Metric definition creation failed due to an unexpected error",
response = ApiError.class)
})
public void createCounter(
@Suspended final AsyncResponse asyncResponse,
public Response createCounter(
@ApiParam(required = true) MetricDefinition metricDefinition,
@Context UriInfo uriInfo
) {
Metric<Double> metric = new Metric<>(tenantId, COUNTER, new MetricId(metricDefinition.getId()),
metricDefinition.getTags(), metricDefinition.getDataRetention());
URI location = uriInfo.getBaseUriBuilder().path("/counters/{id}").build(metric.getId().getName());
metricsService.createMetric(metric).subscribe(new MetricCreatedObserver(asyncResponse, location));

try {
EntityCreatedObserver<?> observer = new MetricCreatedObserver(location);
Observable<Void> observable = metricsService.createMetric(metric);
observable.subscribe(observer);
observable.toBlocking().last();
return observer.getResponse();
} catch (Exception e) {
return ApiUtils.serverError(e);
}
}

@GET
Expand All @@ -121,13 +123,16 @@ public void createCounter(
@ApiResponse(code = 204, message = "Query was successful, but no metrics definition is set."),
@ApiResponse(code = 500, message = "Unexpected error occurred while fetching metric's definition.",
response = ApiError.class) })
public void getCounter(@Suspended final AsyncResponse asyncResponse, @PathParam("id") String id) {

metricsService.findMetric(tenantId, COUNTER, new MetricId(id))
public Response getCounter(@PathParam("id") String id) {
try {
return metricsService.findMetric(tenantId, COUNTER, new MetricId(id))
.map(MetricDefinition::new)
.map(metricDef -> Response.ok(metricDef).build())
.switchIfEmpty(Observable.just(ApiUtils.noContent()))
.subscribe(asyncResponse::resume, t -> asyncResponse.resume(ApiUtils.serverError(t)));
.toBlocking().last();
} catch (Exception e) {
return ApiUtils.serverError(e);
}
}

@POST
Expand All @@ -139,12 +144,14 @@ public void getCounter(@Suspended final AsyncResponse asyncResponse, @PathParam(
@ApiResponse(code = 500, message = "Unexpected error happened while storing the data points",
response = ApiError.class)
})
public void addData(@Suspended final AsyncResponse asyncResponse,
@ApiParam(value = "List of metrics", required = true) List<Counter> counters
public Response addData(@ApiParam(value = "List of metrics", required = true) List<Counter> counters
) {
Observable<Metric<Long>> metrics = requestToCounters(tenantId, counters);
Observable<Void> observable = metricsService.addCounterData(metrics);
observable.subscribe(new ResultSetObserver(asyncResponse));
try {
return metricsService.addCounterData(metrics).map(ApiUtils::simpleOKResponse).toBlocking().last();
} catch (Exception e) {
return ApiUtils.serverError(e);
}
}

@POST
Expand All @@ -156,15 +163,18 @@ public void addData(@Suspended final AsyncResponse asyncResponse,
@ApiResponse(code = 500, message = "Unexpected error happened while storing the data",
response = ApiError.class),
})
public void addData(
@Suspended final AsyncResponse asyncResponse,
public Response addData(
@PathParam("id") String id,
@ApiParam(value = "List of data points containing timestamp and value", required = true)
List<CounterDataPoint> data
) {
Metric<Long> metric = new Metric<>(tenantId, COUNTER, new MetricId(id), requestToCounterDataPoints(data));
Observable<Void> observable = metricsService.addCounterData(Observable.just(metric));
observable.subscribe(new ResultSetObserver(asyncResponse));
try {
return metricsService.addCounterData(Observable.just(metric)).map(ApiUtils::simpleOKResponse).toBlocking()
.last();
} catch (Exception e) {
return ApiUtils.serverError(e);
}
}

@GET
Expand All @@ -177,8 +187,7 @@ public void addData(
response = ApiError.class),
@ApiResponse(code = 500, message = "Unexpected error occurred while fetching metric data.",
response = ApiError.class) })
public void findCounterData(
@Suspended AsyncResponse asyncResponse,
public Response findCounterData(
@PathParam("id") String id,
@ApiParam(value = "Defaults to now - 8 hours") @QueryParam("start") final Long start,
@ApiParam(value = "Defaults to now") @QueryParam("end") final Long end) {
Expand All @@ -187,16 +196,15 @@ public void findCounterData(
long startTime = start == null ? now - EIGHT_HOURS : start;
long endTime = end == null ? now : end;

metricsService.findCounterData(tenantId, new MetricId(id), startTime, endTime)
try {
return metricsService.findCounterData(tenantId, new MetricId(id), startTime, endTime)
.map(CounterDataPoint::new)
.toList()
.map(ApiUtils::collectionToResponse)
.subscribe(
asyncResponse::resume,
t -> {
logger.warn("Failed to fetch counter data", t);
ApiUtils.serverError(t);
});
.map(ApiUtils::collectionToResponse).toBlocking().last();
} catch (Exception e) {
logger.warn("Failed to fetch counter data", e);
return ApiUtils.serverError(e);
}
}

@GET
Expand All @@ -212,8 +220,7 @@ public void findCounterData(
response = ApiError.class),
@ApiResponse(code = 500, message = "Unexpected error occurred while fetching metric data.",
response = ApiError.class) })
public void findRate(
@Suspended AsyncResponse asyncResponse,
public Response findRate(
@PathParam("id") String id,
@ApiParam(value = "Defaults to now - 8 hours") @QueryParam("start") final Long start,
@ApiParam(value = "Defaults to now") @QueryParam("end") final Long end) {
Expand All @@ -222,16 +229,16 @@ public void findRate(
long startTime = start == null ? now - EIGHT_HOURS : start;
long endTime = end == null ? now : end;

metricsService.findRateData(tenantId, new MetricId(id), startTime, endTime)
try {
return metricsService.findRateData(tenantId, new MetricId(id), startTime, endTime)
.map(GaugeDataPoint::new)
.toList()
.map(ApiUtils::collectionToResponse)
.subscribe(
asyncResponse::resume,
t -> {
logger.warn("Failed to fetch counter rate data", t);
ApiUtils.serverError(t);
});
.toBlocking().last();
} catch (Exception e) {
logger.warn("Failed to fetch counter rate data", e);
return ApiUtils.serverError(e);
}
}

}

0 comments on commit a8a7d7c

Please sign in to comment.