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:org.ctoolkit.services.upload.appengine.DataUploadHandlerServlet.java
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if (!isMultipartContent(request)) { log.warn("Wrong content type: " + request.getContentType()); return;/*w ww . j a v a 2 s .c o m*/ } String gStorageName; String imageSize; String customName; String nameFieldMarker = "file"; //preferred method over getBlobInfos or getUploads because uploading files to Cloud Storage Map<String, List<FileInfo>> fileInfos = blobstoreService.getFileInfos(request); List<FileInfo> list = fileInfos.get(nameFieldMarker); if (list == null) { nameFieldMarker = UPLOAD_NAME_FIELD_MARKER; list = fileInfos.get(nameFieldMarker); } if (list == null) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); String message = "Incorrect upload form 'name' field, requested: " + UPLOAD_NAME_FIELD_MARKER; message = message + " " + String.valueOf(fileInfos); throw new IllegalArgumentException(message); } FileInfo info = list.get(0); gStorageName = info.getGsObjectName(); imageSize = request.getParameter(PARAMETER_IMAGE_SIZE); customName = request.getParameter(PARAMETER_CUSTOM_NAME); if (log.isInfoEnabled()) { log.info("Image size: " + imageSize); log.info("Custom name: " + customName); log.info(String.valueOf(info)); } try { if (!Strings.isNullOrEmpty(gStorageName)) { int size = -1; if (!Strings.isNullOrEmpty(imageSize)) { try { size = Integer.parseInt(imageSize); } catch (NumberFormatException e) { log.warn("Parsing of the image size has failed: " + imageSize); } } String servingUrl = null; if (isAnyImageContentType(info)) { ServingUrlOptions options; options = ServingUrlOptions.Builder.withGoogleStorageFileName(gStorageName); options = options.crop(false).secureUrl(true); if (size > 0) { options = options.imageSize(size); } servingUrl = imageService.getServingUrl(options); } GsonBuilder builder = new GsonBuilder(); Gson gson = builder.create(); JsonObject jsonEntry = new JsonObject(); jsonEntry.addProperty("storageName", gStorageName); if (!Strings.isNullOrEmpty(servingUrl)) { jsonEntry.addProperty("servingUrl", servingUrl); } if (!Strings.isNullOrEmpty(customName)) { jsonEntry.addProperty("customName", customName); } // blob key retrieval Map<String, List<BlobKey>> blobs = blobstoreService.getUploads(request); BlobKey blobKey = blobs.get(nameFieldMarker).get(0); if (blobKey == null) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); String message = "Blob key is null for fileInfos: " + String.valueOf(fileInfos); throw new IllegalArgumentException(message); } jsonEntry.addProperty("blobKey", blobKey.getKeyString()); // return blob key and serving URL as JSON gson.toJson(jsonEntry, response.getWriter()); // notify for (DataUploadListener listener : listeners) { try { listener.onDataUpload(gStorageName, blobKey, size, servingUrl, customName, info.getContentType(), info.getFilename(), info.getSize(), info.getMd5Hash()); } catch (Exception e) { log.warn("Calling of the listeners has failed, ignoring ..", e); } } MediaType jsonUtf8 = MediaType.JSON_UTF_8; response.setStatus(HttpServletResponse.SC_CREATED); response.setCharacterEncoding(jsonUtf8.charset().get().name()); response.setContentType(jsonUtf8.toString()); } else { log.warn("No key has found!"); response.setStatus(HttpServletResponse.SC_NOT_FOUND); } } catch (Exception e) { log.error("An error has occurred during uploading of the data: " + gStorageName, e); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } }
From source file:com.citytechinc.cq.clientlibs.core.servlets.SearchServlet.java
/** * GET request handler. Takes the following parameters: * * libraries.include = set to true to have response include libraries. * libraries.path = an absolute path to a library to return. * components.include = set to true to have response include components. * components.resourceType = set this to a resource type to search for only that particular component. * limit.category = limits the libraries and components returned to only those in a given category. This * may produce confusing results if used in conjunction with library or category * specific restrictions. * * All parameters are optional. If no parameters are provided, nothing will be returned. * * @param request/*from w w w . j a v a2 s. c om*/ * @param response * @throws ServletException * @throws IOException */ @Override protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException { // figure out what response wants boolean includeLibraries = Boolean.valueOf(request.getParameter(REQ_PARAM_LIBRARY_INCLUDE)); boolean includeComponents = Boolean.valueOf(request.getParameter(REQ_PARAM_COMPONENTS_INCLUDE)); // category provided? String paramCategory = request.getParameter(REQ_PARAM_LIMIT_CATEGORY); boolean categoryGiven = StringUtils.isNotBlank(paramCategory); // set up response stuff JSONObject jsonResponse = new JSONObject(); int statusCode = 400; // initialize json collections for response JSONArray jsonStatusMessages = new JSONArray(); JSONObject jsonLibraries = new JSONObject(); JSONObject jsonComponents = new JSONObject(); // libraries should be included if (includeLibraries) { // libraries should be included, get necessary stuff out of request String paramLibraryPath = request.getParameter(REQ_PARAM_LIBRARY_PATH); boolean libraryPathGiven = StringUtils.isNotBlank(paramLibraryPath); // no specific library given, return collection of libraries Collection<ClientLibrary> libraries = categoryGiven ? clientLibraryManager.getLibrariesForCategory(paramCategory) : clientLibraryManager.getLibraries(); // loop through libraries and write them out to JSON objects for (ClientLibrary library : libraries) { // if path was given check to make sure it matches, otherwise, just add library if (!libraryPathGiven || StringUtils.equals(paramLibraryPath, library.getClientLibraryPath())) { try { jsonLibraries.put(library.getClientLibraryPath(), DomainToJSONUtil.buildJsonLibrary(library)); if (libraryPathGiven) { // library path was given, therefore to be here a match happened, break out of loop break; } } catch (JSONException e) { // problem occurred writing out JSON, log and return an error message String errMsg = "Could not write out library at " + library.getClientLibraryPath() + "."; LOGGER.error(errMsg, e); jsonStatusMessages.put(errMsg); } } } } // check if components should be included if (includeComponents) { // get necessary stuff out of request String paramResourceType = request.getParameter(REQ_PARAM_COMPONENT_RESOURCE_TYPE); boolean resourceTypeGiven = StringUtils.isNotBlank(paramResourceType); // figure out where the collection of components is coming from Collection<DependentComponent> components = categoryGiven ? dependentComponentManager.getComponentsDependentOnLibraryCategory(paramCategory) : dependentComponentManager.getComponentsByPath().values(); // loop through component collection and write them out to JSON objects for (DependentComponent component : components) { try { // check resource type if it was given as a parameter, add component JSON to response collection if (!resourceTypeGiven || StringUtils.equals(paramResourceType, component.getResourceType())) { jsonComponents.put(component.getComponent().getPath(), DomainToJSONUtil.buildJsonComponent(component)); } } catch (JSONException e) { // problem occurred writing out JSON, log and return an error message String errMsg = "Could not write out component at " + component.getComponent().getPath() + "."; LOGGER.error(errMsg, e); jsonStatusMessages.put(errMsg); } } } try { // add objects to response JSON jsonResponse.put(ServletConstants.RESP_KEY_STATUS, jsonStatusMessages.length() > 0 ? jsonStatusMessages : ServletConstants.STATUS_SUCCESS); jsonResponse.put(RESP_KEY_LIBRARIES, jsonLibraries); jsonResponse.put(RESP_KEY_COMPONENTS, jsonComponents); } catch (JSONException e) { // could not write out JSON for some reason, error out with a 500 LOGGER.error("An error occurred.", e); statusCode = 500; } // write response response.setStatus(statusCode); response.setContentType(MediaType.JSON_UTF_8.toString()); response.getWriter().write(jsonResponse.toString()); }
From source file:org.glowroot.ui.CommonHandler.java
private @Nullable CommonResponse handleIfLoginOrLogoutRequest(CommonRequest request) throws Exception { String path = request.getPath(); if (path.equals("/backend/login")) { String content = request.getContent(); Credentials credentials = mapper.readValue(content, ImmutableCredentials.class); Glowroot.setTransactionUser(credentials.username()); return httpSessionManager.login(credentials.username(), credentials.password()); }// ww w. j ava 2 s . c o m if (path.equals("/backend/sign-out")) { httpSessionManager.signOut(request); Authentication authentication = httpSessionManager.getAnonymousAuthentication(); Glowroot.setTransactionUser(authentication.caseAmbiguousUsername()); String anonymousLayout = layoutService.getLayoutJson(authentication); CommonResponse response = new CommonResponse(OK, MediaType.JSON_UTF_8, anonymousLayout); httpSessionManager.deleteSessionCookie(response); return response; } if (path.equals("/backend/check-layout")) { Authentication authentication = httpSessionManager.getAuthentication(request, false); CommonResponse response = new CommonResponse(OK); response.setHeader("Glowroot-Layout-Version", layoutService.getLayoutVersion(authentication)); List<String> agentRollupIds = request.getParameters("agent-rollup-id"); if (agentRollupIds != null && agentRollupIds.size() == 1) { String agentRollupLayoutVersion = layoutService.getAgentRollupLayoutVersion(authentication, agentRollupIds.get(0)); if (agentRollupLayoutVersion != null) { response.setHeader("Glowroot-Agent-Rollup-Layout-Version", agentRollupLayoutVersion); } } return response; } if (path.equals("/backend/layout")) { Authentication authentication = httpSessionManager.getAuthentication(request, false); return new CommonResponse(OK, MediaType.JSON_UTF_8, layoutService.getLayoutJson(authentication)); } if (path.equals("/backend/agent-rollup-layout")) { Authentication authentication = httpSessionManager.getAuthentication(request, false); String agentRollupId = request.getParameters("agent-rollup-id").get(0); return new CommonResponse(OK, MediaType.JSON_UTF_8, layoutService.getAgentRollupLayoutJson(agentRollupId, authentication)); } return null; }
From source file:org.glowroot.ui.HttpSessionManager.java
private static CommonResponse buildIncorrectLoginResponse() { return new CommonResponse(OK, MediaType.JSON_UTF_8, "{\"incorrectLogin\":true}"); }
From source file:com.citytechinc.cq.clientlibs.core.servlets.GraphServlet.java
@Override protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException { // get request parameters String paramPagePath = request.getParameter(REQ_PARAM_PAGE_PATH); // set up response stuff JSONObject jsonResponse = new JSONObject(); int statusCode = 400; // initialize json collections for response JSONArray jsonStatusMessages = new JSONArray(); JSONArray jsonNodes = new JSONArray(); JSONArray jsonEdges = new JSONArray(); // resolve given path ResourceResolver resourceResolver = request.getResourceResolver(); Resource pageResource = resourceResolver.resolve(paramPagePath); // check if path resolved if (StringUtils.isNotBlank(paramPagePath) && !ResourceUtil.isNonExistingResource(pageResource)) { // get content node Resource jcrContentResource = pageResource.getChild(JcrConstants.JCR_CONTENT); // keep track of categories Set<String> categories = new HashSet<String>(); try {//from w w w .j a va 2 s . c om // write components to JSON for (String resourceType : ComponentUtils.getNestedComponentTypes(jcrContentResource)) { // get dependent component DependentComponent dependentComponent = dependentComponentManager .getDependentComponentForResourceType(resourceType).orNull(); if (dependentComponent != null) { // found dependent component, write it to JSON jsonNodes.put(DomainToJSONUtil.buildJsonComponent(dependentComponent)); // add all dependencies to categories list, add edges from component to categories String componentResourceType = dependentComponent.getResourceType(); Set<String> dependencies = dependentComponent.getDependencies(); for (String dependency : dependencies) { JSONObject jsonEdge = DomainToJSONUtil.buildJsonEdge(componentResourceType, dependency, EdgeType.DEPENDS_ON); jsonEdges.put(jsonEdge); } categories.addAll(dependencies); } else { // this is not a dependent component (probably OOTB), write it to JSON with what info it has jsonNodes.put(DomainToJSONUtil.buildJsonBareComponent(resourceType)); } } // get graph DependencyGraph<ClientLibrary> dependencyGraph = clientLibraryRepository .getClientLibraryDependencyGraph(jcrContentResource); // write client libraries to JSON for (ClientLibrary clientLibrary : dependencyGraph.getNodes()) { jsonNodes.put(DomainToJSONUtil.buildJsonLibrary(clientLibrary)); String clientLibraryPath = clientLibrary.getClientLibraryPath(); // add all categories to categories list, add edges from categories to this library Set<String> memberOfCategories = clientLibrary.getCategories(); for (String category : memberOfCategories) { JSONObject jsonEdge = DomainToJSONUtil.buildJsonEdge(clientLibraryPath, category, EdgeType.MEMBER_OF); jsonEdges.put(jsonEdge); } categories.addAll(memberOfCategories); // add all dependencies to categories list, add edges from categories to libraries List<String> dependencies = clientLibrary.getDependencies(); for (String dependency : dependencies) { JSONObject jsonEdge = DomainToJSONUtil.buildJsonEdge(clientLibraryPath, dependency, EdgeType.DEPENDS_ON); jsonEdges.put(jsonEdge); } categories.addAll(dependencies); // add all embeds to categories list, add edges from embeds to categories List<String> embeds = clientLibrary.getEmbeddedCategories(); for (String embed : embeds) { JSONObject jsonEdge = DomainToJSONUtil.buildJsonEdge(clientLibraryPath, embed, EdgeType.EMBEDS); jsonEdges.put(jsonEdge); } categories.addAll(embeds); } // write categories to JSON for (String category : categories) { jsonNodes.put(DomainToJSONUtil.buildJsonCategory(category)); } } catch (JSONException e) { // JSON error LOGGER.error("Failed to build JSON. Returning 500.", e); jsonStatusMessages.put("Failed to build JSON."); statusCode = 500; } } else { // requested a non-existing resource, return a bad request LOGGER.error("Requested dependency graph for non-existing resource at '" + pageResource + "'. Returning 400."); jsonStatusMessages.put("No resource exists at '" + pageResource + "'."); statusCode = 400; } try { // add objects to response JSON jsonResponse.put(ServletConstants.RESP_KEY_STATUS, jsonStatusMessages.length() > 0 ? jsonStatusMessages : ServletConstants.STATUS_SUCCESS); if (statusCode != 500) { // haven't already failed, write out objects jsonResponse.put(RESP_KEY_NODES, jsonNodes); jsonResponse.put(RESP_KEY_EDGES, jsonEdges); // set status to OK statusCode = 200; } } catch (JSONException e) { // could not write out JSON for some reason, error out with a 500 LOGGER.error("An error occurred.", e); statusCode = 500; } // write response response.setStatus(statusCode); response.setContentType(MediaType.JSON_UTF_8.toString()); response.getWriter().write(jsonResponse.toString()); }
From source file:controllers.api.SystemApiController.java
public Result internalLogsOfNode(String nodeId) { try {/*w ww. j a v a 2s .c o m*/ Map<String, Object> result = Maps.newHashMap(); Node node = nodeService.loadNode(nodeId); Meter meter = (Meter) node.getSingleMetric("org.apache.log4j.Appender.all"); result.put("total", meter.getTotal()); return ok(Json.toJsonString(result)).as(MediaType.JSON_UTF_8.toString()); } catch (NodeService.NodeNotFoundException e) { return status(404, "node not found"); } catch (IOException e) { return internalServerError("io exception"); } catch (APIException e) { return internalServerError("api exception " + e); } }
From source file:controllers.api.SearchApiController.java
public Result histogram(String q, String rangeType, int relative, String from, String to, String keyword, String interval, String streamId, int maxDataPoints) { if (q == null || q.isEmpty()) { q = "*";//from w w w. j ava 2 s. c o m } // Interval. if (interval == null || interval.isEmpty() || !SearchTools.isAllowedDateHistogramInterval(interval)) { interval = "minute"; } // Determine timerange type. TimeRange timerange; try { timerange = TimeRange.factory(rangeType, relative, from, to, keyword); } catch (InvalidRangeParametersException e2) { return status(400, views.html.errors.error.render("Invalid range parameters provided.", e2, request())); } catch (IllegalArgumentException e1) { return status(400, views.html.errors.error.render("Invalid range type provided.", e1, request())); } String filter = null; if (streamId != null && !streamId.isEmpty()) { filter = "streams:" + streamId; } try { UniversalSearch search = searchFactory.queryWithRangeAndFilter(q, timerange, filter); DateHistogramResult histogram = search.dateHistogram(interval); List<Map<String, Long>> results = formatHistogramResults(histogram, maxDataPoints, relative == 0); Map<String, Object> result = Maps.newHashMap(); AbsoluteRange boundaries = histogram.getHistogramBoundaries(); result.put("time", histogram.getTookMs()); result.put("interval", histogram.getInterval()); result.put("values", results); result.put("from", boundaries.getFrom()); result.put("to", boundaries.getTo()); return ok(Json.toJsonString(result)).as(MediaType.JSON_UTF_8.toString()); } catch (IOException e) { return internalServerError("io exception"); } catch (APIException e) { if (e.getHttpCode() == 400) { // This usually means the field does not have a numeric type. Pass through! return badRequest(); } return internalServerError("api exception " + e); } }
From source file:controllers.api.DashboardsApiController.java
public Result widget(String dashboardId, String widgetId) { try {/*from w ww . ja v a 2 s . co m*/ Dashboard dashboard = dashboardService.get(dashboardId); DashboardWidget widget = dashboard.getWidget(widgetId); if (widget == null) { return notFound(); } Map<String, Object> result = Maps.newHashMap(); result.put("type", widget.getType()); result.put("id", widget.getId()); result.put("dashboard_id", widget.getDashboard().getId()); result.put("description", widget.getDescription()); result.put("cache_time", widget.getCacheTime()); result.put("creator_user_id", widget.getCreatorUserId()); result.put("config", widget.getConfig()); return ok(Json.toJsonString(result)).as(MediaType.JSON_UTF_8.toString()); } catch (APIException e) { String message = "Could not get dashboard. We expected HTTP 200, but got a HTTP " + e.getHttpCode() + "."; return status(504, views.html.errors.error.render(message, e, request())); } catch (IOException e) { return status(504, views.html.errors.error.render(ApiClient.ERROR_MSG_IO, e, request())); } }
From source file:com.cyngn.vertx.bosun.BosunReporter.java
/** * Send data to the bosun instance// w ww . j a v a2s . c o m * * @param api the api on bosun to send to * @param data the json data to send * @param message the event bus message the request originated from */ private void sendData(String api, String data, Message message) { HttpClient client = getNextHost(); Buffer buffer = Buffer.buffer(data.getBytes()); client.post(api).exceptionHandler(error -> { sendError(message, "Got ex contacting bosun, " + error.getLocalizedMessage()); }).handler(response -> { int statusCode = response.statusCode(); // is it 2XX if (statusCode >= HttpResponseStatus.OK.code() && statusCode < HttpResponseStatus.MULTIPLE_CHOICES.code()) { message.reply(new JsonObject().put(RESULT_FIELD, BosunResponse.OK_MSG)); } else { response.bodyHandler(responseData -> { sendError(message, "got non 200 response from bosun, error: " + responseData, statusCode); }); } }).setTimeout(timeout).putHeader(HttpHeaders.CONTENT_LENGTH, buffer.length() + "") .putHeader(HttpHeaders.CONTENT_TYPE, MediaType.JSON_UTF_8.toString()).write(buffer).end(); }
From source file:controllers.api.SystemApiController.java
public Result internalLogMetricsOfNode(String nodeId) { try {//ww w . java2s. c om Map<String, Object> result = Maps.newHashMap(); Node node = nodeService.loadNode(nodeId); String[] levels = new String[] { "org.apache.log4j.Appender.debug", "org.apache.log4j.Appender.error", "org.apache.log4j.Appender.fatal", "org.apache.log4j.Appender.info", "org.apache.log4j.Appender.trace", "org.apache.log4j.Appender.warn" }; for (String level : levels) { String shortName = level.substring(level.lastIndexOf(".") + 1); Map<String, Object> meterMap = Maps.newHashMap(); Meter meter = (Meter) node.getSingleMetric(level); meterMap.put("total", meter.getTotal()); meterMap.put("mean_rate", meter.getMeanFormatted()); meterMap.put("one_min_rate", meter.getOneMinuteFormatted()); result.put(shortName, meterMap); } return ok(Json.toJsonString(result)).as(MediaType.JSON_UTF_8.toString()); } catch (NodeService.NodeNotFoundException e) { return status(404, "node not found"); } catch (IOException e) { return internalServerError("io exception"); } catch (APIException e) { return internalServerError("api exception " + e); } }