com.fasterxml.jackson.core.util.DefaultPrettyPrinter Java Examples

The following examples show how to use com.fasterxml.jackson.core.util.DefaultPrettyPrinter. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: JacksonSerializeUnitTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void whenCustomSerialize_thenCorrect() throws ParseException, IOException {

    final SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");

    final ActorJackson rudyYoungblood = new ActorJackson("nm2199632", sdf.parse("21-09-1982"), Arrays.asList("Apocalypto", "Beatdown", "Wind Walkers"));
    final MovieWithNullValue movieWithNullValue = new MovieWithNullValue(null, "Mel Gibson", Arrays.asList(rudyYoungblood));

    final SimpleModule module = new SimpleModule();
    module.addSerializer(new ActorJacksonSerializer(ActorJackson.class));
    final ObjectMapper mapper = new ObjectMapper();

    final String jsonResult = mapper.registerModule(module)
        .writer(new DefaultPrettyPrinter())
        .writeValueAsString(movieWithNullValue);

    final Object json = mapper.readValue("{\"actors\":[{\"imdbId\":\"nm2199632\",\"dateOfBirth\":\"21-09-1982\",\"N° Film: \":3,\"filmography\":\"Apocalypto-Beatdown-Wind Walkers\"}],\"imdbID\":null}", Object.class);
    final String expectedOutput = new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT)
        .writeValueAsString(json);

    Assert.assertEquals(jsonResult, expectedOutput);
}
 
Example #2
Source File: DataMappingService.java    From vethrfolnir-mu with GNU General Public License v3.0 6 votes vote down vote up
@Inject
private void load() {
	if(assetManager == null) {
		throw new RuntimeException("AssetManaget has not been set in your setup! Mapping service cannot be performed!");
	}
	
	defaultTypeFactory = TypeFactory.defaultInstance();

	jsonMapper.setVisibilityChecker(jsonMapper.getDeserializationConfig().getDefaultVisibilityChecker()
	        .withCreatorVisibility(JsonAutoDetect.Visibility.NONE)
	        .withFieldVisibility(JsonAutoDetect.Visibility.ANY)
	        .withGetterVisibility(JsonAutoDetect.Visibility.NONE)
	        .withIsGetterVisibility(JsonAutoDetect.Visibility.NONE)
	        .withSetterVisibility(JsonAutoDetect.Visibility.NONE));
	
	jsonMapper.configure(SerializationFeature.INDENT_OUTPUT, true).configure(Feature.ALLOW_COMMENTS, true);
	
	defaultPrettyPrinter = new DefaultPrettyPrinter();
	defaultPrettyPrinter.indentArraysWith(new Lf2SpacesIndenter());
}
 
Example #3
Source File: JSON.java    From rapidoid with Apache License 2.0 6 votes vote down vote up
private static ObjectMapper prettyMapper() {
	ObjectMapper mapper = new ObjectMapper();
	mapper.setBase64Variant(Base64Variants.MODIFIED_FOR_URL);
	mapper.configure(SerializationFeature.INDENT_OUTPUT, true);

	mapper.registerModule(tuuidModule());

	if (!Env.dev()) {
		mapper.registerModule(new AfterburnerModule());
	}

	DefaultPrettyPrinter pp = new DefaultPrettyPrinter();
	pp = pp.withObjectIndenter(new DefaultIndenter("  ", "\n"));

	mapper.setDefaultPrettyPrinter(pp);

	return mapper;
}
 
Example #4
Source File: JaxRsUtils.java    From cassandra-mesos-deprecated with Apache License 2.0 6 votes vote down vote up
@NotNull
public static Response buildStreamingResponse(@NotNull final JsonFactory factory, @NotNull final Response.Status status, @NotNull final StreamingJsonResponse jsonResponse) {
    return Response.status(status).entity(new StreamingOutput() {
        @Override
        public void write(final OutputStream output) throws IOException, WebApplicationException {
            try (JsonGenerator json = factory.createGenerator(output)) {
                json.setPrettyPrinter(new DefaultPrettyPrinter());
                json.writeStartObject();

                jsonResponse.write(json);

                json.writeEndObject();
            }
        }
    }).type("application/json").build();
}
 
