List of usage examples for com.google.common.net MediaType JSON_UTF_8
MediaType JSON_UTF_8
To view the source code for com.google.common.net MediaType JSON_UTF_8.
Click Source Link
From source file:controllers.api.DashboardsApiController.java
public Result widgetValue(String dashboardId, String widgetId, int resolution) { try {/*from w w w . j a va2 s.c o m*/ Dashboard dashboard = dashboardService.get(dashboardId); DashboardWidget widget = dashboard.getWidget(widgetId); if (widget == null) { return notFound(); } DashboardWidgetValueResponse widgetValue = widget.getValue(api()); Object resultValue; if (widget instanceof ChartWidget) { resultValue = formatWidgetValueResults(resolution, widget, widgetValue); } else { resultValue = widgetValue.result; } Map<String, Object> result = Maps.newHashMap(); result.put("result", resultValue); result.put("took_ms", widgetValue.tookMs); result.put("calculated_at", widgetValue.calculatedAt); result.put("time_range", widgetValue.computationTimeRange); return ok(Json.toJsonString(result)).as(MediaType.JSON_UTF_8.toString()); } catch (APIException e) { try { final ApiErrorMessage apiErrorMessage = mapper.readValue(e.getResponseBody(), ApiErrorMessage.class); return status(e.getHttpCode(), apiErrorMessage.message); } catch (IOException e1) { return status(504, e.getMessage()); } } catch (IOException e) { return status(504, e.getMessage()); } }
From source file:eu.seaclouds.policy.SeaCloudsManagementPolicy.java
private void installInfluxDbObservers() { LOG.info("SeaCloudsInitializerPolicy is installing InfluxDB Observers for " + entity.getId()); for (String metricName : extractMetricNames()) { HttpToolResponse response = post(getConfig(T4C_ENDPOINT) + "/v1/metrics/" + metricName + "/observers", MediaType.JSON_UTF_8.toString(), getConfig(T4C_USERNAME), getConfig(T4C_PASSWORD), observerInitializerPayload.getBytes()); if (!HttpTool.isStatusCodeHealthy(response.getResponseCode())) { throw new RuntimeException("Something went wrong while attaching the observers to the Rules. " + "Invalid response code, " + response.getResponseCode() + ":" + response.getContentAsString()); }// ww w . j ava 2s .c om } }
From source file:eu.seaclouds.policy.SeaCloudsManagementPolicy.java
private void installGrafanaDashboards() { try {//from w w w. ja v a 2 s . c om HttpToolResponse response = post(getConfig(GRAFANA_ENDPOINT) + "/api/dashboards/db", MediaType.JSON_UTF_8.toString(), getConfig(GRAFANA_USERNAME), getConfig(GRAFANA_PASSWORD), grafanaInitializerPayload.getBytes()); if (!HttpTool.isStatusCodeHealthy(response.getResponseCode())) { throw new RuntimeException( "Something went wrong while installing Grafana Dashboards. " + "Invalid response code, " + response.getResponseCode() + ":" + response.getContentAsString()); } // Retrieving unique slug to be able to remove the Dashboard later ObjectMapper mapper = new ObjectMapper(); JsonNode json = mapper.readTree(response.getContent()); grafanaDashboardSlug = json.get("slug").asText(); } catch (Exception e) { Exceptions.propagateIfFatal(e); LOG.warn("Error installingGrafanaDashboards, using " + getConfig(GRAFANA_ENDPOINT) + "/api/dashboards/db {}", e); } }
From source file:org.glowroot.local.ui.HttpServerHandler.java
private FullHttpResponse buildJsonResponse(@Nullable Object responseObject) { FullHttpResponse response;//from ww w . ja v a2 s .c o m if (responseObject == null) { response = new DefaultFullHttpResponse(HTTP_1_1, OK); } else if (responseObject instanceof FullHttpResponse) { response = (FullHttpResponse) responseObject; } else if (responseObject instanceof String) { ByteBuf content = Unpooled.copiedBuffer(responseObject.toString(), Charsets.ISO_8859_1); response = new DefaultFullHttpResponse(HTTP_1_1, OK, content); } else { logger.warn("unexpected type of json service response: {}", responseObject.getClass().getName()); return new DefaultFullHttpResponse(HTTP_1_1, INTERNAL_SERVER_ERROR); } response.headers().add(Names.CONTENT_TYPE, MediaType.JSON_UTF_8); HttpServices.preventCaching(response); return response; }
From source file:eu.seaclouds.policy.SeaCloudsManagementPolicy.java
private void removeGrafanaDashboard() { LOG.info("SeaCloudsInitializerPolicy is removing Grafana Dashboard for " + entity.getId()); HttpToolResponse response = delete(//from w w w.j av a 2 s.co m getConfig(GRAFANA_ENDPOINT) + "/api/dashboards/db/" + grafanaDashboardSlug, MediaType.JSON_UTF_8.toString(), getConfig(GRAFANA_USERNAME), getConfig(GRAFANA_PASSWORD)); if (!HttpTool.isStatusCodeHealthy(response.getResponseCode())) { throw new RuntimeException("Something went wrong while removing Grafana Dashboards. " + "Invalid response code, " + response.getResponseCode() + ":" + response.getContentAsString()); } }
From source file:org.glowroot.ui.CommonHandler.java
private CommonResponse handleNotAuthorized(CommonRequest request, Authentication authentication) throws Exception { if (authentication.anonymous()) { if (httpSessionManager.getSessionId(request) != null) { return new CommonResponse(UNAUTHORIZED, MediaType.JSON_UTF_8, "{\"timedOut\":true}"); } else {/*from w w w. ja va2 s .c om*/ return new CommonResponse(UNAUTHORIZED); } } else { return new CommonResponse(FORBIDDEN); } }
From source file:com.facebook.presto.server.HttpRemoteTask.java
private synchronized void scheduleUpdate() { // don't update if the task hasn't been started yet or if it is already finished if (!needsUpdate.get() || taskInfo.get().getState().isDone()) { return;/* w ww . ja v a 2 s .c o m*/ } // if we have an old request outstanding, cancel it if (currentRequest != null && Duration.nanosSince(currentRequestStartNanos).compareTo(requestTimeout) >= 0) { needsUpdate.set(true); currentRequest.cancel(true); currentRequest = null; currentRequestStartNanos = 0; } // if there is a request already running, wait for it to complete if (this.currentRequest != null && !this.currentRequest.isDone()) { return; } // if throttled due to error, asynchronously wait for timeout and try again ListenableFuture<?> errorRateLimit = updateErrorTracker.acquireRequestPermit(); if (!errorRateLimit.isDone()) { errorRateLimit.addListener(this::scheduleUpdate, executor); return; } List<TaskSource> sources = getSources(); TaskUpdateRequest updateRequest = new TaskUpdateRequest(session.toSessionRepresentation(), planFragment, sources, outputBuffers.get()); Request request = preparePost() .setUri(uriBuilderFrom(taskInfo.get().getSelf()).addParameter("summarize").build()) .setHeader(HttpHeaders.CONTENT_TYPE, MediaType.JSON_UTF_8.toString()) .setBodyGenerator(jsonBodyGenerator(taskUpdateRequestCodec, updateRequest)).build(); updateErrorTracker.startRequest(); ListenableFuture<JsonResponse<TaskInfo>> future = httpClient.executeAsync(request, createFullJsonResponseHandler(taskInfoCodec)); currentRequest = future; currentRequestStartNanos = System.nanoTime(); // The needsUpdate flag needs to be set to false BEFORE adding the Future callback since callback might change the flag value // and does so without grabbing the instance lock. needsUpdate.set(false); Futures.addCallback(future, new SimpleHttpResponseHandler<>(new UpdateResponseHandler(sources), request.getUri()), executor); }
From source file:eu.seaclouds.policy.SeaCloudsManagementPolicy.java
private void removeMonitoringRules() { LOG.info("SeaCloudsInitializerPolicy is removing T4C Monitoring Rules for " + entity.getId()); for (MonitoringRule rule : monitoringRules.getMonitoringRules()) { HttpToolResponse response = delete(getConfig(T4C_ENDPOINT) + "/v1/monitoring-rules/" + rule.getId(), MediaType.JSON_UTF_8.toString(), getConfig(T4C_USERNAME), getConfig(T4C_PASSWORD)); if (!HttpTool.isStatusCodeHealthy(response.getResponseCode())) { throw new RuntimeException( "Something went wrong while removing the Monitoring Rules. " + "Invalid response code, " + response.getResponseCode() + ":" + response.getContentAsString()); }/*from w ww . j av a 2 s . co m*/ } }
From source file:com.facebook.presto.server.remotetask.HttpRemoteTask.java
private synchronized void sendUpdate() { TaskStatus taskStatus = getTaskStatus(); // don't update if the task hasn't been started yet or if it is already finished if (!needsUpdate.get() || taskStatus.getState().isDone()) { return;//from www .j av a2s . c o m } // if we have an old request outstanding, cancel it if (currentRequest != null && Duration.nanosSince(currentRequestStartNanos).compareTo(requestTimeout) >= 0) { needsUpdate.set(true); currentRequest.cancel(true); currentRequest = null; currentRequestStartNanos = 0; } // if there is a request already running, wait for it to complete if (this.currentRequest != null && !this.currentRequest.isDone()) { return; } // if throttled due to error, asynchronously wait for timeout and try again ListenableFuture<?> errorRateLimit = updateErrorTracker.acquireRequestPermit(); if (!errorRateLimit.isDone()) { errorRateLimit.addListener(this::sendUpdate, executor); return; } List<TaskSource> sources = getSources(); Optional<PlanFragment> fragment = Optional.empty(); if (sendPlan.get()) { fragment = Optional.of(planFragment); } TaskUpdateRequest updateRequest = new TaskUpdateRequest(session.toSessionRepresentation(), fragment, sources, outputBuffers.get()); HttpUriBuilder uriBuilder = getHttpUriBuilder(taskStatus); Request request = preparePost().setUri(uriBuilder.build()) .setHeader(HttpHeaders.CONTENT_TYPE, MediaType.JSON_UTF_8.toString()) .setBodyGenerator(jsonBodyGenerator(taskUpdateRequestCodec, updateRequest)).build(); updateErrorTracker.startRequest(); ListenableFuture<JsonResponse<TaskInfo>> future = httpClient.executeAsync(request, createFullJsonResponseHandler(taskInfoCodec)); currentRequest = future; currentRequestStartNanos = System.nanoTime(); // The needsUpdate flag needs to be set to false BEFORE adding the Future callback since callback might change the flag value // and does so without grabbing the instance lock. needsUpdate.set(false); Futures.addCallback(future, new SimpleHttpResponseHandler<>(new UpdateResponseHandler(sources), request.getUri(), stats), executor); }
From source file:org.glowroot.ui.CommonHandler.java
private static CommonResponse buildJsonResponse(@Nullable Object responseObject) { if (responseObject == null) { return new CommonResponse(OK, MediaType.JSON_UTF_8, ""); } else if (responseObject instanceof CommonResponse) { return (CommonResponse) responseObject; } else if (responseObject instanceof String) { return new CommonResponse(OK, MediaType.JSON_UTF_8, (String) responseObject); } else {//ww w . ja v a 2 s . c om logger.warn("unexpected type of json service response: {}", responseObject.getClass().getName()); return new CommonResponse(INTERNAL_SERVER_ERROR); } }