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

The following examples show how to use com.fasterxml.jackson.core.util.MinimalPrettyPrinter. 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: JsonRecordWriter.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
@Override
public void startPartition(WritePartition partition) throws Exception {
  // close previous partition if open.
  if(this.partition != null){
    doClose();
  }
  this.partition = partition;

  try {
    this.fileName = fs.canonicalizePath(partition.qualified(location, prefix + "_0." + extension));
    stream = new DataOutputStream(fs.create(fileName));
    jsonGenerator = factory.createGenerator((OutputStream) stream)
      .disable(JsonGenerator.Feature.AUTO_CLOSE_TARGET)
      .enable(JsonGenerator.Feature.FLUSH_PASSED_TO_STREAM)
      .useDefaultPrettyPrinter();

    if (uglify) {
      jsonGenerator = jsonGenerator.setPrettyPrinter(new MinimalPrettyPrinter(LINE_FEED));
    }
    if(useExtendedOutput){
      gen = new ExtendedJsonOutput(jsonGenerator);
    }else{
      gen = new BasicJsonOutput(jsonGenerator);
    }
    logger.debug("Created file: {}", fileName);
  } catch (IOException ex) {
    throw UserException.dataWriteError(ex)
      .message("Failure writing JSON file %s.", fileName)
      .build(logger);
  }

}
 
Example #2
Source File: JacksonJsonLayout.java    From log4j2-elasticsearch with Apache License 2.0 5 votes vote down vote up
protected ObjectWriter createConfiguredWriter(List<JacksonMixIn> mixins) {

            ObjectMapper objectMapper = createDefaultObjectMapper();
            objectMapper.registerModule(new ExtendedLog4j2JsonModule());

            if (useAfterburner) {
                // com.fasterxml.jackson.module:jackson-module-afterburner required here
                new JacksonAfterburnerModuleConfigurer().configure(objectMapper);
            }

            for (JacksonMixIn mixin : mixins) {
                objectMapper.addMixIn(mixin.getTargetClass(), mixin.getMixInClass());
            }

            ValueResolver valueResolver = createValueResolver();

            for (VirtualProperty property : virtualProperties) {
                if (!property.isDynamic()) {
                    property.setValue(valueResolver.resolve(property.getValue()));
                }
            }

            SerializationConfig customConfig = objectMapper.getSerializationConfig()
                    .with(new JacksonHandlerInstantiator(
                            virtualProperties,
                            valueResolver,
                            virtualPropertyFilters
                    ));

            objectMapper.setConfig(customConfig);

            return objectMapper.writer(new MinimalPrettyPrinter());

        }
 
Example #3
Source File: DataflowWorkerLoggingHandler.java    From beam with Apache License 2.0 5 votes vote down vote up
private void createOutputStream() throws IOException {
  CountingOutputStream stream = new CountingOutputStream(outputStreamFactory.get());
  generator = generatorFactory.createGenerator(stream, JsonEncoding.UTF8);
  counter = stream;

  // Avoid 1 space indent for every line. We already add a newline after each log record.
  generator.setPrettyPrinter(new MinimalPrettyPrinter(""));
}
 