Example #5
Source File: JsonMerger.java    From carnotzet with Apache License 2.0 6 votes vote down vote up
/**
 * Properties of file2 have precedence over the ones in file1
 */
@Override
public void merge(Path file1Path, Path file2Path, Path output) {
	ObjectMapper mapper = new ObjectMapper();
	ObjectWriter writer = mapper.writer(new DefaultPrettyPrinter());
	try (InputStream in1 = Files.newInputStream(file1Path)) {
		try (InputStream in2 = Files.newInputStream(file2Path)) {
			JsonNode file1 = mapper.readTree(in1);
			JsonNode file2 = mapper.readTree(in2);
			JsonNode merged = merge(file1, file2);
			writer.writeValue(output.toFile(), merged);
		}
	}
	catch (IOException e) {
		throw new UncheckedIOException(e);
	}
}
 
Example #6
Source File: SnapshotMatcher.java    From json-snapshot.github.io with MIT License 6 votes vote down vote up
private static PrettyPrinter buildDefaultPrettyPrinter() {
  DefaultPrettyPrinter pp =
      new DefaultPrettyPrinter("") {
        @Override
        public DefaultPrettyPrinter withSeparators(Separators separators) {
          this._separators = separators;
          this._objectFieldValueSeparatorWithSpaces =
              separators.getObjectFieldValueSeparator() + " ";
          return this;
        }
      };
  Indenter lfOnlyIndenter = new DefaultIndenter("  ", "\n");
  pp.indentArraysWith(lfOnlyIndenter);
  pp.indentObjectsWith(lfOnlyIndenter);
  return pp;
}
 
Example #7
Source File: OASGenerator.java    From crnk-framework with Apache License 2.0 6 votes vote down vote up
@VisibleForTesting
static String generateOpenApiContent(OpenAPI openApi, OutputFormat outputFormat, Boolean sort) {
  if (sort) {
    ObjectMapper objectMapper = outputFormat.mapper();
    objectMapper.enable(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS);
    objectMapper.enable(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY);
    try {
      return objectMapper.writer(new DefaultPrettyPrinter()).writeValueAsString(openApi);
    } catch (JsonProcessingException e) {
      LOGGER.error("Sorting failed!");
      return outputFormat.pretty(openApi);
    }
  } else {
    return outputFormat.pretty(openApi);
  }
}
 
Example #8
Source File: ServiceResponseMarshaller.java    From keycloak-protocol-cas with Apache License 2.0 6 votes vote down vote up
public static String marshalJson(CASServiceResponse serviceResponse) {
    ObjectMapper mapper = new ObjectMapper();
    mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    //Force newlines to be LF (default is system dependent)
    DefaultPrettyPrinter printer = new DefaultPrettyPrinter()
            .withObjectIndenter(new DefaultIndenter("  ", "\n"));

    //create wrapper node
    Map<String, Object> casModel = new HashMap<>();
    casModel.put("serviceResponse", serviceResponse);
    try {
        return mapper.writer(printer).writeValueAsString(casModel);
    } catch (JsonProcessingException e) {
        throw new RuntimeException(e);
    }
}
 
