Example usage for com.google.common.net MediaType JSON_UTF_8

List of usage examples for com.google.common.net MediaType JSON_UTF_8

Introduction

In this page you can find the example usage for com.google.common.net MediaType JSON_UTF_8.

Prototype

MediaType JSON_UTF_8

To view the source code for com.google.common.net MediaType JSON_UTF_8.

Click Source Link

Usage

From source file:org.openqa.selenium.grid.server.BaseServer.java

public BaseServer(BaseServerOptions options) {
    int port = options.getPort() == 0 ? PortProber.findFreePort() : options.getPort();

    String host = options.getHostname().orElseGet(() -> {
        try {/* www .j  av a 2s .co  m*/
            return new NetworkUtils().getNonLoopbackAddressOfThisMachine();
        } catch (WebDriverException ignored) {
            return "localhost";
        }
    });

    try {
        this.url = new URL("http", host, port, "");
    } catch (MalformedURLException e) {
        throw new UncheckedIOException(e);
    }

    Log.setLog(new JavaUtilLog());
    this.server = new org.seleniumhq.jetty9.server.Server(new QueuedThreadPool(options.getMaxServerThreads()));

    // Insertion order may matter
    this.handlers = new LinkedHashMap<>();

    Json json = new Json();
    this.injector = Injector.builder().register(json).build();

    addRoute(Routes.get("/status").using((in, out) -> {
        String value = json.toJson(ImmutableMap.of("value",
                ImmutableMap.of("ready", false, "message", "Stub server without handlers")));

        out.setHeader("Content-Type", MediaType.JSON_UTF_8.toString());
        out.setHeader("Cache-Control", "none");
        out.setStatus(HTTP_OK);

        out.setContent(value.getBytes(UTF_8));
    }).build());

    this.servletContextHandler = new ServletContextHandler(ServletContextHandler.SECURITY);
    ConstraintSecurityHandler securityHandler = (ConstraintSecurityHandler) servletContextHandler
            .getSecurityHandler();

    Constraint disableTrace = new Constraint();
    disableTrace.setName("Disable TRACE");
    disableTrace.setAuthenticate(true);
    ConstraintMapping disableTraceMapping = new ConstraintMapping();
    disableTraceMapping.setConstraint(disableTrace);
    disableTraceMapping.setMethod("TRACE");
    disableTraceMapping.setPathSpec("/");
    securityHandler.addConstraintMapping(disableTraceMapping);

    Constraint enableOther = new Constraint();
    enableOther.setName("Enable everything but TRACE");
    ConstraintMapping enableOtherMapping = new ConstraintMapping();
    enableOtherMapping.setConstraint(enableOther);
    enableOtherMapping.setMethodOmissions(new String[] { "TRACE" });
    enableOtherMapping.setPathSpec("/");
    securityHandler.addConstraintMapping(enableOtherMapping);

    server.setHandler(servletContextHandler);

    HttpConfiguration httpConfig = new HttpConfiguration();
    httpConfig.setSecureScheme("https");

    ServerConnector http = new ServerConnector(server, new HttpConnectionFactory(httpConfig));
    options.getHostname().ifPresent(http::setHost);
    http.setPort(getUrl().getPort());

    http.setIdleTimeout(500000);

    server.setConnectors(new Connector[] { http });
}

From source file:controllers.api.ToolsApiController.java

public Result naturalDateTest(String string) {
    if (string.isEmpty()) {
        return badRequest();
    }//ww w.  j av  a2 s  .com

    try {
        return ok(Json.toJsonString(naturalDateTest.test(string))).as(MediaType.JSON_UTF_8.toString());
    } catch (IOException e) {
        return internalServerError("io exception");
    } catch (APIException e) {
        if (e.getHttpCode() == 422) {
            return status(422);
        }
        return internalServerError("api exception " + e);
    }
}

From source file:controllers.api.DashboardsApiController.java