Example #4
Source File: JsonRecordWriter.java    From Bats with Apache License 2.0 4 votes vote down vote up
@Override
public void init(Map<String, String> writerOptions) throws IOException {
  this.location = writerOptions.get("location");
  this.prefix = writerOptions.get("prefix");
  this.fieldDelimiter = writerOptions.get("separator");
  this.extension = writerOptions.get("extension");
  this.useExtendedOutput = Boolean.parseBoolean(writerOptions.get("extended"));
  this.skipNullFields = Boolean.parseBoolean(writerOptions.get("skipnulls"));
  final boolean uglify = Boolean.parseBoolean(writerOptions.get("uglify"));

  this.fs = FileSystem.get(fsConf);

  Path fileName = new Path(location, prefix + "_" + index + "." + extension);
  try {
    // json writer does not support partitions, so only one file can be created
    // and thus only one location should be deleted in case of abort
    // to ensure that our writer was the first to create output file,
    // we create empty output file first and fail if file exists
    cleanUpLocation = storageStrategy.createFileAndApply(fs, fileName);

    // since empty output file will be overwritten (some file systems may restrict append option)
    // we need to re-apply file permission
    stream = fs.create(fileName);
    storageStrategy.applyToFile(fs, fileName);

    JsonGenerator generator = factory.createGenerator(stream).useDefaultPrettyPrinter()
        .configure(JsonGenerator.Feature.QUOTE_NON_NUMERIC_NUMBERS,
            !Boolean.parseBoolean(writerOptions.get("enableNanInf")));
    if (uglify) {
      generator = generator.setPrettyPrinter(new MinimalPrettyPrinter(LINE_FEED));
    }
    if(useExtendedOutput){
      gen = new ExtendedJsonOutput(generator);
    }else{
      gen = new BasicJsonOutput(generator);
    }
    logger.debug("Created file: {}", fileName);
  } catch (IOException ex) {
    logger.error("Unable to create file: " + fileName, ex);
    throw ex;
  }
}
 
Example #5
Source File: JacksonFactory.java    From summerframework with Apache License 2.0 4 votes vote down vote up
@Override
protected PrettyPrinter newCompactPrinter() {
    return new MinimalPrettyPrinter();
}
 
Example #6
Source File: LoggedEventExporter.java    From inception with Apache License 2.0 4 votes vote down vote up
@Override
public void exportData(ProjectExportRequest aRequest, ProjectExportTaskMonitor aMonitor,
        ExportedProject aExProject, File aFile)
    throws Exception
{
    Project project = aRequest.getProject();
    
    AtomicInteger eventCount = new AtomicInteger(0);
    Set<Long> missingDocuments = new HashSet<>();
    AtomicInteger droppedEvents = new AtomicInteger(0);
    
    // Set up a map of document IDs to document names because we export by name and not
    // by ID.
    Map<Long, String> documentNameIndex = new HashMap<>();
    documentService.listSourceDocuments(project).forEach(doc -> 
        documentNameIndex.put(doc.getId(), doc.getName())
    );
    
    File eventLog = new File(aFile, EVENT_LOG);
    eventLog.createNewFile();
    try (JsonGenerator jGenerator = new ObjectMapper().getFactory()
            .createGenerator(new FileOutputStream(eventLog), JsonEncoding.UTF8)) {

        jGenerator.setPrettyPrinter(new MinimalPrettyPrinter("\n"));
        
        // Stream data
        eventRepository.forEachLoggedEvent(project, event -> {
            String documentName = null;
            // If the document ID is -1, then there is no document linked up to this event.
            // In this case, we do not need to try resolving the IDs to a name.
            if (event.getDocument() != -1) {
                documentName = documentNameIndex.get(event.getDocument());
                if (documentName == null) {
                    // The document has been deleted from the project so we cannot link up
                    // events back up to this document during import. So since this is not
                    // possible, we can even save ourselves the effort of exporting the logged
                    // events on a document that doesn't exist anymore.
                    missingDocuments.add(event.getDocument());
                    droppedEvents.incrementAndGet();
                    return;
                }
            }

            // Transfer data over to DTO
            ExportedLoggedEvent exportedEvent = new ExportedLoggedEvent();
            exportedEvent.setId(event.getId());
            exportedEvent.setCreated(event.getCreated());
            exportedEvent.setDocumentName(documentName);
            exportedEvent.setEvent(event.getEvent());
            exportedEvent.setAnnotator(event.getAnnotator());
            exportedEvent.setUser(event.getUser());
            exportedEvent.setDetails(event.getDetails());
            
            // Write DTO
            try {
                jGenerator.writeObject(exportedEvent);
            }
            catch (IOException e) {
                throw new RuntimeException(e);
            }
            
            eventCount.incrementAndGet();
        });
    }
    
    LOG.info("Exported [{}] logged events for project [{}]", eventCount.get(),
            project.getName());
    if (!missingDocuments.isEmpty()) {
        LOG.info("Skipped [{}] logged events for [{}] documents no longer existing",
                droppedEvents.get(), missingDocuments.size());
    }
}
 