Example #9
Source File: JaxrsReaderTest.java    From swagger-maven-plugin with Apache License 2.0 6 votes vote down vote up
@Test
public void createCommonParameters() throws Exception {
    reader = new JaxrsReader(new Swagger(), Mockito.mock(Log.class));
    Swagger result = reader.read(CommonParametersApi.class);
    Parameter headerParam = result.getParameter("headerParam");
    assertTrue(headerParam instanceof HeaderParameter);
    Parameter queryParam = result.getParameter("queryParam");
    assertTrue(queryParam instanceof QueryParameter);

    result = reader.read(ReferenceCommonParametersApi.class);
    Operation get = result.getPath("/apath").getGet();
    List<Parameter> parameters = get.getParameters();
    for (Parameter parameter : parameters) {
        assertTrue(parameter instanceof RefParameter);
    }

    ObjectMapper mapper = Json.mapper();
    ObjectWriter jsonWriter = mapper.writer(new DefaultPrettyPrinter());
    String json = jsonWriter.writeValueAsString(result);
    JsonNode expectJson = mapper.readTree(this.getClass().getResourceAsStream("/expectedOutput/swagger-common-parameters.json"));
    JsonAssert.assertJsonEquals(expectJson, json);
}
 
Example #10
Source File: JsonProvider.java    From teku with Apache License 2.0 6 votes vote down vote up
private void addTekuMappers() {
  SimpleModule module = new SimpleModule("TekuJson", new Version(1, 0, 0, null, null, null));

  module.addSerializer(Bitlist.class, new BitlistSerializer());
  module.addDeserializer(Bitlist.class, new BitlistDeserializer());
  module.addDeserializer(Bitvector.class, new BitvectorDeserializer());
  module.addSerializer(Bitvector.class, new BitvectorSerializer());

  module.addSerializer(BLSPubKey.class, new BLSPubKeySerializer());
  module.addDeserializer(BLSPubKey.class, new BLSPubKeyDeserializer());
  module.addDeserializer(BLSSignature.class, new BLSSignatureDeserializer());
  module.addSerializer(BLSSignature.class, new BLSSignatureSerializer());

  module.addDeserializer(Bytes32.class, new Bytes32Deserializer());
  module.addDeserializer(Bytes4.class, new Bytes4Deserializer());
  module.addSerializer(Bytes4.class, new Bytes4Serializer());
  module.addDeserializer(Bytes.class, new BytesDeserializer());
  module.addSerializer(Bytes.class, new BytesSerializer());

  module.addDeserializer(UnsignedLong.class, new UnsignedLongDeserializer());
  module.addSerializer(UnsignedLong.class, new UnsignedLongSerializer());

  objectMapper.registerModule(module).writer(new DefaultPrettyPrinter());
}
 
Example #11
Source File: Backup.java    From zoocreeper with Apache License 2.0 6 votes vote down vote up
public void backup(OutputStream os) throws InterruptedException, IOException, KeeperException {
    JsonGenerator jgen = null;
    ZooKeeper zk = null;
    try {
        zk = options.createZooKeeper(LOGGER);
        jgen = JSON_FACTORY.createGenerator(os);
        if (options.prettyPrint) {
            jgen.setPrettyPrinter(new DefaultPrettyPrinter());
        }
        jgen.writeStartObject();
        if (zk.exists(options.rootPath, false) == null) {
            LOGGER.warn("Root path not found: {}", options.rootPath);
        } else {
            doBackup(zk, jgen, options.rootPath);
        }
        jgen.writeEndObject();
    } finally {
        if (jgen != null) {
            jgen.close();
        }
        if (zk != null) {
            zk.close();
        }
    }
}
 
Example #12
Source File: JSONUtil.java    From webanno with Apache License 2.0 5 votes vote down vote up
public static String toJsonString(ObjectMapper aMapper, boolean aPretty, Object aObject)
    throws IOException
{
    StringWriter out = new StringWriter();

    JsonGenerator jsonGenerator = aMapper.getFactory().createGenerator(out);
    if (aPretty) {
        jsonGenerator.setPrettyPrinter(new DefaultPrettyPrinter()
                .withObjectIndenter(new DefaultIndenter().withLinefeed("\n")));
    }

    jsonGenerator.writeObject(aObject);
    return out.toString();
}
 
