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:controllers.api.SystemApiController.java

public Result jobs() {
    try {/*from   w w w .j a v a 2s . c o  m*/
        List<Map<String, Object>> jobs = Lists.newArrayList();
        for (SystemJob j : clusterService.allSystemJobs()) {
            Map<String, Object> job = Maps.newHashMap();

            job.put("id", j.getId());
            job.put("percent_complete", j.getPercentComplete());

            jobs.add(job);
        }

        Map<String, Object> result = Maps.newHashMap();
        result.put("jobs", jobs);

        return ok(Json.toJsonString(result)).as(MediaType.JSON_UTF_8.toString());
    } catch (IOException e) {
        return internalServerError("io exception");
    } catch (APIException e) {
        return internalServerError("api exception " + e);
    }
}

From source file:controllers.api.InputsApiController.java

public Result io(String nodeId, String inputId) {
    try {//from w ww . j a  v  a 2  s .c  o m
        Map<String, Object> result = Maps.newHashMap();

        final Node node = nodeService.loadNode(nodeId);
        final Input input = node.getInput(inputId);
        final Input.IoStats ioStats = input.getIoStats();

        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());
    } catch (IOException e) {
        return internalServerError("io exception");
    } catch (APIException e) {
        return internalServerError("api exception " + e);
    } catch (NodeService.NodeNotFoundException e) {
        return status(404, views.html.errors.error.render(ApiClient.ERROR_MSG_NODE_NOT_FOUND, e, request()));
    }
}

From source file:google.registry.flows.CheckApiAction.java

@Override
public void run() {
    response.setHeader("Content-Disposition", "attachment");
    response.setHeader("X-Content-Type-Options", "nosniff");
    response.setHeader(ACCESS_CONTROL_ALLOW_ORIGIN, "*");
    response.setContentType(MediaType.JSON_UTF_8);
    response.setPayload(toJSONString(doCheck()));
}

From source file:org.haiku.haikudepotserver.pkg.job.PkgDumpExportJobRunner.java

@Override
public void run(JobService jobService, PkgDumpExportJobSpecification specification)
        throws IOException, JobRunnerException {

    // this will register the outbound data against the job.
    JobDataWithByteSink jobDataWithByteSink = jobService.storeGeneratedData(specification.getGuid(), "download",
            MediaType.JSON_UTF_8.toString());

    try (final OutputStream outputStream = jobDataWithByteSink.getByteSink().openBufferedStream();
            final GZIPOutputStream gzipOutputStream = new GZIPOutputStream(outputStream);
            final JsonGenerator jsonGenerator = objectMapper.getFactory().createGenerator(gzipOutputStream)) {
        jsonGenerator.writeStartObject();
        writeInfo(jsonGenerator, specification);
        writePkgs(jsonGenerator, specification);
        jsonGenerator.writeEndObject();//  w  w  w. ja v a2 s  .  c  o  m
    }
}

From source file:com.google.caliper.runner.resultprocessor.ResultsUploader.java

@Override
public final void processTrial(Trial trial) {
    if (uploadUri.isPresent()) {
        boolean succeeded = false;
        try {/*  w w  w .  ja v  a  2s.  c o  m*/
            String json = gson.toJson(ImmutableList.of(trial));
            succeeded = handler.upload(uploadUri.get(), json, MediaType.JSON_UTF_8.toString(), apiKey, trial);
        } finally {
            failure |= !succeeded;
        }

        if (succeeded) {
            // only set the run id if a result has been successfully uploaded
            runId = Optional.of(trial.run().id());
        }
    }
}

From source file:controllers.api.SystemApiController.java

public Result notifications() {
    try {/*from   w  w w. ja  v  a 2s  . co m*/
        /*Map<String, Object> result = Maps.newHashMap();
        result.put("count", clusterService.allNotifications().size());*/
        List<Notification> notifications = clusterService.allNotifications();

        return ok(Json.toJsonString(notifications)).as(MediaType.JSON_UTF_8.toString());
    } catch (IOException e) {
        return internalServerError("io exception");
    } catch (APIException e) {
        return internalServerError("api exception " + e);
    }
}

From source file:com.github.fge.jsonschema.servlets.SyntaxValidateServlet.java

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

    /*//from  www .j a v  a 2s.c o  m
     * First, check our parameters
     */
    /*
     * Why, in 2013, doesn't servlet-api provide an Iterator<String>?
     *
     * Well, at least, Jetty's implementation has a generified Enumeration.
     * Still, that sucks.
     */
    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(Request.required())) {
        log.warn("Missing parameters! Someone using me as a web service?");
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Missing parameters");
        return;
    }

    // We don't want extraneous parameters
    params.removeAll(Request.valid());

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

    final String rawSchema = req.getParameter(Request.SCHEMA);

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

    final JsonNode ret;
    try {
        ret = buildResult(rawSchema);
    } catch (ProcessingException e) {
        // Should not happen!
        log.error("Uh, syntax validation failed!", e);
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return;
    }

    final OutputStream out = resp.getOutputStream();

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

From source file:controllers.api.ToolsApiController.java

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

    try {//from w  ww .java 2  s  . com
        if (request.splitBy().isEmpty() || request.index() < 0 || request.string().isEmpty()) {
            return badRequest();
        }

        return ok(Json.toJsonString(splitAndIndexTest.test(request))).as(MediaType.JSON_UTF_8.toString());
    } catch (IOException e) {
        return internalServerError("io exception");
    } catch (APIException e) {
        return internalServerError("api exception " + e);
    }
}

From source file:controllers.api.SearchApiController.java

public Result fieldStats(String q, String field, String rangeType, int relative, String from, String to,
        String keyword, String streamId) {
    if (q == null || q.isEmpty()) {
        q = "*";//from w  w  w. j a  va2 s.c o m
    }

    // 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);
        FieldStatsResponse stats = search.fieldStats(field);

        Map<String, Object> result = Maps.newHashMap();
        result.put("count", stats.count < 0 ? "N/A" : stats.count);
        result.put("sum", stats.sum);
        result.put("mean", stats.mean);
        result.put("min", stats.min);
        result.put("max", stats.max);
        result.put("variance", stats.variance);
        result.put("sum_of_squares", stats.sumOfSquares);
        result.put("std_deviation", stats.stdDeviation);
        result.put("cardinality", stats.cardinality < 0 ? "N/A" : stats.cardinality);

        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:com.twitter.common.net.http.handlers.TimeSeriesDataSource.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    resp.setContentType(MediaType.JSON_UTF_8.toString());
    PrintWriter out = resp.getWriter();
    try {//from   www. j  a  v  a  2 s .  co m
        out.write(getResponse(req.getParameter(METRICS), req.getParameter(SINCE)));
    } catch (MetricException e) {
        resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        out.write(e.getMessage());
    }
}