Example usage for com.fasterxml.jackson.databind ObjectMapper writerWithDefaultPrettyPrinter

List of usage examples for com.fasterxml.jackson.databind ObjectMapper writerWithDefaultPrettyPrinter

Introduction

In this page you can find the example usage for com.fasterxml.jackson.databind ObjectMapper writerWithDefaultPrettyPrinter.

Prototype

public ObjectWriter writerWithDefaultPrettyPrinter() 

Source Link

Document

Factory method for constructing ObjectWriter that will serialize objects using the default pretty printer for indentation

Usage

From source file:org.apache.drill.exec.store.parquet.metadata.Metadata.java

private void writeFile(ParquetTableMetadataDirs parquetTableMetadataDirs, Path p, FileSystem fs)
        throws IOException {
    JsonFactory jsonFactory = new JsonFactory();
    jsonFactory.configure(Feature.AUTO_CLOSE_TARGET, false);
    jsonFactory.configure(JsonParser.Feature.AUTO_CLOSE_SOURCE, false);
    ObjectMapper mapper = new ObjectMapper(jsonFactory);
    SimpleModule module = new SimpleModule();
    mapper.registerModule(module);/*from  w w w .  ja va 2  s .  c o m*/
    FSDataOutputStream os = fs.create(p);
    mapper.writerWithDefaultPrettyPrinter().writeValue(os, parquetTableMetadataDirs);
    os.flush();
    os.close();
}

From source file:pl.project13.maven.git.GitCommitIdMojo.java

void maybeGeneratePropertiesFile(@NotNull Properties localProperties, File base, String propertiesFilename)
        throws GitCommitIdExecutionException {
    try {//from  w w w.  j  av a2  s .c o  m
        final File gitPropsFile = craftPropertiesOutputFile(base, propertiesFilename);
        final boolean isJsonFormat = "json".equalsIgnoreCase(format);

        boolean shouldGenerate = true;

        if (gitPropsFile.exists()) {
            final Properties persistedProperties;

            try {
                if (isJsonFormat) {
                    log.info("Reading existing json file [{}] (for module {})...",
                            gitPropsFile.getAbsolutePath(), project.getName());

                    persistedProperties = readJsonProperties(gitPropsFile);
                } else {
                    log.info("Reading existing properties file [{}] (for module {})...",
                            gitPropsFile.getAbsolutePath(), project.getName());

                    persistedProperties = readProperties(gitPropsFile);
                }

                final Properties propertiesCopy = (Properties) localProperties.clone();

                final String buildTimeProperty = prefixDot + BUILD_TIME;

                propertiesCopy.remove(buildTimeProperty);
                persistedProperties.remove(buildTimeProperty);

                shouldGenerate = !propertiesCopy.equals(persistedProperties);
            } catch (CannotReadFileException ex) {
                // Read has failed, regenerate file
                log.info("Cannot read properties file [{}] (for module {})...", gitPropsFile.getAbsolutePath(),
                        project.getName());
                shouldGenerate = true;
            }
        }

        if (shouldGenerate) {
            Files.createParentDirs(gitPropsFile);
            Writer outputWriter = null;
            boolean threw = true;

            try {
                outputWriter = new OutputStreamWriter(new FileOutputStream(gitPropsFile), sourceCharset);
                if (isJsonFormat) {
                    log.info("Writing json file to [{}] (for module {})...", gitPropsFile.getAbsolutePath(),
                            project.getName());
                    ObjectMapper mapper = new ObjectMapper();
                    mapper.writerWithDefaultPrettyPrinter().writeValue(outputWriter, localProperties);
                } else {
                    log.info("Writing properties file to [{}] (for module {})...",
                            gitPropsFile.getAbsolutePath(), project.getName());
                    localProperties.store(outputWriter, "Generated by Git-Commit-Id-Plugin");
                }
                threw = false;
            } catch (final IOException ex) {
                throw new RuntimeException("Cannot create custom git properties file: " + gitPropsFile, ex);
            } finally {
                Closeables.close(outputWriter, threw);
            }
        } else {
            log.info("Properties file [{}] is up-to-date (for module {})...", gitPropsFile.getAbsolutePath(),
                    project.getName());
        }
    } catch (IOException e) {
        throw new GitCommitIdExecutionException(e);
    }
}