Example #13
Source File: JsonFormatter.java    From formatter-maven-plugin with Apache License 2.0 5 votes vote down vote up
@Override
public void init(Map<String, String> options, ConfigurationSource cfg) {
    super.initCfg(cfg);

    int indent = Integer.parseInt(options.getOrDefault("indent", "4"));
    String lineEnding = options.getOrDefault("lineending", System.lineSeparator());
    boolean spaceBeforeSeparator = Boolean.parseBoolean(options.getOrDefault("spaceBeforeSeparator", "true"));

    formatter = new ObjectMapper();

    // Setup a pretty printer with an indenter (indenter has 4 spaces in this case)
    DefaultPrettyPrinter.Indenter indenter = new DefaultIndenter(Strings.repeat(" ", indent), lineEnding);
    DefaultPrettyPrinter printer = new DefaultPrettyPrinter() {
        private static final long serialVersionUID = 1L;

        @Override
        public DefaultPrettyPrinter createInstance() {
            return new DefaultPrettyPrinter(this);
        }

        @Override
        public DefaultPrettyPrinter withSeparators(Separators separators) {
            this._separators = separators;
            this._objectFieldValueSeparatorWithSpaces = (spaceBeforeSeparator ? " " : "")
                    + separators.getObjectFieldValueSeparator() + " ";
            return this;
        }
    };

    printer.indentObjectsWith(indenter);
    printer.indentArraysWith(indenter);
    formatter.setDefaultPrettyPrinter(printer);
    formatter.enable(SerializationFeature.INDENT_OUTPUT);
}
 
Example #14
Source File: JacksonObjectMapper.java    From bonita-ui-designer with GNU General Public License v2.0 5 votes vote down vote up
public byte[] toPrettyJson(Object object, Class<?> serializationView) throws IOException {
    // Use UTF8 to accept any character and have platform-independent files.
    return objectMapper.writerWithView(serializationView)
            .with(new DefaultPrettyPrinter()
                .withArrayIndenter(DefaultIndenter.SYSTEM_LINEFEED_INSTANCE))
            .writeValueAsString(object)
            .getBytes(StandardCharsets.UTF_8);
}
 
Example #15
Source File: SceneSerializer.java    From flashback with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public void serialize(Scene scene, Writer writer)
    throws IOException {
  _jsonGenerator = JSON_FACTORY.createGenerator(writer);
  _jsonGenerator.setPrettyPrinter(new DefaultPrettyPrinter());
  _jsonGenerator.writeStartObject();
  _jsonGenerator.writeStringField(SceneSerializationConstant.SCENE_TAG_NAME, scene.getName());
  writeHttpExchanges(scene.getRecordedHttpExchangeList());
  _jsonGenerator.writeEndObject();
  _jsonGenerator.close();
}
 
Example #16
Source File: TestDependencyReport.java    From status with Apache License 2.0 5 votes vote down vote up
@Test
public void testJsonInvariants() throws Exception {
    final Dependency alwaysDies = new PingableDependency("alwaysDies", "", BuiltIns.REQUIRED) {
        public void ping () throws Exception {
            // throw a new checked exception caused by an unchecked exceptions
            throw new IOException(new NullPointerException());
        }

        @Override
        public String getDocumentationUrl() {
            return null;
        }
    };
    final DependencyManager manager = new DependencyManager();
    manager.addDependency(alwaysDies);

    final CheckResultSet results = manager.evaluate();
    final StringWriter out = new StringWriter();
    new JsonFactory(new ObjectMapper()).createJsonGenerator(out).setPrettyPrinter(new DefaultPrettyPrinter()).writeObject(results.summarize(true));
    final String json = out.toString();

    final List<String> expectedJsonFingerprints = ImmutableList.of(
                    "\"status\" : \"OUTAGE\"",
                    "\"exception\" : \"IOException\"",
                    "\"exception\" : \"NullPointerException\"");
    for (final String fingerprint:  expectedJsonFingerprints) {
        Assert.assertTrue(
                "Expected to find fingerprint '" + fingerprint + "' in json: " + json,
                json.contains(fingerprint));
    }
}
 
