Example usage for com.fasterxml.jackson.core JsonFactory enable

List of usage examples for com.fasterxml.jackson.core JsonFactory enable

Introduction

In this page you can find the example usage for com.fasterxml.jackson.core JsonFactory enable.

Prototype

public JsonFactory enable(JsonGenerator.Feature f) 

Source Link

Document

Method for enabling specified generator features (check JsonGenerator.Feature for list of features)

Usage

From source file:com.sangupta.comparator.JSONComparer.java

/**
 * Compare two JSON string representations.
 * /*from w ww . j  av a2s  .  com*/
 * @param json1
 *            the first representation
 * 
 * @param json2
 *            the second representation
 * 
 * @return <code>true</code> if the two JSON representations represent the
 *         same object, <code>false</code> otherwise.
 * 
 * @throws JsonParseException
 *             if something fails
 * 
 * @throws JsonProcessingException
 *             if something fails
 * 
 * @throws IOException
 *             if something fails
 * 
 */
public static boolean compareJson(String json1, String json2) throws JsonProcessingException, IOException {
    if (json1 == null || json2 == null) {
        return false;
    }

    if (json1 == json2) {
        return true;
    }

    JsonFactory factory = new JsonFactory();
    factory.enable(Feature.ALLOW_COMMENTS);

    ObjectMapper mapper = new ObjectMapper();
    JsonNode node1 = mapper.readTree(json1);
    JsonNode node2 = mapper.readTree(json2);

    return node1.equals(node2);
}

From source file:com.sangupta.comparator.JSONComparer.java

/**
 * Compare two JSON representations./* www  .  j  a  v  a 2s  .c  o m*/
 * 
 * @param reader1
 *            the first representation
 * 
 * @param reader2
 *            the second representation
 * 
 * @return <code>true</code> if the two JSON representations represent the
 *         same object, <code>false</code> otherwise.
 * 
 * @throws JsonParseException
 *             if something fails
 * 
 * @throws JsonProcessingException
 *             if something fails
 * 
 * @throws IOException
 *             if something fails
 * 
 */
public static boolean compareJson(Reader reader1, Reader reader2) throws JsonProcessingException, IOException {
    if (reader1 == null || reader2 == null) {
        return false;
    }

    if (reader1 == reader2) {
        return true;
    }

    JsonFactory factory = new JsonFactory();
    factory.enable(Feature.ALLOW_COMMENTS);

    ObjectMapper mapper = new ObjectMapper();
    JsonNode node1 = mapper.readTree(reader1);
    JsonNode node2 = mapper.readTree(reader2);

    return node1.equals(node2);
}

From source file:com.sangupta.comparator.JSONComparer.java

/**
 * Compare two JSON representations.//from w  w w.j a va 2  s  .  c  o  m
 * 
 * @param stream1
 *            the first representation
 * 
 * @param stream2
 *            the second representation
 * 
 * @return <code>true</code> if the two JSON representations represent the
 *         same object, <code>false</code> otherwise.
 * 
 * @throws JsonParseException
 *             if something fails
 * 
 * @throws JsonProcessingException
 *             if something fails
 * 
 * @throws IOException
 *             if something fails
 * 
 */
public static boolean compareJson(InputStream stream1, InputStream stream2)
        throws JsonProcessingException, IOException {
    if (stream1 == null || stream2 == null) {
        return false;
    }

    if (stream1 == stream2) {
        return true;
    }

    JsonFactory factory = new JsonFactory();
    factory.enable(Feature.ALLOW_COMMENTS);

    ObjectMapper mapper = new ObjectMapper();
    JsonNode node1 = mapper.readTree(stream1);
    JsonNode node2 = mapper.readTree(stream2);

    return node1.equals(node2);
}

From source file:com.rockagen.commons.util.JsonUtil.java

/**
 * return a JsonFactory if exist,else new JsonFactory
 * /*from   ww  w .  j  av  a 2 s.c om*/
 * @return JsonFactory
 */
public static JsonFactory getJsonFactory() {

    JsonFactory jsonFactory = threadJsonFactory.get();
    if (jsonFactory == null) {
        jsonFactory = new JsonFactory();
        // JsonParser.Feature for configuring parsing settings:
        // to allow C/C++ style comments in JSON (non-standard, disabled by
        // default)
        jsonFactory.enable(JsonParser.Feature.ALLOW_COMMENTS);
        // to allow (non-standard) unquoted field names in JSON:
        jsonFactory.disable(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES);
        // to allow use of apostrophes (single quotes), non standard
        jsonFactory.disable(JsonParser.Feature.ALLOW_SINGLE_QUOTES);

        // JsonGenerator.Feature for configuring low-level JSON generation:

        // no escaping of non-ASCII characters:
        jsonFactory.disable(JsonGenerator.Feature.ESCAPE_NON_ASCII);
        threadJsonFactory.set(jsonFactory);

    }
    return jsonFactory;
}

From source file:org.jahia.loganalyzer.writers.internal.JSONLogEntryWriter.java

public JSONLogEntryWriter(File htmlFile) throws IOException {
    JsonFactory factory = new JsonFactory();
    // configure, if necessary:
    factory.enable(JsonParser.Feature.ALLOW_COMMENTS);
    fileWriter = new FileWriter(htmlFile);
    jsonGenerator = factory.createGenerator(fileWriter);
    jsonGenerator.setCodec(new ObjectMapper());
    jsonGenerator.useDefaultPrettyPrinter();
    jsonGenerator.writeStartArray();/* w  ww.ja v a 2 s  .  c o m*/
}

From source file:com.ethlo.geodata.importer.file.FileIpLookupImporter.java