From source file:org.apache.drill.exec.store.parquet.metadata.Metadata.java

/**
 * Serialize parquet metadata to json and write to a file.
 *
 * @param parquetTableMetadata parquet table metadata
 * @param p file path/*from www.j a v a2 s  .  c om*/
 */
private void writeFile(ParquetTableMetadata_v3 parquetTableMetadata, Path p, FileSystem fs) throws IOException {
    JsonFactory jsonFactory = new JsonFactory();
    jsonFactory.configure(Feature.AUTO_CLOSE_TARGET, false);
    jsonFactory.configure(JsonParser.Feature.AUTO_CLOSE_SOURCE, false);
    ObjectMapper mapper = new ObjectMapper(jsonFactory);
    SimpleModule module = new SimpleModule();
    module.addSerializer(ColumnMetadata_v3.class, new ColumnMetadata_v3.Serializer());
    mapper.registerModule(module);
    FSDataOutputStream os = fs.create(p);
    mapper.writerWithDefaultPrettyPrinter().writeValue(os, parquetTableMetadata);
    os.flush();
    os.close();
}

From source file:emea.summit.architects.HackathlonAPIResource.java

@POST
@Path("/service/proxy")
@Consumes("application/json")
@ApiOperation("Receives request, validates request so far, identifies next service to contact, contacts the service OR if no more sends the email to SANTA")
public String submit(TeamPayload request) {
    boolean PROD_ENV = System.getenv("ENVIRONMENT") != null
            && System.getenv("ENVIRONMENT").equalsIgnoreCase("PROD") ? true : false;

    //      IClient ocpClient = createOCPClient();

    //      System.out.println("<------------------ ROUTE DETAILS ------------------>");
    //      System.out.println(ocpClient.get(ResourceKind.ROUTE, namespaceFromService(request.getServiceName())));
    //      System.out.println("<--------------------------------------------------->");

    System.out.println("=====[" + System.getenv("ENVIRONMENT") + " MODE]=============REQUESTING SERVICE: "
            + request.getServiceName() + "=======================");
    System.out.println("PAYLOAD PROVIDED");
    ObjectMapper mapper = new ObjectMapper();
    String jsonInString = null;//from www  .ja  v  a 2s  .c  o  m
    try {
        //Convert object to JSON string and pretty print
        jsonInString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(request);
        System.out.println("JSON REQUEST " + jsonInString);

    } catch (Exception e) {
        e.printStackTrace();
        return "Failed to transform to JSON " + e.getMessage();
    }

    boolean payloadValid = validate(request.getPayload()).equalsIgnoreCase(VALID_RESPONSE);
    if (PROD_ENV) {

        System.out.println("[" + System.getenv("ENVIRONMENT") + "] Payload Valid Pass: " + payloadValid);

        String host = System.getenv(serviceENVVariableMap.get(request.getServiceName()) + "_SERVICE_HOST");
        String port = System.getenv(serviceENVVariableMap.get(request.getServiceName()) + "_SERVICE_PORT");

        if (!request.getServiceName().equalsIgnoreCase("alabaster-snowball")) {
            System.out.println("Next call Service [" + serviceENVVariableMap.get(request.getServiceName())
                    + "] at http://" + host + ":" + port + "/reindeerservice");
            httpCall("POST", "http://" + host + ":" + port + "/reindeerservice", jsonInString);
        } else {
            System.out.println("Next Notify Santa via Email");
            EmailPayload email = new EmailPayload(request.getPayload(), "SUCCESS",
                    Arrays.asList("stelios@redhat.com"));

            mapper = new ObjectMapper();
            String jsonEmailString = null;
            try {
                //Convert object to JSON string
                jsonEmailString = mapper.writeValueAsString(email);

                //Convert object to JSON string and pretty print
                jsonEmailString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(email);
                System.out.println("JSON REQUEST " + jsonEmailString);

            } catch (Exception e) {
                e.printStackTrace();
                return "Failed to transform to JSON " + e.getMessage();
            }

            System.out.println("EMAIL DIRECT (NO REST SERVICE CALL...");
            sendEmailNotification(email);

            // Hackahtlon reward
            System.out.println("Reward will be sent to hackathlon participant");
            Set rewardEmails = new HashSet<String>();
            for (RequestPayload item : request.getPayload()) {
                for (Map.Entry<String, String> entry : item.getNameEmaiMap().entrySet()) {
                    System.out.println(entry.getKey() + " : " + entry.getValue());
                    rewardEmails.add(entry.getValue());
                }
            }
            String emailBody = "Dear Hackathlon Participant,\n Thank you for participating on the PAAS Hackathlon. To reward you for your tenacity send to atarocch@redhat.com, stelios@redhat.com "
                    + "your T-SHIRT size along with a delivery address for some Red Hat swag. \nThank You\n The Hackathlon Team";
            try {
                String emailContent = (email.getContent() == null ? "" : email.getContent().toString());
                JavaMailService.generateAndSendEmail(emailBody, "REWARD FOR PAAS HACKATHLON PARTICIPATION",
                        new ArrayList<String>(rewardEmails));
            } catch (MessagingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                return "Email Failed due to " + e.getMessage();
            }

        }

    } else {
        String host = System.getenv(serviceENVVariableMap.get(request.getServiceName()) + "_SERVICE_HOST");
        String port = System.getenv(serviceENVVariableMap.get(request.getServiceName()) + "_SERVICE_PORT");

        System.out
                .println("[" + System.getenv("ENVIRONMENT") + "]Payload Validation Statement: " + payloadValid);
        System.out.println("Next call [" + serviceENVVariableMap.get(request.getServiceName())
                + "] \n POST   http://" + host + ":" + port);

        if (request.getServiceName().equalsIgnoreCase("alabaster-snowball")) {
            System.out.println("Next Service we would have called if NOT in DEV Mode would have been ["
                    + serviceENVVariableMap.get(request.getServiceName())
                    + "/api/service/email-santa] \n POST   http://" + host + ":" + port
                    + "/api/service/email-santa");
        } else {
            System.out.println("Next Service we would have called if NOT in DEV Mode would have been ["
                    + serviceENVVariableMap.get(request.getServiceName()) + "/reindeerservice] http://" + host
                    + ":" + port + "/redindeerservice");
        }

    }

    System.out.println("Request from [" + request.getServiceName() + "] submitted successfully to next service "
            + serviceENVVariableMap.get(request.getServiceName()) + "] payload was "
            + (payloadValid ? "VALID" : "INVALID"));
    System.out.println("^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^");

    return "Request from [" + request.getServiceName() + "] submitted successfully to next service ["
            + serviceENVVariableMap.get(request.getServiceName()) + "] payload was "
            + (payloadValid ? "VALID" : "INVALID") + "\n" + request.toString();
}