Example #17
Source File: UserConfigUtils.java    From burp-rest-api with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * Given a userconfig, copy it in a new temporary file and injects all the registered extensions
 * @param path a userconfig path to be injected
 * @return a new userconfig path
 * @throws IOException when one of the two userconfig is not accessible/writable/creatable
 */
public String injectExtensions(String path) throws IOException {
    Path userOptionsTempFile = Files.createTempFile("user-options_", ".json");
    FileCopyUtils.copy(new File(path), userOptionsTempFile.toFile());

    //addBurpExtensions here to the temporary file and return the handle to the new temporary file
    //- read all file in in jackson object
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);
    JsonNode tree = objectMapper.readTree(userOptionsTempFile.toFile());
    //- inject the burp extensions here inside the user configuration
    JsonNode user_options = safeGet(objectMapper, tree, "user_options");
    JsonNode extender = safeGet(objectMapper, user_options, "extender");
    JsonNode extension = extender.get("extensions");
    if (!extension.isArray()) {
        ArrayNode array = objectMapper.createArrayNode();
        ((ObjectNode)extender).replace("extensions", array);
        extension = array;
    }
    for (Extension e : extensions) {
        ((ArrayNode) extension).addPOJO(e);
    }
    //- write the jackson configuration inside the temporary user configuration
    objectMapper.writer(new DefaultPrettyPrinter()).writeValue(userOptionsTempFile.toFile(), tree);

    userOptionsTempFile.toFile().deleteOnExit();
    return userOptionsTempFile.toAbsolutePath().toString();
}
 
Example #18
Source File: RDFJSONWriter.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static void modelToRdfJsonInternal(final Model graph, final WriterConfig writerConfig,
		final JsonGenerator jg) throws IOException, JsonGenerationException {
	if (writerConfig.get(BasicWriterSettings.PRETTY_PRINT)) {
		// SES-2011: Always use \n for consistency
		Indenter indenter = DefaultIndenter.SYSTEM_LINEFEED_INSTANCE;
		// By default Jackson does not pretty print, so enable this unless
		// PRETTY_PRINT setting is disabled
		DefaultPrettyPrinter pp = new DefaultPrettyPrinter().withArrayIndenter(indenter)
				.withObjectIndenter(indenter);
		jg.setPrettyPrinter(pp);
	}
	jg.writeStartObject();
	for (final Resource nextSubject : graph.subjects()) {
		jg.writeObjectFieldStart(RDFJSONWriter.resourceToString(nextSubject));
		for (final IRI nextPredicate : graph.filter(nextSubject, null, null).predicates()) {
			jg.writeArrayFieldStart(nextPredicate.stringValue());
			for (final Value nextObject : graph.filter(nextSubject, nextPredicate, null).objects()) {
				// contexts are optional, so this may return empty in some
				// scenarios depending on the interpretation of the way contexts
				// work
				final Set<Resource> contexts = graph.filter(nextSubject, nextPredicate, nextObject).contexts();

				RDFJSONWriter.writeObject(nextObject, contexts, jg);
			}
			jg.writeEndArray();
		}
		jg.writeEndObject();
	}
	jg.writeEndObject();
}
 
Example #19
Source File: AbstractSPARQLJSONWriter.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public void startDocument() throws QueryResultHandlerException {
	if (!documentOpen) {
		documentOpen = true;
		headerOpen = false;
		headerComplete = false;
		tupleVariablesFound = false;
		firstTupleWritten = false;
		linksFound = false;

		if (getWriterConfig().get(BasicWriterSettings.PRETTY_PRINT)) {
			// SES-2011: Always use \n for consistency
			Indenter indenter = DefaultIndenter.SYSTEM_LINEFEED_INSTANCE;
			// By default Jackson does not pretty print, so enable this unless
			// PRETTY_PRINT setting is disabled
			DefaultPrettyPrinter pp = new DefaultPrettyPrinter().withArrayIndenter(indenter)
					.withObjectIndenter(indenter);
			jg.setPrettyPrinter(pp);
		}

		try {
			if (getWriterConfig().isSet(BasicQueryWriterSettings.JSONP_CALLBACK)) {
				// SES-1019 : Write the callbackfunction name as a wrapper for
				// the results here
				String callbackName = getWriterConfig().get(BasicQueryWriterSettings.JSONP_CALLBACK);
				jg.writeRaw(callbackName);
				jg.writeRaw("(");
			}
			jg.writeStartObject();
		} catch (IOException e) {
			throw new QueryResultHandlerException(e);
		}
	}
}
 
