Example usage for com.fasterxml.jackson.databind ObjectWriter writeValue

List of usage examples for com.fasterxml.jackson.databind ObjectWriter writeValue

Introduction

In this page you can find the example usage for com.fasterxml.jackson.databind ObjectWriter writeValue.

Prototype

public void writeValue(Writer w, Object value)
        throws IOException, JsonGenerationException, JsonMappingException 

Source Link

Document

Method that can be used to serialize any Java value as JSON output, using Writer provided.

Usage

From source file:com.digitalpebble.storm.crawler.metrics.DebugMetricsConsumer.java

private Server startServlet(int serverPort) throws Exception {
    // Setup HTTP server
    Server server = new Server(serverPort);
    Context root = new Context(server, "/");
    server.start();/*ww  w .j  av  a2 s .  co  m*/

    HttpServlet servlet = new HttpServlet() {
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp)
                throws ServletException, IOException {
            SortedMap<String, Number> metrics = ImmutableSortedMap.copyOf(DebugMetricsConsumer.this.metrics);
            SortedMap<String, Map<String, Object>> metrics_metadata = ImmutableSortedMap
                    .copyOf(DebugMetricsConsumer.this.metrics_metadata);

            Map<String, Object> toplevel = ImmutableMap.of("retrieved", new Date(),

                    // TODO this call fails with mysterious
                    // exception
                    // "java.lang.IllegalArgumentException: Could not find component common for __metrics"
                    // Mailing list suggests it's a library version
                    // issue but couldn't find anything suspicious
                    // Need to eventually investigate
                    // "sources",
                    // context.getThisSources().toString(),

                    "metrics", metrics, "metric_metadata", metrics_metadata);

            ObjectWriter prettyPrinter = OM.writerWithDefaultPrettyPrinter();
            prettyPrinter.writeValue(resp.getWriter(), toplevel);
        }
    };

    root.addServlet(new ServletHolder(servlet), "/metrics");

    log.info("Started metric server...");
    return server;

}

From source file:net.riezebos.thoth.renderers.RendererBase.java

protected void executeJson(Map<String, Object> variables, OutputStream outputStream) throws ServletException {
    try {// ww w .  j  a va 2 s  . c  o m
        boolean prettyPrintJson = getConfiguration().isPrettyPrintJson();
        ObjectMapper mapper = new ObjectMapper();
        ObjectWriter writer = prettyPrintJson ? mapper.writerWithDefaultPrettyPrinter() : mapper.writer();
        writer.writeValue(outputStream, variables);
    } catch (Exception e) {
        throw new ServletException(e);
    }
}

From source file:org.n52.web.BaseController.java

private void writeExceptionResponse(WebException e, HttpServletResponse response, HttpStatus status) {

    if (status == INTERNAL_SERVER_ERROR) {
        LOGGER.error("An exception occured.", e);
    } else {//from w w  w . j  a v  a 2  s. c o m
        LOGGER.debug("An exception occured.", e);
    }

    // TODO consider using a 'suppress_response_codes=true' parameter and always return 200 OK

    response.setStatus(status.value());
    response.setContentType(APPLICATION_JSON.getMimeType());
    ObjectMapper objectMapper = createObjectMapper();
    ObjectWriter writer = objectMapper.writerWithType(ExceptionResponse.class);
    ExceptionResponse exceptionResponse = createExceptionResponse(e, status);
    try {
        writer.writeValue(response.getOutputStream(), exceptionResponse);
    } catch (IOException ioe) {
        LOGGER.error("Could not process error message.", e);
    }
}

From source file:ch.cyberduck.core.sds.SDSDelegatingCopyFeature.java

@Override
public void copy(final Path source, final Path target, final TransferStatus status,
        final ConnectionCallback callback) throws BackgroundException {
    if (containerService.getContainer(target).getType().contains(Path.Type.vault)) {
        final FileKey fileKey = TripleCryptConverter.toSwaggerFileKey(Crypto.generateFileKey());
        final ObjectWriter writer = session.getClient().getJSON().getContext(null).writerFor(FileKey.class);
        final ByteArrayOutputStream out = new ByteArrayOutputStream();
        try {//from  www.  j ava 2  s .c  o m
            writer.writeValue(out, fileKey);
        } catch (IOException e) {
            throw new DefaultIOExceptionMappingService().map(e);
        }
        status.setFilekey(ByteBuffer.wrap(out.toByteArray()));
    }
    if (containerService.getContainer(source).getType().contains(Path.Type.vault)
            || containerService.getContainer(target).getType().contains(Path.Type.vault)) {
        new DefaultCopyFeature(session).copy(source, target, status, callback);
    } else {
        if (StringUtils.equals(source.getName(), target.getName())) {
            proxy.copy(source, target, status, callback);
        } else {
            new DefaultCopyFeature(session).copy(source, target, status, callback);
        }
    }
}

From source file:org.wrml.runtime.format.application.schema.json.JsonSchemaFormatter.java

