List of usage examples for com.fasterxml.jackson.core JsonFactory JsonFactory
public JsonFactory()
From source file:com.apteligent.ApteligentJavaClient.java
/** * @param hash The crash hash to retrieve * @param diagnostics include detailed diagnostics information for crash * @param getOtherCrashes include other crashes and legacy crash groups now part of this group * @return Crash object//from w ww . j av a 2 s. c o m */ public Crash getCrash(String hash, boolean diagnostics, boolean getOtherCrashes) { String params = "?diagnostics=" + diagnostics + "&get_other_crashes=" + getOtherCrashes; Crash crash = null; try { HttpsURLConnection conn = sendGetRequest(API_CRASH_DETAILS.replace("{hash}", hash), params); JsonFactory jsonFactory = new JsonFactory(); JsonParser jp = jsonFactory.createParser(conn.getInputStream()); ObjectMapper mapper = getObjectMapper(); TreeNode node = mapper.readTree(jp); crash = mapper.treeToValue(node, Crash.class); } catch (IOException ioex) { ioex.printStackTrace(); } return crash; }
From source file:org.apache.manifoldcf.agents.output.amazoncloudsearch.AmazonCloudSearchConnector.java
private String getStatusFromJsonResponse(String responsbody) throws ManifoldCFException { try {//from w w w . j a v a 2s . com JsonParser parser = new JsonFactory().createJsonParser(responsbody); while (parser.nextToken() != JsonToken.END_OBJECT) { String name = parser.getCurrentName(); if ("status".equalsIgnoreCase(name)) { parser.nextToken(); return parser.getText(); } } } catch (JsonParseException e) { throw new ManifoldCFException(e); } catch (IOException e) { throw new ManifoldCFException(e); } return null; }
From source file:org.jbpm.designer.bpmn2.impl.Bpmn2JsonMarshaller.java
public String marshall(Definitions def, String preProcessingData) throws IOException { DroolsPackageImpl.init();/*from w w w. ja v a 2 s. c o m*/ BpsimPackageImpl.init(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); JsonFactory f = new JsonFactory(); JsonGenerator generator = f.createJsonGenerator(baos, JsonEncoding.UTF8); if (def.getRelationships() != null && def.getRelationships().size() > 0) { // current support for single relationship Relationship relationship = def.getRelationships().get(0); for (ExtensionAttributeValue extattrval : relationship.getExtensionValues()) { FeatureMap extensionElements = extattrval.getValue(); @SuppressWarnings("unchecked") List<BPSimDataType> bpsimExtensions = (List<BPSimDataType>) extensionElements .get(BpsimPackage.Literals.DOCUMENT_ROOT__BP_SIM_DATA, true); if (bpsimExtensions != null && bpsimExtensions.size() > 0) { BPSimDataType processAnalysis = bpsimExtensions.get(0); if (processAnalysis.getScenario() != null && processAnalysis.getScenario().size() > 0) { _simulationScenario = processAnalysis.getScenario().get(0); } } } } if (preProcessingData == null || preProcessingData.length() < 1) { preProcessingData = "ReadOnlyService"; } // this is a temp way to determine if // coordinate system changes are necessary String bpmn2Exporter = def.getExporter(); String bpmn2ExporterVersion = def.getExporterVersion(); boolean haveExporter = bpmn2Exporter != null && bpmn2ExporterVersion != null; if (_simulationScenario != null && !haveExporter) { coordianteManipulation = false; } marshallDefinitions(def, generator, preProcessingData); generator.close(); return baos.toString("UTF-8"); }
From source file:com.marklogic.client.functionaltest.TestBulkReadWriteWithJacksonParserHandle.java
@Test public void testWriteMultipleJSONDocsFromFactory() throws Exception { String docId[] = { "/a.json", "/b.json", "/c.json" }; String json1 = new String("{\"animal\":\"dog\", \"says\":\"woof\"}"); String json2 = new String("{\"animal\":\"cat\", \"says\":\"meow\"}"); String json3 = new String("{\"animal\":\"rat\", \"says\":\"keek\"}"); JsonFactory f = new JsonFactory(); JSONDocumentManager docMgr = client.newJSONDocumentManager(); docMgr.setMetadataCategories(Metadata.ALL); DocumentWriteSet writeset = docMgr.newWriteSet(); //Create a content Factory from JacksonDatabindHandle that will handle writes. ContentHandleFactory ch = JacksonParserHandle.newFactory(); //Instantiate a handle. JacksonParserHandle jacksonParserHandle1 = (JacksonParserHandle) ch.newHandle(JsonParser.class); JacksonParserHandle jacksonParserHandle2 = (JacksonParserHandle) ch.newHandle(JsonParser.class); JacksonParserHandle jacksonParserHandle3 = (JacksonParserHandle) ch.newHandle(JsonParser.class); jacksonParserHandle1.set(f.createParser(json1)); jacksonParserHandle2.set(f.createParser(json2)); jacksonParserHandle3.set(f.createParser(json3)); writeset.add(docId[0], jacksonParserHandle1); writeset.add(docId[1], jacksonParserHandle2); writeset.add(docId[2], jacksonParserHandle3); docMgr.write(writeset);/*from w w w .j a v a 2 s.co m*/ //Using JacksonHandle to read back from database. JacksonHandle jacksonhandle = new JacksonHandle(); docMgr.read(docId[0], jacksonhandle); JSONAssert.assertEquals(json1, jacksonhandle.toString(), true); docMgr.read(docId[1], jacksonhandle); JSONAssert.assertEquals(json2, jacksonhandle.toString(), true); docMgr.read(docId[2], jacksonhandle); JSONAssert.assertEquals(json3, jacksonhandle.toString(), true); // Close handles. jacksonParserHandle1.close(); jacksonParserHandle2.close(); jacksonParserHandle3.close(); }
From source file:de.odysseus.staxon.json.stream.jackson.JacksonStreamSourceTest.java
@Test(expected = IOException.class) public void testUnexpected() throws IOException { StringReader reader = new StringReader("\"alice\":\"bob\""); // missing document start/end JacksonStreamSource source = new JacksonStreamSource(new JsonFactory().createParser(reader)); Assert.assertEquals(JsonStreamToken.VALUE, source.peek()); source.value();/* w w w .j av a 2 s .co m*/ source.peek(); source.close(); }
From source file:org.eclipse.winery.repository.resources.AbstractComponentsResource.java
/** * Used by org.eclipse.winery.repository.repository.client and by the * artifactcreationdialog.tag. Especially the "name" field is used there at * the UI/*from w w w .ja v a2 s. co m*/ * * @return A list of all ids of all instances of this component type. If the * "name" attribute is required, that name is used as id <br /> * Format: * <code>[({"namespace": "<namespace>", "id": "<id>"},)* ]</code>. A * <code>name<code> field is added if the model allows an additional name attribute */ @GET @Produces(MediaType.APPLICATION_JSON) public String getListOfAllIds() { Class<? extends TOSCAComponentId> idClass = Utils.getComponentIdClassForComponentContainer(this.getClass()); boolean supportsNameAttribute = Util.instanceSupportsNameAttribute(idClass); SortedSet<? extends TOSCAComponentId> allTOSCAcomponentIds = Repository.INSTANCE .getAllTOSCAComponentIds(idClass); JsonFactory jsonFactory = new JsonFactory(); StringWriter sw = new StringWriter(); try { JsonGenerator jg = jsonFactory.createGenerator(sw); // We produce org.eclipse.winery.repository.client.WineryRepositoryClient.NamespaceAndId by hand here // Refactoring could move this class to common and fill it here jg.writeStartArray(); for (TOSCAComponentId id : allTOSCAcomponentIds) { jg.writeStartObject(); jg.writeStringField("namespace", id.getNamespace().getDecoded()); jg.writeStringField("id", id.getXmlId().getDecoded()); if (supportsNameAttribute) { AbstractComponentInstanceResource componentInstaceResource = AbstractComponentsResource .getComponentInstaceResource(id); String name = ((IHasName) componentInstaceResource).getName(); jg.writeStringField("name", name); } jg.writeEndObject(); } jg.writeEndArray(); jg.close(); } catch (Exception e) { AbstractComponentsResource.logger.error(e.getMessage(), e); return "[]"; } return sw.toString(); }
From source file:com.cinnober.msgcodec.json.JsonCodec.java
/** * Write the group to the stream, but without adding the '$type' field. * To decode the JSON the receiver must know what group type to expect. * * @param group the group to encode./* w w w .j a v a2 s.co m*/ * @param out the stream to write to, not null. * @throws IOException if the underlying byte sink throws an exception. * @throws IllegalArgumentException if the group is not correct or complete, e.g. a required field is missing. * Partial data may have been written to the stream. */ public void encodeStatic(Object group, OutputStream out) throws IOException { if (group == null) { out.write(NULL_BYTES); } else { JsonFactory f = new JsonFactory(); JsonGenerator g = f.createGenerator(out); StaticGroupHandler groupHandler = lookupGroupByValue(group); if (groupHandler == null) { throw new IllegalArgumentException("Cannot encode group (unknown type)"); } groupHandler.writeValue(group, g, false); g.flush(); } }
From source file:org.apache.olingo.server.core.serializer.json.ODataJsonSerializer.java
@Override public SerializerResult entityCollection(final ServiceMetadata metadata, final EdmEntityType entityType, final AbstractEntityCollection entitySet, final EntityCollectionSerializerOptions options) throws SerializerException { OutputStream outputStream = null; SerializerException cachedException = null; boolean pagination = false; try {//from w w w . j av a 2 s . com CircleStreamBuffer buffer = new CircleStreamBuffer(); outputStream = buffer.getOutputStream(); JsonGenerator json = new JsonFactory().createGenerator(outputStream); json.writeStartObject(); final ContextURL contextURL = checkContextURL(options == null ? null : options.getContextURL()); String name = contextURL == null ? null : contextURL.getEntitySetOrSingletonOrType(); writeContextURL(contextURL, json); writeMetadataETag(metadata, json); if (options != null && options.getCount() != null && options.getCount().getValue()) { writeInlineCount("", entitySet.getCount(), json); } writeOperations(entitySet.getOperations(), json); json.writeFieldName(Constants.VALUE); if (options == null) { writeEntitySet(metadata, entityType, entitySet, null, null, null, false, null, name, json); } else { writeEntitySet(metadata, entityType, entitySet, options.getExpand(), null, options.getSelect(), options.getWriteOnlyReferences(), null, name, json); } writeNextLink(entitySet, json, pagination); writeDeltaLink(entitySet, json, pagination); json.close(); outputStream.close(); return SerializerResultImpl.with().content(buffer.getInputStream()).build(); } catch (final IOException e) { cachedException = new SerializerException(IO_EXCEPTION_TEXT, e, SerializerException.MessageKeys.IO_EXCEPTION); throw cachedException; } catch (DecoderException e) { cachedException = new SerializerException(IO_EXCEPTION_TEXT, e, SerializerException.MessageKeys.IO_EXCEPTION); throw cachedException; } finally { closeCircleStreamBufferOutput(outputStream, cachedException); } }
From source file:com.comcast.cdn.traffic_control.traffic_router.core.external.ConsistentHashTest.java
License:asdf
@Test public void itUsesBypassFiltersWithDeliveryServiceSteering() throws Exception { CloseableHttpResponse response = null; try {//from www . j a v a 2 s. co m String requestPath = URLEncoder.encode("/some/path/force-to-target-2/more/asdfasdf", "UTF-8"); HttpGet httpGet = new HttpGet( "http://localhost:3333/crs/consistenthash/deliveryservice?ip=98.76.54.123&deliveryServiceId=" + steeringDeliveryServiceId + "&requestPath=" + requestPath); response = closeableHttpClient.execute(httpGet); ObjectMapper objectMapper = new ObjectMapper(new JsonFactory()); JsonNode deliveryServiceNode = objectMapper.readTree(EntityUtils.toString(response.getEntity())); assertThat(deliveryServiceNode.get("id").asText(), equalTo("steering-target-2")); requestPath = URLEncoder.encode("/some/path/force-to-target-1/more/asdfasdf", "UTF-8"); httpGet = new HttpGet( "http://localhost:3333/crs/consistenthash/deliveryservice?ip=98.76.54.123&deliveryServiceId=" + steeringDeliveryServiceId + "&requestPath=" + requestPath); response = closeableHttpClient.execute(httpGet); deliveryServiceNode = objectMapper.readTree(EntityUtils.toString(response.getEntity())); assertThat(deliveryServiceNode.get("id").asText(), equalTo("steering-target-1")); } finally { if (response != null) response.close(); } }