Example #20
Source File: PentahoAvroOutputFormat.java    From pentaho-hadoop-shims with Apache License 2.0 5 votes vote down vote up
protected void writeAvroSchemaToFile( String schemaFilename ) throws KettleFileException, IOException {
  ObjectNode schemaObjectNode = this.getSchemaObjectNode();
  if ( schemaObjectNode != null && schemaFilename != null ) {
    ObjectMapper mapper = new ObjectMapper();
    ObjectWriter writer = mapper.writer( new DefaultPrettyPrinter() );
    writer.writeValue( KettleVFS.getOutputStream( schemaFilename, variableSpace, false ), schemaObjectNode );
  }
}
 
Example #21
Source File: JSonDatabaseWriter.java    From dbsync with Apache License 2.0 5 votes vote down vote up
public JSonDatabaseWriter(final OutputStream outStream) throws IOException {
    this.mOutStream = outStream;

    JsonFactory f = new JsonFactory();
    mGen = f.createGenerator(outStream, JsonEncoding.UTF8);
    mGen.setPrettyPrinter(new DefaultPrettyPrinter());
}
 
Example #22
Source File: JSON.java    From jackson-jr with Apache License 2.0 5 votes vote down vote up
@Override
public PrettyPrinter getPrettyPrinter() {
    PrettyPrinter pp = _prettyPrinter;
    if (pp != null) {
        if (pp instanceof Instantiatable<?>) {
            pp = (PrettyPrinter) ((Instantiatable<?>) pp).createInstance();
        }
        return pp;
    }
    if (isEnabled(Feature.PRETTY_PRINT_OUTPUT)) {
        return new DefaultPrettyPrinter();
    }
    return null;
}
 
Example #23
Source File: JsonGraphFormatter.java    From depgraph-maven-plugin with Apache License 2.0 5 votes vote down vote up
private String serialize(JsonGraph jsonGraph) {
  DefaultPrettyPrinter prettyPrinter = new DefaultPrettyPrinter()
      .withObjectIndenter(new DefaultIndenter("  ", "\n"));

  ObjectWriter writer = this.objectMapper.writer(prettyPrinter);
  StringWriter jsonWriter = new StringWriter();
  try {
    writer.writeValue(jsonWriter, jsonGraph);
  } catch (IOException e) {
    // should never happen with StringWriter
    throw new IllegalStateException(e);
  }

  return jsonWriter.toString();
}
 
Example #24
Source File: AbstractJackson2HttpMessageConverter.java    From java-technology-stack with MIT License 5 votes vote down vote up
protected AbstractJackson2HttpMessageConverter(ObjectMapper objectMapper) {
	this.objectMapper = objectMapper;
	setDefaultCharset(DEFAULT_CHARSET);
	DefaultPrettyPrinter prettyPrinter = new DefaultPrettyPrinter();
	prettyPrinter.indentObjectsWith(new DefaultIndenter("  ", "\ndata:"));
	this.ssePrettyPrinter = prettyPrinter;
}
 
