List of usage examples for com.fasterxml.jackson.core JsonFactory createParser
public JsonParser createParser(String content) throws IOException, JsonParseException
From source file:org.labkey.freezerpro.export.FreezerProCommandResonse.java
public List<Map<String, Object>> loadData() { List<Map<String, Object>> data = new ArrayList<>(); try {//from www .j a va2 s .c o m JsonFactory factory = new JsonFactory(); new ObjectMapper(factory); _parser = factory.createParser(_text); // locate the data array if (!ensureDataNode(_parser, _dataNodeName)) { if (_job != null) _job.error("Unable to locate data in the returned response: " + _text); throw new IOException("Unable to locate data in the returned response: " + _text); } // parse the data array parseDataArray(_parser, data); } catch (IOException e) { throw new RuntimeException(e); } return data; }
From source file:net.troja.eve.crest.CrestDataProcessor.java
private <T> String processData(final CrestApiProcessor<T> processor, final CrestContainer<T> container, final String data) { String next = null;/* w ww.j ava2 s. co m*/ try { final JsonFactory parserFactory = new JsonFactory(); final JsonParser jsonParser = parserFactory.createParser(data); jsonParser.nextToken(); while (jsonParser.nextToken() != JsonToken.END_OBJECT) { final String fieldname = jsonParser.getCurrentName(); jsonParser.nextToken(); switch (fieldname) { case "totalCount": container.setTotalCount(jsonParser.getIntValue()); break; case "pageCount": container.setPageCount(jsonParser.getIntValue()); break; case "items": processItems(processor, container, jsonParser); break; case "next": next = processNext(jsonParser); break; default: break; } } } catch (final IOException e) { if (LOGGER.isWarnEnabled()) { LOGGER.warn("Problems while parsing json data: " + e.getMessage(), e); } } return next; }
From source file:org.helm.notation2.wsadapter.MonomerWSSaver.java
/** * Adds or updates a single monomer to the monomer store using the URL configured in {@code MonomerStoreConfiguration} * ./*w ww . ja v a 2s . c o m*/ * * @param monomer to save */ public String saveMonomerToStore(Monomer monomer) { String res = ""; CloseableHttpResponse response = null; try { response = WSAdapterUtils.putResource(monomer.toJSON(), MonomerStoreConfiguration.getInstance().getWebserviceNucleotidesPutFullURL()); LOG.debug(response.getStatusLine().toString()); JsonFactory jsonf = new JsonFactory(); InputStream instream = response.getEntity().getContent(); JsonParser jsonParser = jsonf.createParser(instream); while (!jsonParser.isClosed()) { JsonToken jsonToken = jsonParser.nextToken(); if (JsonToken.FIELD_NAME.equals(jsonToken)) { String fieldName = jsonParser.getCurrentName(); LOG.debug("Field name: " + fieldName); jsonParser.nextToken(); if (fieldName.equals("monomerShortName")) { res = jsonParser.getValueAsString(); break; } } } EntityUtils.consume(response.getEntity()); } catch (Exception e) { LOG.error("Saving monomer failed!", e); return ""; } finally { try { if (response != null) { response.close(); } } catch (IOException e) { LOG.debug("Closing resources failed.", e); return res; } } return res; }
From source file:org.zalando.logbook.JsonHttpLogFormatter.java
private String compactJson(final String json) throws IOException { if (isAlreadyCompacted(json)) { return json; }/*from w ww . j a v a 2 s.c o m*/ final StringWriter output = new StringWriter(); final JsonFactory factory = mapper.getFactory(); final JsonParser parser = factory.createParser(json); final JsonGenerator generator = factory.createGenerator(output); // https://github.com/jacoco/jacoco/wiki/FilteringOptions //noinspection TryFinallyCanBeTryWithResources - jacoco can't handle try-with correctly try { while (parser.nextToken() != null) { generator.copyCurrentEvent(parser); } } finally { generator.close(); } return output.toString(); }
From source file:com.salmon.security.xacml.demo.springmvc.rest.controller.MarketPlacePopulatorController.java
@ExceptionHandler(HttpMessageNotReadableException.class) @ResponseStatus(HttpStatus.BAD_REQUEST)/*w w w .j a v a2 s . c om*/ public void whenPayloadIsStrange(HttpServletRequest request, HttpMessageNotReadableException ex) { StringBuilder sb = new StringBuilder("REQUEST PARTS: "); LOG.info("************************ JSON ERROR ************************ "); LOG.info("ContentType " + request.getContentType()); LOG.info("ContentLength " + request.getContentLength()); StringBuffer jb = new StringBuffer(); String line = null; try { BufferedReader reader = request.getReader(); while ((line = reader.readLine()) != null) jb.append(line); } catch (Exception e) { /*report an error*/ } LOG.info("************************ JSON PARSING ************************ "); LOG.info("Payload: " + jb.toString()); try { ObjectMapper mapper = new ObjectMapper(); JsonFactory factory = mapper.getFactory(); JsonParser jp = factory.createParser(jb.toString()); JsonNode actualObj = mapper.readTree(jp); LOG.info("JSON OBJECT CREATED: " + actualObj.toString()); ObjectMapper driverMapper = new ObjectMapper(); Driver jsonDriver = driverMapper.readValue(actualObj.toString(), Driver.class); LOG.info("DRIVER OBJECT CREATED: " + jsonDriver.toString()); } catch (Exception e) { LOG.error("JSON Parsing Exception " + e.getMessage()); } }
From source file:com.ntsync.shared.RawContact.java
/** * Creates and returns an instance of the RawContact from encrypted data * /* w w w . j a va 2 s . c o m*/ * */ public static RawContact valueOf(String rowId, Map<Byte, ByteBuffer> values, Key privateKey) throws InvalidKeyException { try { String serverContactId = null; long rawContactId = -1; if (values.containsKey(ContactConstants.SERVERROW_ID)) { serverContactId = readRawString(values.get(ContactConstants.SERVERROW_ID)); } String lastModStr = readRawString(values.get(ContactConstants.MODIFIED)); Date lastModified = null; if (lastModStr != null) { lastModified = new Date(Long.parseLong(lastModStr)); } if (serverContactId == null || !serverContactId.equals(rowId)) { // If ServerContactId is different, then rowId is the clientId rawContactId = Long.parseLong(rowId); } if (serverContactId == null && rawContactId < 0) { throw new IllegalArgumentException("Missing RowId in data"); } AEADBlockCipher cipher = CryptoHelper.getCipher(); final boolean deleted = values.containsKey(ContactConstants.DELETED); final String textData = CryptoHelper.decodeStringValue(ContactConstants.TEXTDATA, values, cipher, privateKey); if (textData == null && !deleted) { LOG.error("No textdata found for row with Id:" + rowId); return null; } String fullName = null; String firstName = null; String lastName = null; String middleName = null; String prefixName = null; String suffixName = null; String phonecticFirst = null; String phonecticMiddle = null; String phonecticLast = null; List<String> groupSourceIds = null; String note = null; List<ListRawData<PhoneType>> phones = null; List<ListRawData<EmailType>> emails = null; List<ListRawData<WebsiteType>> websites = null; List<ListRawData<EventType>> events = null; List<ListRawData<RelationType>> relations = null; List<ListRawData<SipAddressType>> sipaddresses = null; List<ListRawData<NicknameType>> nicknames = null; List<RawAddressData> addresses = null; List<RawImData> imAddresses = null; RawOrganizationData organization = null; boolean photoSuperPrimary = false; boolean starred = false; String customRingtone = null; boolean sendToVoiceMail = false; if (!SyncDataHelper.isEmpty(textData)) { JsonFactory fac = new JsonFactory(); JsonParser jp = fac.createParser(textData); jp.nextToken(); while (jp.nextToken() != JsonToken.END_OBJECT) { String fieldname = jp.getCurrentName(); // move to value, or START_OBJECT/START_ARRAY jp.nextToken(); if (ContactConstants.STRUCTUREDNAME.equals(fieldname)) { while (jp.nextToken() != JsonToken.END_OBJECT) { String namefield = jp.getCurrentName(); // move to value if (jp.nextToken() == null) { throw new JsonParseException("Invalid JSON-Structure. End of Object missing.", jp.getCurrentLocation()); } if (ContactConstants.DISPLAY_NAME.equals(namefield)) { fullName = jp.getValueAsString(); } else if (ContactConstants.FAMILY_NAME.equals(namefield)) { lastName = jp.getValueAsString(); } else if (ContactConstants.GIVEN_NAME.equals(namefield)) { firstName = jp.getValueAsString(); } else if (ContactConstants.MIDDLE_NAME.equals(namefield)) { middleName = jp.getValueAsString(); } else if (ContactConstants.SUFFIX_NAME.equals(namefield)) { suffixName = jp.getValueAsString(); } else if (ContactConstants.PREFIX_NAME.equals(namefield)) { prefixName = jp.getValueAsString(); } else if (ContactConstants.PHONETIC_FAMILY.equals(namefield)) { phonecticLast = jp.getValueAsString(); } else if (ContactConstants.PHONETIC_GIVEN.equals(namefield)) { phonecticFirst = jp.getValueAsString(); } else if (ContactConstants.PHONETIC_MIDDLE.equals(namefield)) { phonecticMiddle = jp.getValueAsString(); } else { LOG.error("Unrecognized structurednamefield for row with Id:" + rowId + " Fieldname:" + fieldname); break; } } } else if (ContactConstants.STRUCTUREDPOSTAL.equals(fieldname)) { addresses = readAddressList(rowId, addresses, jp); } else if (ContactConstants.PHONE.equals(fieldname)) { phones = readJsonList(rowId, phones, jp, fieldname, PhoneType.TYPE_OTHER, PhoneType.class); } else if (ContactConstants.EMAIL.equals(fieldname)) { emails = readJsonList(rowId, emails, jp, fieldname, EmailType.TYPE_OTHER, EmailType.class); } else if (ContactConstants.WEBSITE.equals(fieldname)) { websites = readJsonList(rowId, websites, jp, fieldname, WebsiteType.TYPE_OTHER, WebsiteType.class); } else if (ContactConstants.EVENT.equals(fieldname)) { events = readJsonList(rowId, events, jp, fieldname, EventType.TYPE_OTHER, EventType.class); } else if (ContactConstants.RELATION.equals(fieldname)) { relations = readJsonList(rowId, relations, jp, fieldname, RelationType.TYPE_CUSTOM, RelationType.class); } else if (ContactConstants.SIPADDRESS.equals(fieldname)) { sipaddresses = readJsonList(rowId, sipaddresses, jp, fieldname, SipAddressType.TYPE_OTHER, SipAddressType.class); } else if (ContactConstants.NICKNAME.equals(fieldname)) { nicknames = readJsonList(rowId, nicknames, jp, fieldname, NicknameType.TYPE_DEFAULT, NicknameType.class); } else if (ContactConstants.IM.equals(fieldname)) { imAddresses = readImList(rowId, imAddresses, jp); } else if (ContactConstants.NOTE.equals(fieldname)) { note = jp.getValueAsString(); } else if (ContactConstants.GROUPMEMBERSHIP.equals(fieldname)) { while (jp.nextToken() != JsonToken.END_ARRAY) { String groupSourceId = jp.getValueAsString(); if (groupSourceIds == null) { groupSourceIds = new ArrayList<String>(); } groupSourceIds.add(groupSourceId); } } else if (ContactConstants.ORGANIZATION.equals(fieldname)) { organization = readOrg(rowId, jp); } else if (ContactConstants.PHOTO_SUPERPRIMARY.equals(fieldname)) { photoSuperPrimary = jp.getValueAsBoolean(); } else if (ContactConstants.STARRED.equals(fieldname)) { starred = jp.getValueAsBoolean(); } else if (ContactConstants.SEND_TO_VOICE_MAIL.equals(fieldname)) { sendToVoiceMail = jp.getValueAsBoolean(); } else if (ContactConstants.DROID_CUSTOM_RINGTONE.equals(fieldname)) { customRingtone = jp.getValueAsString(); } else { LOG.error("Unrecognized field for row with Id:" + rowId + " Fieldname:" + fieldname); } } jp.close(); } final byte[] photo = CryptoHelper.decodeValue(ContactConstants.PHOTO, values, cipher, privateKey); return new RawContact(fullName, firstName, lastName, middleName, prefixName, suffixName, phonecticFirst, phonecticMiddle, phonecticLast, phones, emails, websites, addresses, events, relations, sipaddresses, nicknames, imAddresses, note, organization, photo, photoSuperPrimary, groupSourceIds, null, starred, customRingtone, sendToVoiceMail, lastModified, deleted, serverContactId, rawContactId, false, -1); } catch (InvalidCipherTextException ex) { throw new InvalidKeyException("Invalid key detected.", ex); } catch (final IOException ex) { LOG.info("Error parsing contact data. Reason:" + ex.toString(), ex); } catch (IllegalArgumentException ex) { LOG.warn("Error parsing contact data. Reason:" + ex.toString(), ex); } return null; }
From source file:org.n52.tamis.core.test.json.deserialize.SingleProcessDescriptionDeserializer_Test.java
/** * Parses the example document located at * "src/test/resources/extendedSingleProcessDescription_example.json" and * deserializes its content into an instance of * {@link ProcessDescription_singleProcess} *//*from w ww .j av a 2 s. co m*/ @Test public void test() { try { input = this.getClass().getResourceAsStream(EXTENDED_SINGLE_PROCESS_DESCRIPTION_EXAMPLE_JSON); ObjectMapper objectMapper = new ObjectMapper(); JsonFactory jsonFactory = objectMapper.getFactory(); this.jsonParser = jsonFactory.createParser(input); ProcessDescription_singleProcess singleProcessDescription_short = processesDeserializer .deserialize(jsonParser, null); /* * Assert that values of the intantiated * ProcessDescription_singleProcess object match the expected * parameters from the example document */ Assert.assertNotNull(singleProcessDescription_short); /* * id */ Assert.assertEquals("org.n52.tamis.algorithm.interpolation", singleProcessDescription_short.getId()); /* * label */ Assert.assertEquals("TAMIS Interpolation Process", singleProcessDescription_short.getLabel()); /* * inputs */ List<ProcessDescriptionInput> inputs = singleProcessDescription_short.getInputs(); Assert.assertEquals(3, inputs.size()); /* * first Input */ ProcessDescriptionInput firstInput = inputs.get(0); Assert.assertEquals("target-grid", firstInput.getId()); Assert.assertEquals("Target Grid", firstInput.getLabel()); Assert.assertEquals("text/xml | application/x-netcdf", firstInput.getType()); Assert.assertEquals(true, firstInput.getRequired()); /* * second Input */ ProcessDescriptionInput secondInput = inputs.get(1); Assert.assertEquals("interpolation-method", secondInput.getId()); Assert.assertEquals("Interpolation Method", secondInput.getLabel()); Assert.assertEquals("text/plain | text/xml", secondInput.getType()); Assert.assertEquals(true, secondInput.getRequired()); /* * third Input */ ProcessDescriptionInput thirdInput = inputs.get(2); Assert.assertEquals("input-values", thirdInput.getId()); Assert.assertEquals("Input Values", thirdInput.getLabel()); Assert.assertEquals("application/om+xml; version=2.0", thirdInput.getType()); Assert.assertEquals(true, thirdInput.getRequired()); /* * output(s) */ List<ProcessDescriptionOutput> outputs = singleProcessDescription_short.getOutputs(); Assert.assertEquals(1, outputs.size()); ProcessDescriptionOutput firstOutput = outputs.get(0); Assert.assertEquals("interpolated-values", firstOutput.getId()); Assert.assertEquals("Interpolated Values", firstOutput.getLabel()); Assert.assertEquals("application/geotiff | application/x-netcdf", firstOutput.getType()); } catch (IOException ex) { ex.printStackTrace(); } finally { if (input != null) { try { input.close(); } catch (IOException e) { e.printStackTrace(); } } } }
From source file:com.netflix.hollow.jsonadapter.HollowJsonAdapterPrimaryKeyFinder.java
public Object[] findKey(String json) throws IOException { JsonFactory factory = new JsonFactory(); JsonParser parser = factory.createParser(new StringReader(json)); return Arrays.copyOf(findKey(parser), keyElementArray.length); }
From source file:io.seldon.external.ExternalPredictionServer.java
public JsonNode predict(String client, JsonNode jsonNode, OptionsHolder options) { long timeNow = System.currentTimeMillis(); URI uri = URI.create(options.getStringOption(URL_PROPERTY_NAME)); try {/*from w ww. j a v a 2 s . co m*/ URIBuilder builder = new URIBuilder().setScheme("http").setHost(uri.getHost()).setPort(uri.getPort()) .setPath(uri.getPath()).setParameter("client", client) .setParameter("json", jsonNode.toString()); uri = builder.build(); } catch (URISyntaxException e) { throw new APIException(APIException.GENERIC_ERROR); } HttpContext context = HttpClientContext.create(); HttpGet httpGet = new HttpGet(uri); try { if (logger.isDebugEnabled()) logger.debug("Requesting " + httpGet.getURI().toString()); CloseableHttpResponse resp = httpClient.execute(httpGet, context); try { if (resp.getStatusLine().getStatusCode() == 200) { ObjectMapper mapper = new ObjectMapper(); JsonFactory factory = mapper.getFactory(); JsonParser parser = factory.createParser(resp.getEntity().getContent()); JsonNode actualObj = mapper.readTree(parser); return actualObj; } else { logger.error( "Couldn't retrieve prediction from external prediction server -- bad http return code: " + resp.getStatusLine().getStatusCode()); throw new APIException(APIException.GENERIC_ERROR); } } finally { if (resp != null) resp.close(); if (logger.isDebugEnabled()) logger.debug( "External prediction server took " + (System.currentTimeMillis() - timeNow) + "ms"); } } catch (IOException e) { logger.error("Couldn't retrieve prediction from external prediction server - ", e); throw new APIException(APIException.GENERIC_ERROR); } catch (Exception e) { logger.error("Couldn't retrieve prediction from external prediction server - ", e); throw new APIException(APIException.GENERIC_ERROR); } finally { } }
From source file:org.apache.nifi.minifi.c2.provider.nifi.rest.TemplatesIterator.java
public TemplatesIterator(HttpConnector httpConnector, JsonFactory jsonFactory) throws ConfigurationProviderException, IOException { urlConnection = httpConnector.get(FLOW_TEMPLATES); inputStream = urlConnection.getInputStream(); parser = jsonFactory.createParser(inputStream); while (parser.nextToken() != JsonToken.END_OBJECT) { if ("templates".equals(parser.getCurrentName())) { break; }/*from ww w.j a v a2s . c o m*/ } next = getNext(); }