From source file:com.spectralogic.ds3cli.views.json.CommandExceptionJsonView.java

@Override
public String render(final CommandException obj) throws JsonProcessingException {
    final CommonJsonView view = CommonJsonView.newView(CommonJsonView.Status.ERROR);
    final Map<String, String> jsonBackingMap = new TreeMap<>();

    view.message(obj.getMessage());//from ww w .j  a va 2 s. co  m

    try {
        final ObjectMapper mapper = new ObjectMapper();
        if (obj.getCause() != null) {
            if (obj.getCause() instanceof FailedRequestException) {
                final FailedRequestException ce = (FailedRequestException) obj.getCause();
                jsonBackingMap.put("StatusCode", Integer.toString(ce.getStatusCode()));
                jsonBackingMap.put("ApiErrorMessage", ce.getResponseString());
            } else {
                final ByteArrayOutputStream out = new ByteArrayOutputStream();
                final PrintWriter pOut = new PrintWriter(out);
                obj.printStackTrace(pOut);
                try {
                    jsonBackingMap.put("StackTrace", out.toString("utf-8"));
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }
        }

        return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(view.data(jsonBackingMap));
    } catch (final Exception e) {
        return "Failed to render error: " + e.getMessage();
    }
}

From source file:org.opencb.opencga.storage.app.cli.client.executors.VariantCommandExecutor.java

private void query() throws Exception {
    StorageVariantCommandOptions.VariantQueryCommandOptions variantQueryCommandOptions = variantCommandOptions.variantQueryCommandOptions;

    //        if (true) {
    ////            System.out.println(variantCommandOptions.queryVariantsCommandOptions.toString());
    //            System.out.println(new ObjectMapper().writer().withDefaultPrettyPrinter().writeValueAsString(variantCommandOptions
    //                    .variantQueryCommandOptions));
    //            return;
    //        }/* ww w  .j  a v a  2s.c om*/

    storageConfiguration.getVariant().getOptions().putAll(variantQueryCommandOptions.commonOptions.params);

    VariantDBAdaptor variantDBAdaptor = variantStorageEngine
            .getDBAdaptor(variantQueryCommandOptions.commonQueryOptions.dbName);
    List<String> studyNames = variantDBAdaptor.getStudyConfigurationManager().getStudyNames(new QueryOptions());

    Query query = VariantQueryCommandUtils.parseQuery(variantQueryCommandOptions, studyNames);
    QueryOptions options = VariantQueryCommandUtils.parseQueryOptions(variantQueryCommandOptions);
    options.put("summary", variantQueryCommandOptions.summary);

    if (variantQueryCommandOptions.commonQueryOptions.count) {
        QueryResult<Long> result = variantDBAdaptor.count(query);
        System.out.println("Num. results\t" + result.getResult().get(0));
    } else if (StringUtils.isNotEmpty(variantQueryCommandOptions.rank)) {
        executeRank(query, variantDBAdaptor, variantQueryCommandOptions);
    } else if (StringUtils.isNotEmpty(variantQueryCommandOptions.groupBy)) {
        ObjectMapper objectMapper = new ObjectMapper();
        QueryResult groupBy = variantDBAdaptor.groupBy(query, variantQueryCommandOptions.groupBy, options);
        System.out.println(
                "groupBy = " + objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(groupBy));
    } else {
        URI uri = StringUtils.isEmpty(variantQueryCommandOptions.commonQueryOptions.output) ? null
                : UriUtils.createUri(variantQueryCommandOptions.commonQueryOptions.output);

        if (variantQueryCommandOptions.annotations != null) {
            options.add("annotations", variantQueryCommandOptions.annotations);
        }
        VariantWriterFactory.VariantOutputFormat of = VariantWriterFactory.toOutputFormat(
                variantQueryCommandOptions.outputFormat, variantQueryCommandOptions.commonQueryOptions.output);
        variantStorageEngine.exportData(uri, of, variantQueryCommandOptions.commonQueryOptions.dbName, query,
                options);
    }
}

From source file:io.fabric8.ConnectorMojo.java

@Override
public File createArchive() throws MojoExecutionException {

    String gitUrl;// w w  w  .  j a v a2 s.c o m

    // find the component dependency and get its .json file

    File file = new File(classesDirectory, "camel-connector.json");
    if (file.exists()) {

        // we want to include the git url of the project
        File gitFolder = GitHelper.findGitFolder();
        try {
            gitUrl = GitHelper.extractGitUrl(gitFolder);
        } catch (IOException e) {
            throw new MojoExecutionException("Cannot extract gitUrl due " + e.getMessage(), e);
        }
        if (gitUrl == null) {
            getLog().warn("No .git directory found for connector");
        }

        try {

            ObjectMapper mapper = new ObjectMapper();
            Map dto = mapper.readValue(file, Map.class);

            // embed girUrl in camel-connector.json file
            if (gitUrl != null) {
                String existingGitUrl = (String) dto.get("gitUrl");
                if (existingGitUrl == null || !existingGitUrl.equals(gitUrl)) {
                    dto.put("gitUrl", gitUrl);
                    // update file
                    mapper.writerWithDefaultPrettyPrinter().writeValue(file, dto);
                    // update source file also
                    File root = classesDirectory.getParentFile().getParentFile();
                    file = new File(root, "src/main/resources/camel-connector.json");
                    if (file.exists()) {
                        getLog().info("Updating gitUrl to " + file);
                        mapper.writerWithDefaultPrettyPrinter().writeValue(file, dto);
                    }
                }
            }

            File schema = embedCamelComponentSchema(file);
            if (schema != null) {
                String json = loadText(new FileInputStream(schema));

                List<Map<String, String>> rows = parseJsonSchema("component", json, false);
                String header = buildComponentHeaderSchema(rows, dto, gitUrl);
                getLog().debug(header);

                rows = parseJsonSchema("componentProperties", json, true);
                // we do not offer editing component properties (yet) so clear the rows
                rows.clear();
                String componentOptions = buildComponentOptionsSchema(rows, dto);
                getLog().debug(componentOptions);

                rows = parseJsonSchema("properties", json, true);
                String endpointOptions = buildEndpointOptionsSchema(rows, dto);
                getLog().debug(endpointOptions);

                // generate the json file
                StringBuilder jsonSchema = new StringBuilder();
                jsonSchema.append("{\n");
                jsonSchema.append(header);
                jsonSchema.append(componentOptions);
                jsonSchema.append(endpointOptions);
                jsonSchema.append("}\n");

                String newJson = jsonSchema.toString();

                // parse ourselves
                rows = parseJsonSchema("component", newJson, false);
                String newScheme = getOption(rows, "scheme");

                // write the json file to the target directory as if camel apt would do it
                String javaType = (String) dto.get("javaType");
                String dir = javaType.substring(0, javaType.lastIndexOf("."));
                dir = dir.replace('.', '/');
                File subDir = new File(classesDirectory, dir);
                String name = newScheme + ".json";
                File out = new File(subDir, name);

                FileOutputStream fos = new FileOutputStream(out, false);
                fos.write(newJson.getBytes());
                fos.close();
            }

            // build json schema for component that only has the selectable options
        } catch (Exception e) {
            throw new MojoExecutionException("Error in connector-maven-plugin", e);
        }
    }

    return super.createArchive();
}

From source file:org.forgerock.openidm.tools.scriptedbundler.ScriptedBundler.java

private static void printHelp() {
    HelpFormatter help = new HelpFormatter();
    help.printHelp("bundle [OPTIONS] -c <FILE>", options);

    try {//from www .j a  v a  2s . c  o  m
        ObjectMapper mapper = new ObjectMapper();
        System.out.println("Configuration format:");
        CustomConfiguration config = new CustomConfiguration();
        config.setPackageName("MyConnector");
        config.setDisplayName("My Connector");
        config.setDescription("This is my super awesome connector");
        config.setVersion("1.0");
        config.setAuthor("Coder McLightningfingers");
        config.setProvidedProperties(Arrays.asList(new ProvidedProperty() {
            {
                setName("provided1");
                setValue("default");
                setType("String");
            }
        }, new ProvidedProperty() {
            {
                setName("provided2");
                setValue(2);
                setType("Integer");
            }
        }));
        config.setProperties(Arrays.asList(new CustomProperty() {
            {
                setOrder(0);
                setType("String");
                setName("FirstProperty");
                setValue("firstValue");
                setRequired(Boolean.TRUE);
                setConfidential(Boolean.FALSE);
                setDisplayMessage("This is my first property");
                setHelpMessage("This should be a String value");
                setGroup("default");
            }
        }, new CustomProperty() {
            {
                setOrder(1);
                setType("Double");
                setName("SecondProperty");
                setValue(1.234);
                setRequired(Boolean.FALSE);
                setConfidential(Boolean.FALSE);
                setDisplayMessage("This is my second property");
                setHelpMessage("This should be a Double value");
                setGroup("default");
            }
        }));
        System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(config));
    } catch (Exception e) {
        /* no user input, won't happen */
    }
}

From source file:eu.seaclouds.platform.planner.core.Planner.java

private String generateMMOutput2(Map<String, HashSet<String>> mmResult,
        Map<String, Pair<NodeTemplate, String>> offerings) throws JsonProcessingException {
    ObjectMapper mapper = new ObjectMapper();

    ArrayList<Map<String, ArrayList<Map<String, Object>>>> singleRes = new ArrayList<>();

    Yaml yml = new Yaml();

    for (String moduleName : mmResult.keySet()) {

        ArrayList<Map<String, Object>> suitableList = new ArrayList<>();

        //create suitable lists
        for (String id : mmResult.get(moduleName)) {
            String off = offerings.get(id).second;
            Map<String, Object> innerMap = new HashMap<>();
            innerMap.put(id, off);/*from w w  w .j  av a  2s.  com*/
            suitableList.add(innerMap);
        }

        HashMap<String, ArrayList<Map<String, Object>>> finalRes = new HashMap<>();
        finalRes.put(moduleName, suitableList);
        singleRes.add(finalRes);
    }

    return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(singleRes);
}