Example #25
Source File: AbstractQueryCommand.java    From buck with Apache License 2.0 5 votes vote down vote up
private static <T extends SortedMap<String, Object>> void printAttributesAsJson(
    ImmutableSortedMap<String, T> result, PrintStream printStream) throws IOException {
  ObjectMappers.WRITER
      .with(
          new DefaultPrettyPrinter().withArrayIndenter(DefaultIndenter.SYSTEM_LINEFEED_INSTANCE))
      // Jackson closes stream by default - we do not want it
      .without(JsonGenerator.Feature.AUTO_CLOSE_TARGET)
      .writeValue(printStream, result);

  // Jackson does not append a newline after final closing bracket. Do it to make JSON look
  // nice on console.
  printStream.println();
}
 
Example #26
Source File: ExportServiceImpl.java    From usergrid with Apache License 2.0 5 votes vote down vote up
protected JsonGenerator getJsonGenerator( File ephermal ) throws IOException {
    //TODO:shouldn't the below be UTF-16?

    JsonGenerator jg = jsonFactory.createJsonGenerator( ephermal, JsonEncoding.UTF8 );
    jg.setPrettyPrinter( new DefaultPrettyPrinter(  ) );
    jg.setCodec( new ObjectMapper() );
    return jg;
}
 
Example #27
Source File: AbstractJackson2HttpMessageConverter.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
protected void init(ObjectMapper objectMapper) {
	this.objectMapper = objectMapper;
	setDefaultCharset(DEFAULT_CHARSET);
	DefaultPrettyPrinter prettyPrinter = new DefaultPrettyPrinter();
	prettyPrinter.indentObjectsWith(new DefaultIndenter("  ", "\ndata:"));
	this.ssePrettyPrinter = prettyPrinter;
}
 
Example #28
Source File: ExportingToolBase.java    From usergrid with Apache License 2.0 5 votes vote down vote up
protected JsonGenerator getJsonGenerator( File outFile ) throws IOException {
    PrintWriter out = new PrintWriter( outFile, "UTF-8" );
    JsonGenerator jg = jsonFactory.createJsonGenerator( out );
    jg.setPrettyPrinter( new DefaultPrettyPrinter() );
    jg.setCodec( new ObjectMapper() );
    return jg;
}
 
Example #29
Source File: Java2SwaggerMojo.java    From cxf with Apache License 2.0 4 votes vote down vote up
private void generateSwaggerPayLoad() throws MojoExecutionException {

        if (outputFile == null && project != null) {
            // Put the json in target/generated/json
            // put the yaml in target/generated/yaml

            String name = null;
            if (outputFileName != null) {
                name = outputFileName;
            } else if (resourceClasses.size() == 1) {
                name = resourceClasses.iterator().next().getSimpleName();
            } else {
                name = "swagger";
            }
            outputFile = (project.getBuild().getDirectory() + "/generated/" + payload.toLowerCase() + "/" + name + "."
                    + payload.toLowerCase()).replace("/", File.separator);
        }

        FileUtils.mkDir(new File(outputFile).getParentFile());
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(outputFile))) {
            if ("json".equals(this.payload)) {
                ObjectWriter jsonWriter = mapper.writer(new DefaultPrettyPrinter());
                writer.write(jsonWriter.writeValueAsString(swagger));
            } else if ("yaml".equals(this.payload)) {
                writer.write(Yaml.pretty().writeValueAsString(swagger));
            }

        } catch (IOException e) {
            throw new MojoExecutionException(e.getMessage(), e);
        }

        // Attach the generated swagger file to the artifacts that get deployed
        // with the enclosing project
        if (attachSwagger && outputFile != null) {
            File jsonFile = new File(outputFile);
            if (jsonFile.exists()) {
                if (classifier != null) {
                    projectHelper.attachArtifact(project, payload.toLowerCase(), classifier, jsonFile);
                } else {
                    projectHelper.attachArtifact(project, payload.toLowerCase(), jsonFile);
                }

            }
        }
    }
 
Example #30
Source File: YamlJacksonFactory.java    From logging-log4j2 with Apache License 2.0 4 votes vote down vote up
@Override
protected PrettyPrinter newPrettyPrinter() {
    return new DefaultPrettyPrinter();
}