List of usage examples for com.fasterxml.jackson.core JsonFactory JsonFactory
public JsonFactory()
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;/*from www .j a v a2s.co 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.joliciel.jochre.search.highlight.HighlightManagerImpl.java
@Override public void highlight(Highlighter highlighter, Set<Integer> docIds, Set<String> fields, Writer out) { try {//ww w.j a v a 2s . c o m Map<Integer, Set<HighlightTerm>> termMap = highlighter.highlight(docIds, fields); JsonFactory jsonFactory = new JsonFactory(); JsonGenerator jsonGen = jsonFactory.createGenerator(out); jsonGen.writeStartObject(); for (int docId : docIds) { Document doc = indexSearcher.doc(docId); jsonGen.writeObjectFieldStart(doc.get("id")); jsonGen.writeStringField("path", doc.get("path")); jsonGen.writeNumberField("docId", docId); jsonGen.writeArrayFieldStart("terms"); for (HighlightTerm term : termMap.get(docId)) { fields.add(term.getField()); term.toJson(jsonGen, df); } jsonGen.writeEndArray(); if (includeText) { for (String field : fields) { jsonGen.writeObjectFieldStart("field" + field); Set<HighlightTerm> terms = termMap.get(docId); jsonGen.writeStringField("contents", this.displayHighlights(docId, field, terms)); jsonGen.writeEndObject(); } } jsonGen.writeEndObject(); } jsonGen.writeEndObject(); jsonGen.flush(); } catch (IOException ioe) { LogUtils.logError(LOG, ioe); throw new RuntimeException(ioe); } }
From source file:org.odlabs.wiquery.ui.autocomplete.AutocompleteComponent.java
@Override protected void onBeforeRenderAutocomplete(Autocomplete<?> autocomplete) { StringWriter sw = new StringWriter(); try {/*from ww w . java 2 s.c o m*/ JsonGenerator gen = new JsonFactory().createGenerator(sw); List<Object> json = new ArrayList<Object>(); T defaultValue = AutocompleteComponent.this.getModelObject(); AutocompleteJson value = null; Integer index = 0; for (T obj : AutocompleteComponent.this.list.getObject()) { index++; value = newAutocompleteJson(index, obj); json.add(value); if (obj.equals(defaultValue)) { autocomplete.setDefaultModelObject(value.getLabel()); getAutocompleteHidden().setModelObject(value.getValueId()); } } new ObjectMapper().writeValue(gen, json); } catch (IOException e) { throw new WicketRuntimeException(e); } autocomplete.getOptions().put("source", sw.toString()); }
From source file:cc.arduino.packages.discoverers.PluggableDiscovery.java
@Override public void run() { // this method is started as a new thread, it will constantly listen // to the discovery tool and keep track of the discovered ports try {/* w w w .j a va 2s.c o m*/ start(); InputStream input = program.getInputStream(); JsonFactory factory = new JsonFactory(); JsonParser parser = factory.createParser(input); ObjectMapper mapper = new ObjectMapper(); mapper.setVisibility(PropertyAccessor.ALL, Visibility.NONE); mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); while (program != null && program.isAlive()) { JsonNode tree = mapper.readTree(parser); if (tree == null) { if (program != null && program.isAlive()) { System.err.println(format("{0}: Invalid json message", discoveryName)); } break; } debug("Received json: " + tree); processJsonNode(mapper, tree); } debug("thread exit normally"); } catch (InterruptedException e) { debug("thread exit by interrupt"); e.printStackTrace(); } catch (Exception e) { debug("thread exit other exception"); e.printStackTrace(); } try { stop(); } catch (Exception e) { } }
From source file:io.apiman.manager.api.exportimport.json.JsonImportReader.java
/** * Constructor./*from ww w. j a v a2 s . c o m*/ * @param logger the apiman logger * @param in the input stream * @throws JsonParseException * @throws IOException */ public JsonImportReader(IApimanLogger logger, InputStream in) throws IOException { this.logger = logger; this.in = in; jp = new JsonFactory().createParser(in); jp.setCodec(new ObjectMapper()); }
From source file:com.ryan.ryanreader.jsonwrap.JsonValue.java
/** * Begins parsing a JSON stream into a tree structure. The JsonValue object * created contains the value at the root of the tree. * //from ww w .j a v a 2 s .com * This constructor will block until the first JSON token is received. To * continue building the tree, the "build" method (inherited from * JsonBuffered) must be called in another thread. * * @param source * The source of incoming JSON data. * @throws java.io.IOException */ public JsonValue(final InputStream source) throws IOException { this(new JsonFactory().createParser(source)); }
From source file:eu.project.ttc.readers.TermSuiteJsonCasSerializer.java
public static void serialize(Writer writer, JCas jCas) throws IOException { JsonFactory jsonFactory = new JsonFactory(); JsonGenerator jg = jsonFactory.createGenerator(writer); jg.useDefaultPrettyPrinter();/*w w w . ja va2 s . co m*/ jg.writeStartObject(); jg.writeFieldName(F_SDI); writeSDI(jg, jCas); jg.writeFieldName(F_WORD_ANNOTATIONS); writeWordAnnotations(jg, jCas); jg.writeFieldName(F_TERM_OCC_ANNOTATIONS); writeTermOccAnnotations(jg, jCas); jg.writeFieldName(F_FIXED_EXPRESSIONS); writeFixedExpressions(jg, jCas); writeCoveredText(jg, jCas); jg.writeEndObject(); jg.flush(); writer.close(); }
From source file:com.sangupta.comparator.JSONComparer.java
/** * Compare two JSON representations.//from w ww . jav a 2 s.com * * @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.comcast.cdn.traffic_control.traffic_router.core.external.SteeringTest.java
License:asdf
JsonNode getJsonForResourcePath(String resourcePath) throws IOException { ObjectMapper objectMapper = new ObjectMapper(new JsonFactory()); InputStream inputStream = getClass().getClassLoader().getResourceAsStream(resourcePath); if (inputStream == null) { fail("Could not find file '" + resourcePath + "' needed for test from the current classpath as a resource!"); }//from w w w . ja va 2 s. c o m return objectMapper.readTree(inputStream).get("response").get(0); }
From source file:com.adobe.communities.ugc.migration.importer.SocialGraphImportServlet.java
/** * The post operation accepts a json file, parses it and applies the social graph relationships to local profiles * @param request - the request//w w w. ja v a 2 s .c o m * @param response - the response * @throws javax.servlet.ServletException * @throws java.io.IOException */ protected void doPost(final SlingHttpServletRequest request, final SlingHttpServletResponse response) throws ServletException, IOException { final ResourceResolver resolver = request.getResourceResolver(); UGCImportHelper.checkUserPrivileges(resolver, rrf); final RequestParameter[] fileRequestParameters = request.getRequestParameters("file"); if (fileRequestParameters != null && fileRequestParameters.length > 0 && !fileRequestParameters[0].isFormField() && fileRequestParameters[0].getFileName().endsWith(".json")) { final InputStream inputStream = fileRequestParameters[0].getInputStream(); final JsonParser jsonParser = new JsonFactory().createParser(inputStream); JsonToken token = jsonParser.nextToken(); // get the first token if (token.equals(JsonToken.START_OBJECT)) { importFile(jsonParser, request); } else { throw new ServletException("Expected a start object token, got " + token); } } else { throw new ServletException("Expected to get a json file in post request"); } }