@Override
public long importData() throws IOException {
    final Map.Entry<Date, File> ipDataFile = super.fetchResource(DataType.IP, url);
    final AtomicInteger count = new AtomicInteger(0);

    final File csvFile = ipDataFile.getValue();
    final long total = IoUtils.lineCount(csvFile);
    final ProgressListener prg = new ProgressListener(
            l -> publish(new DataLoadedEvent(this, DataType.IP, Operation.IMPORT, l, total)));

    final IpLookupImporter ipLookupImporter = new IpLookupImporter(csvFile);

    final JsonFactory f = new JsonFactory();
    f.enable(JsonGenerator.Feature.ESCAPE_NON_ASCII);
    f.disable(JsonGenerator.Feature.AUTO_CLOSE_TARGET);
    final ObjectMapper mapper = new ObjectMapper(f);

    final byte newLine = (byte) "\n".charAt(0);

    logger.info("Writing IP data to file {}", getFile().getAbsolutePath());
    try (final OutputStream out = new BufferedOutputStream(new FileOutputStream(getFile()))) {
        ipLookupImporter.processFile(entry -> {
            final String strGeoNameId = findMapValue(entry, "geoname_id", "represented_country_geoname_id",
                    "registered_country_geoname_id");
            final String strGeoNameCountryId = findMapValue(entry, "represented_country_geoname_id",
                    "registered_country_geoname_id");
            final Long geonameId = strGeoNameId != null ? Long.parseLong(strGeoNameId) : null;
            final Long geonameCountryId = strGeoNameCountryId != null ? Long.parseLong(strGeoNameCountryId)
                    : null;/*w ww.  j av  a 2 s . c o m*/
            if (geonameId != null) {
                final SubnetUtils u = new SubnetUtils(entry.get("network"));
                final long lower = UnsignedInteger
                        .fromIntBits(InetAddresses
                                .coerceToInteger(InetAddresses.forString(u.getInfo().getLowAddress())))
                        .longValue();
                final long upper = UnsignedInteger
                        .fromIntBits(InetAddresses
                                .coerceToInteger(InetAddresses.forString(u.getInfo().getHighAddress())))
                        .longValue();
                final Map<String, Object> paramMap = new HashMap<>(5);
                paramMap.put("geoname_id", geonameId);
                paramMap.put("geoname_country_id", geonameCountryId);
                paramMap.put("first", lower);
                paramMap.put("last", upper);

                try {
                    mapper.writeValue(out, paramMap);
                    out.write(newLine);
                } catch (IOException exc) {
                    throw new DataAccessResourceFailureException(exc.getMessage(), exc);
                }
            }

            if (count.get() % 100_000 == 0) {
                logger.info("Processed {}", count.get());
            }

            count.getAndIncrement();

            prg.update();
        });
    }

    return total;
}

From source file:com.bazaarvoice.jsonpps.PrettyPrintJson.java

public void prettyPrint(List<File> inputFiles, File outputFile) throws IOException {
    JsonFactory factory = new JsonFactory();
    factory.disable(JsonFactory.Feature.INTERN_FIELD_NAMES);
    if (!strict) {
        factory.enable(JsonParser.Feature.ALLOW_BACKSLASH_ESCAPING_ANY_CHARACTER);
        factory.enable(JsonParser.Feature.ALLOW_COMMENTS);
        factory.enable(JsonParser.Feature.ALLOW_NON_NUMERIC_NUMBERS);
        factory.enable(JsonParser.Feature.ALLOW_NUMERIC_LEADING_ZEROS);
        factory.enable(JsonParser.Feature.ALLOW_SINGLE_QUOTES);
        factory.enable(JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS);
        factory.enable(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES);
    }//from   www. j  a va  2  s .c o  m

    ObjectMapper mapper = null;
    if (sortKeys) {
        mapper = new ObjectMapper(factory);
        mapper.enable(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS);
        mapper.disable(SerializationFeature.FLUSH_AFTER_WRITE_VALUE);
    }

    // Open the output stream and create the Json emitter.
    JsonGenerator generator;
    File tempOutputFile = null;
    if (STDINOUT.equals(outputFile)) {
        generator = factory.createGenerator(stdout, JsonEncoding.UTF8);
    } else if (!caseInsensitiveContains(inputFiles, outputFile)) {
        generator = factory.createGenerator(outputFile, JsonEncoding.UTF8);
    } else {
        // Writing to an input file.. use a temp file to stage the output until we're done.
        tempOutputFile = getTemporaryFileFor(outputFile);
        generator = factory.createGenerator(tempOutputFile, JsonEncoding.UTF8);
    }
    try {
        // Separate top-level objects by a newline in the output.
        String newline = System.getProperty("line.separator");
        generator.setPrettyPrinter(new DefaultPrettyPrinter(newline));

        if (wrap) {
            generator.writeStartArray();
        }

        for (File inputFile : inputFiles) {
            JsonParser parser;
            if (STDINOUT.equals(inputFile)) {
                parser = factory.createParser(stdin);
            } else {
                parser = factory.createParser(inputFile);
            }
            try {
                while (parser.nextToken() != null) {
                    copyCurrentStructure(parser, mapper, 0, generator);
                }
            } finally {
                parser.close();
            }
        }

        if (wrap) {
            generator.writeEndArray();
        }

        generator.writeRaw(newline);
    } finally {
        generator.close();
    }
    if (tempOutputFile != null && !tempOutputFile.renameTo(outputFile)) {
        System.err.println("error: unable to rename temporary file to output: " + outputFile);
        System.exit(1);
    }
}