Example #7
Source File: InternalConfigStateController.java    From springboot-shiro-cas-mybatis with MIT License 4 votes vote down vote up
/**
 * Instantiates a new Bean object json serializer.
 */
public BeanObjectJsonSerializer() {
    super(new MinimalPrettyPrinter());
}
 
Example #8
Source File: JsonJacksonFactory.java    From curiostack with MIT License 4 votes vote down vote up
@Override
protected PrettyPrinter newCompactPrinter() {
  return new MinimalPrettyPrinter();
}
 
Example #9
Source File: ProctorController.java    From proctor with Apache License 2.0 4 votes vote down vote up
/**
 * set spring Model attribute for view
 *
 * @return view spring name
 */
private String getArtifactForView(final Model model, final Environment branch, final ProctorView view) {
    final TestMatrixVersion testMatrix = getCurrentMatrix(branch);
    final TestMatrixDefinition testMatrixDefinition;
    if (testMatrix == null || testMatrix.getTestMatrixDefinition() == null) {
        testMatrixDefinition = new TestMatrixDefinition();
    } else {
        testMatrixDefinition = testMatrix.getTestMatrixDefinition();
    }

    model.addAttribute("branch", branch);
    model.addAttribute("session",
            SessionViewModel.builder()
                    .setUseCompiledCSS(getConfiguration().isUseCompiledCSS())
                    .setUseCompiledJavaScript(getConfiguration().isUseCompiledJavaScript())
                    // todo get the appropriate js compile / non-compile url
                    .build());
    model.addAttribute("testMatrixVersion", testMatrix);

    final Set<String> testNames = testMatrixDefinition.getTests().keySet();
    final Map<String, List<Revision>> allHistories = getAllHistories(branch);
    final Map<String, Long> updatedTimeMap = Maps.toMap(testNames, testName -> {
        final Date updatedDate = getUpdatedDate(allHistories, testName);
        if (updatedDate != null) {
            return updatedDate.getTime();
        } else {
            return FALLBACK_UPDATED_TIME;
        }
    });
    model.addAttribute("updatedTimeMap", updatedTimeMap);

    final String errorMessage = "Apparently not impossible exception generating JSON";
    try {
        final String testMatrixJson = OBJECT_MAPPER.writer(new MinimalPrettyPrinter()).writeValueAsString(testMatrixDefinition);
        model.addAttribute("testMatrixDefinition", testMatrixJson);

        final Map<String, Map<String, String>> colors = Maps.newHashMap();
        for (final Entry<String, TestDefinition> entry : testMatrixDefinition.getTests().entrySet()) {
            final Map<String, String> testColors = Maps.newHashMap();
            for (final TestBucket bucket : entry.getValue().getBuckets()) {
                final long hashedBucketName = Hashing.md5().newHasher().putString(bucket.getName(), Charsets.UTF_8).hash().asLong();
                final int color = ((int) (hashedBucketName & 0x00FFFFFFL)) | 0x00808080; //  convert a hash of the bucket to a color, but keep it light
                testColors.put(bucket.getName(), Integer.toHexString(color));
            }
            colors.put(entry.getKey(), testColors);
        }
        model.addAttribute("colors", colors);

        return view.getName();
    } catch (final IOException e) {
        LOGGER.error(errorMessage, e);
        model.addAttribute("exception", toString(e));
    }
    model.addAttribute("error", errorMessage);
    return ProctorView.ERROR.getName();
}
 
Example #10
Source File: YamlJacksonFactory.java    From logging-log4j2 with Apache License 2.0 4 votes vote down vote up
@Override
protected PrettyPrinter newCompactPrinter() {
    return new MinimalPrettyPrinter();
}
 
Example #11
Source File: JsonJacksonFactory.java    From logging-log4j2 with Apache License 2.0 4 votes vote down vote up
@Override
protected PrettyPrinter newCompactPrinter() {
    return new MinimalPrettyPrinter();
}