public Result index() {
    try {//from www  .  j  a  v  a  2 s .c  o  m
        Map<String, Object> result = Maps.newHashMap();
        for (Dashboard d : dashboardService.getAll()) {
            Map<String, String> dashboard = Maps.newHashMap();

            dashboard.put("title", d.getTitle());
            dashboard.put("description", d.getDescription());
            dashboard.put("created_by", (d.getCreatorUser() == null) ? null : d.getCreatorUser().getName());
            dashboard.put("content_pack", d.getContentPack());

            result.put(d.getId(), dashboard);
        }

        return ok(Json.toJsonString(result)).as(MediaType.JSON_UTF_8.toString());
    } catch (APIException e) {
        String message = "Could not get dashboards. 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:controllers.BundlesController.java

public Result export() {
    final Form<ExportBundleRequest> form = Tools.bindMultiValueFormFromRequest(ExportBundleRequest.class);

    if (form.hasErrors()) {
        BreadcrumbList bc = new BreadcrumbList();
        bc.addCrumb("System", routes.SystemController.index(0));
        bc.addCrumb("Content packs", routes.BundlesController.index());
        bc.addCrumb("Create", routes.BundlesController.exportForm());

        Map<String, List> data = getListData();

        flash("error", "Please correct the fields marked in red to export the bundle");
        return badRequest(views.html.system.bundles.export.render(form, currentUser(), bc,
                (List<Input>) data.get("inputs"), (List<Output>) data.get("outputs"),
                (List<Stream>) data.get("streams"), (List<Dashboard>) data.get("dashboards"),
                (List<GrokPatternSummary>) data.get("grok-patterns")));
    }//w  ww .  ja  v a2 s  .  c om

    try {
        final ExportBundleRequest exportBundleRequest = form.get();
        ConfigurationBundle bundle = bundleService.export(exportBundleRequest);

        response().setContentType(MediaType.JSON_UTF_8.toString());
        response().setHeader("Content-Disposition", "attachment; filename=content_pack.json");
        ObjectMapper m = new ObjectMapper();
        ObjectWriter ow = m.writer().withDefaultPrettyPrinter();
        return ok(ow.writeValueAsString(bundle));
    } catch (IOException e) {
        flash("error", "Could not reach Graylog server");
    } catch (Exception e) {
        flash("error", "Unexpected error exporting configuration bundle, please try again later");
    }

    return redirect(routes.BundlesController.exportForm());
}

From source file:controllers.api.InputsApiController.java

public Result globaIO(String inputId) {
    Map<String, Object> result = Maps.newHashMap();

    final Input globalInput;
    try {//ww w.  java 2 s  .com
        globalInput = nodeService.loadMasterNode().getInput(inputId);
        if (!globalInput.getGlobal()) {
            return badRequest();
        }
    } catch (IOException e) {
        log.error("Could not load input.");
        return internalServerError();
    } catch (APIException e) {
        log.error("Could not load input.");
        return internalServerError();
    }

    final Input.IoStats ioStats = clusterService.getGlobalInputIo(globalInput);

    result.put("total_rx", Tools.byteToHuman(ioStats.readBytesTotal));
    result.put("total_tx", Tools.byteToHuman(ioStats.writtenBytesTotal));
    result.put("rx", Tools.byteToHuman(ioStats.readBytes));
    result.put("tx", Tools.byteToHuman(ioStats.writtenBytes));

    return ok(Json.toJsonString(result)).as(MediaType.JSON_UTF_8.toString());
}

From source file:controllers.api.SystemApiController.java

public Result totalThroughput() {
    Map<String, Object> result = Maps.newHashMap();
    final F.Tuple<Integer, Integer> throughputPerNodes = clusterService.getClusterThroughput();
    result.put("throughput", throughputPerNodes._1);
    result.put("nodecount", throughputPerNodes._2);

    return ok(Json.toJsonString(result)).as(MediaType.JSON_UTF_8.toString());
}

From source file:com.mastfrog.acteur.ClasspathResourcePage.java

protected MediaType getContentType(Path path) {
    MediaType type = responseHeaders.getContentType();
    if (type != null) {
        return type;
    }//from   ww  w . jav a2  s  .  co  m
    String pth = path.toString();
    if (pth.endsWith("svg")) {
        return MediaType.SVG_UTF_8;
    } else if (pth.endsWith("css")) {
        return MediaType.CSS_UTF_8;
    } else if (pth.endsWith("html")) {
        return MediaType.HTML_UTF_8;
    } else if (pth.endsWith("json")) {
        return MediaType.JSON_UTF_8;
    } else if (pth.endsWith("js")) {
        return MediaType.JAVASCRIPT_UTF_8;
    } else if (pth.endsWith("gif")) {
        return MediaType.GIF;
    } else if (pth.endsWith("jpg")) {
        return MediaType.JPEG;
    } else if (pth.endsWith("png")) {
        return MediaType.PNG;
    }
    return null;
}

From source file:controllers.api.ToolsApiController.java

public Result grokTest() {
    final JsonNode json = request().body().asJson();
    final GrokTestRequest request = Json.fromJson(json, GrokTestRequest.class);

    if (request.pattern().isEmpty() || request.string().isEmpty()) {
        return badRequest();
    }/*from ww w  .jav a  2  s.c  o  m*/

    try {
        return ok(Json.toJsonString(grokTest.test(request))).as(MediaType.JSON_UTF_8.toString());
    } catch (IOException e) {
        return internalServerError("io exception");
    } catch (APIException e) {
        if (e.getHttpCode() == 422) {
            return status(422);
        }
        return internalServerError("api exception " + e);
    }
}

From source file:controllers.api.SystemApiController.java

public Result nodeThroughput(String nodeId) {
    try {//  ww w .  j  a  v a2  s. c  o m
        Map<String, Object> result = Maps.newHashMap();
        final Node node = nodeService.loadNode(nodeId);
        result.put("throughput", node.getThroughput());

        return ok(Json.toJsonString(result)).as(MediaType.JSON_UTF_8.toString());
    } catch (NodeService.NodeNotFoundException e) {
        return status(404, "node not found");
    }
}

From source file:com.mockey.ui.JsonSchemaValidateServlet.java

@Override
public void doPost(final HttpServletRequest req, final HttpServletResponse resp)
        throws ServletException, IOException {
    final Set<String> params = Sets.newHashSet();
    final Enumeration<String> enumeration = req.getParameterNames();

    // FIXME: no duplicates, it seems, but I cannot find the spec which
    // guarantees that
    while (enumeration.hasMoreElements())
        params.add(enumeration.nextElement());

    // We have required parameters
    if (!params.containsAll(ValidateRequest.REQUIRED_PARAMS)) {
        logger.warn("Missing parameters! Someone using me as a web service?");
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Missing parameters");
        return;//  w ww  .j av a  2 s.  c om
    }

    // We don't want extraneous parameters
    params.removeAll(ValidateRequest.VALID_PARAMS);

    if (!params.isEmpty()) {
        logger.warn("Invalid parameters! Someone using me as a web service?");
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid parameters");
        return;
    }

    final String rawSchema = req.getParameter(ValidateRequest.SCHEMA);
    final String data = req.getParameter(ValidateRequest.DATA);

    // Set correct content type
    resp.setContentType(MediaType.JSON_UTF_8.toString());

    final boolean useV3 = Boolean.parseBoolean(req.getParameter(ValidateRequest.USE_V3));
    final boolean useId = Boolean.parseBoolean(req.getParameter(ValidateRequest.USE_ID));

    final JsonNode ret = JsonSchemaUtil.buildResult(rawSchema, data, useV3, useId);

    final OutputStream out = resp.getOutputStream();

    try {
        out.write(ret.toString().getBytes(Charset.forName("UTF-8")));
        out.flush();
    } finally {
        Closeables.closeQuietly(out);
    }
}