@Override
public void writeModel(final OutputStream out, final Model model, final ModelWriteOptions writeOptions)
        throws ModelWritingException, UnsupportedOperationException {

    final Context context = getContext();
    final SchemaLoader schemaLoader = context.getSchemaLoader();

    if (!(model instanceof Schema)) {
        throw new UnsupportedOperationException(getClass().getSimpleName()
                + " can be used to read and write schemas only (" + schemaLoader.getSchemaSchemaUri() + ")");
    }//  w w  w. j  ava2  s. c o m

    final Schema wrmlSchema = (Schema) model;
    final ObjectWriter objectWriter = new ObjectMapper().writer(new DefaultPrettyPrinter());
    final JsonSchema jsonSchema = schemaLoader.getJsonSchemaLoader().load(wrmlSchema);

    try {
        objectWriter.writeValue(out, jsonSchema.getRootNode());
    } catch (final Exception e) {
        throw new ModelWritingException(
                getClass().getSimpleName() + " encounter an error while attempting to write a JSON Schema ("
                        + model + ").  Message: " + e.getMessage(),
                null, this);

    }

}

From source file:com.moreapps.SwaggerMojo.java

public void execute() throws MojoExecutionException {
    SpringMvcParser springMvcParser = new SpringMvcParser(getLog());
    springMvcParser.setApiVersion(apiVersion);
    springMvcParser.setBasePath(basePath);

    Service service = springMvcParser.parse(baseControllerPackage);

    ServiceInfo info = new ServiceInfo();
    info.setTitle(title);//  w ww . j  a v a 2  s  .  c om
    info.setDescription(description);
    info.setTermsOfServiceUrl(termsOfServiceUrl);
    info.setContact(contact);
    info.setLicense(license);
    info.setLicenseUrl(licenseUrl);
    service.setInfo(info);

    try {
        ensureDirectoryExists(outputDirectory);

        ObjectWriter objectWriter = new ObjectMapper().writerWithDefaultPrettyPrinter();
        File serviceFile = new File(outputDirectory, "service.json");
        getLog().info("Writing to file " + serviceFile);
        objectWriter.writeValue(serviceFile, service);

        for (ServiceApi serviceApi : service.getApis()) {
            ServiceApiDetail details = serviceApi.getDetails();

            if (details.getResourcePath() == null) {
                throw new MojoExecutionException("ResourcePath of " + serviceApi.getPath() + " cannot be null");
            }
            File detailOutputFile = new File(outputDirectory, details.getResourcePath() + ".json");
            getLog().info("Writing to file " + detailOutputFile);
            ensureDirectoryExists(detailOutputFile.getParentFile());

            objectWriter.writeValue(detailOutputFile, details);
        }
    } catch (IOException e) {
        throw new MojoExecutionException(e.getMessage(), e);
    }
}

From source file:org.n52.web.ctrl.BaseController.java

private void writeExceptionResponse(WebException e, HttpServletResponse response, HttpStatus status) {

    if (status == INTERNAL_SERVER_ERROR) {
        LOGGER.error("An exception occured.", e);
    } else {/*from  w  w  w. j av a  2s. c om*/
        LOGGER.debug("An exception occured.", e);
    }

    // TODO consider using a 'suppress_response_codes=true' parameter and always return 200 OK
    response.setStatus(status.value());
    response.setContentType(APPLICATION_JSON.getMimeType());
    ObjectMapper objectMapper = createObjectMapper();
    ObjectWriter writer = objectMapper.writerFor(ExceptionResponse.class);
    ExceptionResponse exceptionResponse = createExceptionResponse(e, status);
    try (OutputStream outputStream = response.getOutputStream()) {
        writer.writeValue(outputStream, exceptionResponse);
    } catch (IOException ioe) {
        LOGGER.error("Could not process error message.", ioe);
    }
}

From source file:ai.grakn.engine.controller.SystemController.java

@GET
@Path("/metrics")
@ApiOperation(value = "Exposes internal metrics")
@ApiImplicitParams({//from  w  w  w  .j  a va  2s  .  c  o m
        @ApiImplicitParam(name = FORMAT, value = "prometheus", dataType = "string", paramType = "path") })
private String getMetrics(Request request, Response response) throws IOException {
    response.header(CACHE_CONTROL, "must-revalidate,no-cache,no-store");
    response.status(HttpServletResponse.SC_OK);
    Optional<String> format = Optional.ofNullable(request.queryParams(FORMAT));
    String dFormat = format.orElse(JSON);
    if (dFormat.equals(PROMETHEUS)) {
        // Prometheus format for the metrics
        response.type(PROMETHEUS_CONTENT_TYPE);
        final Writer writer1 = new StringWriter();
        TextFormat.write004(writer1, this.prometheusRegistry.metricFamilySamples());
        return writer1.toString();
    } else if (dFormat.equals(JSON)) {
        // Json/Dropwizard format
        response.type(APPLICATION_JSON);
        final ObjectWriter writer = mapper.writer();
        try (ByteArrayOutputStream output = new ByteArrayOutputStream()) {
            writer.writeValue(output, this.metricRegistry);
            return new String(output.toByteArray(), "UTF-8");
        }
    } else {
        throw new IllegalArgumentException("Unexpected format " + dFormat);
    }
}

From source file:com.basistech.rosette.dm.json.array.JsonTest.java

@Test
public void versionCheckPasses() throws Exception {
    StringWriter writer = new StringWriter();
    ObjectMapper mapper = AnnotatedDataModelArrayModule.setupObjectMapper(new ObjectMapper());
    ObjectWriter objectWriter = mapper.writer();
    objectWriter.writeValue(writer, referenceText);
    mapper.readValue(writer.toString(), AnnotatedText.class);
}