List of usage examples for com.fasterxml.jackson.core JsonFactory JsonFactory
public JsonFactory()
From source file:com.apteligent.ApteligentJavaClient.java
/*********************************************************************************************************************/ private Token auth(String email, String password) throws IOException { String urlParameters = "grant_type=password&username=" + email + "&password=" + password; URL obj = new URL(API_TOKEN); HttpsURLConnection conn = (HttpsURLConnection) obj.openConnection(); conn.setSSLSocketFactory((SSLSocketFactory) SSLSocketFactory.getDefault()); conn.setDoOutput(true);//from ww w . j a v a2 s . co m conn.setDoInput(true); //add request header String basicAuth = new String(Base64.encodeBytes(apiKey.getBytes())); conn.setRequestProperty("Authorization", String.format("Basic %s", basicAuth)); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setRequestProperty("Accept", "*/*"); conn.setRequestProperty("Content-Length", Integer.toString(urlParameters.getBytes().length)); conn.setRequestMethod("POST"); // Send post request DataOutputStream wr = new DataOutputStream(conn.getOutputStream()); wr.writeBytes(urlParameters); wr.flush(); wr.close(); // read token JsonFactory jsonFactory = new JsonFactory(); JsonParser jp = jsonFactory.createParser(conn.getInputStream()); ObjectMapper mapper = getObjectMapper(); Token token = mapper.readValue(jp, Token.class); return token; }
From source file:com.marklogic.client.functionaltest.TestBulkReadWriteWithJacksonParserHandle.java
@Test public void testWriteMultipleJSONDocsWithDefaultMetadata() 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(); // put meta-data DocumentMetadataHandle mh = setMetadata(); DocumentMetadataHandle mhRead = new DocumentMetadataHandle(); JacksonParserHandle jacksonParserHandle1 = new JacksonParserHandle(); JacksonParserHandle jacksonParserHandle2 = new JacksonParserHandle(); JacksonParserHandle jacksonParserHandle3 = new JacksonParserHandle(); jacksonParserHandle1.set(f.createParser(json1)); jacksonParserHandle2.set(f.createParser(json2)); jacksonParserHandle3.set(f.createParser(json3)); writeset.addDefault(mh);/*from w w w . ja v a2 s. co m*/ writeset.add(docId[0], jacksonParserHandle1); writeset.add(docId[1], jacksonParserHandle2); writeset.add(docId[2], jacksonParserHandle3); docMgr.write(writeset); DocumentPage page = docMgr.read(docId); while (page.hasNext()) { DocumentRecord rec = page.next(); docMgr.readMetadata(rec.getUri(), mhRead); System.out.println(rec.getUri()); validateMetadata(mhRead); } validateMetadata(mhRead); // Close handles. jacksonParserHandle1.close(); jacksonParserHandle2.close(); jacksonParserHandle3.close(); }
From source file:org.apache.olingo.server.core.serializer.json.ODataJsonSerializer.java
public void entityCollectionIntoStream(final ServiceMetadata metadata, final EdmEntityType entityType, final EntityIterator entitySet, final EntityCollectionSerializerOptions options, final OutputStream outputStream) throws SerializerException { SerializerException cachedException; boolean pagination = false; try {/*w w w . j a v a 2s . co m*/ JsonGenerator json = new JsonFactory().createGenerator(outputStream); json.writeStartObject(); final ContextURL contextURL = checkContextURL(options == null ? null : options.getContextURL()); writeContextURL(contextURL, json); writeMetadataETag(metadata, json); if (options != null && options.getCount() != null && options.getCount().getValue()) { writeInlineCount("", entitySet.getCount(), json); } json.writeFieldName(Constants.VALUE); String name = contextURL == null ? null : contextURL.getEntitySetOrSingletonOrType(); 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); } // next link support for streaming results writeNextLink(entitySet, json, pagination); json.close(); } 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; } }
From source file:com.cinnober.msgcodec.json.JsonCodec.java
/** * Read a static group from the specified stream, when the JSON does not contain the '$type' field. * * @param groupType the expected group type, not null. * @param in the stream to read from, not null. * @return the decoded value./*from w ww. j a va 2 s. c o m*/ * @throws IOException if the underlying stream throws an exception. * @throws DecodeException if the value could not be decoded, or if a required field is missing. */ public Object decodeStatic(Object groupType, InputStream in) throws IOException { StaticGroupHandler groupHandler = staticGroupsByGroupType.get(groupType); if (groupHandler == null) { throw new IllegalArgumentException("Unknown group type"); } JsonFactory f = new JsonFactory(); JsonParser p = f.createParser(in); JsonToken token = p.nextToken(); if (token == JsonToken.VALUE_NULL) { return null; } else if (token != JsonToken.START_OBJECT) { throw new DecodeException("Expected {"); } return groupHandler.readValue(p); }
From source file:com.marklogic.client.functionaltest.TestBiTemporal.java
private void validateLSQTQueryData(DatabaseClient client) throws Exception { // Fetch documents associated with a search term (such as XML) in Address // element/* w w w. j a v a 2 s . c om*/ QueryManager queryMgr = client.newQueryManager(); StructuredQueryBuilder sqb = queryMgr.newStructuredQueryBuilder(); Calendar queryTime = DatatypeConverter.parseDateTime("2007-01-01T00:00:01"); StructuredQueryDefinition periodQuery = sqb.temporalLsqtQuery(temporalLsqtCollectionName, queryTime, 0, new String[] {}); long start = 1; JSONDocumentManager docMgr = client.newJSONDocumentManager(); docMgr.setMetadataCategories(Metadata.ALL); // Get all metadata DocumentPage termQueryResults = docMgr.search(periodQuery, start); long count = 0; while (termQueryResults.hasNext()) { ++count; DocumentRecord record = termQueryResults.next(); System.out.println("URI = " + record.getUri()); DocumentMetadataHandle metadataHandle = new DocumentMetadataHandle(); record.getMetadata(metadataHandle); Iterator<String> resCollections = metadataHandle.getCollections().iterator(); while (resCollections.hasNext()) { System.out.println("Collection = " + resCollections.next()); } if (record.getFormat() == Format.XML) { DOMHandle recordHandle = new DOMHandle(); record.getContent(recordHandle); System.out.println("Content = " + recordHandle.toString()); } else { JacksonDatabindHandle<ObjectNode> recordHandle = new JacksonDatabindHandle<ObjectNode>( ObjectNode.class); record.getContent(recordHandle); System.out.println("Content = " + recordHandle.toString()); JsonFactory factory = new JsonFactory(); ObjectMapper mapper = new ObjectMapper(factory); TypeReference<HashMap<String, Object>> typeRef = new TypeReference<HashMap<String, Object>>() { }; HashMap<String, Object> docObject = mapper.readValue(recordHandle.toString(), typeRef); @SuppressWarnings("unchecked") HashMap<String, Object> systemNode = (HashMap<String, Object>) (docObject.get(systemNodeName)); String systemStartDate = (String) systemNode.get(systemStartERIName); String systemEndDate = (String) systemNode.get(systemEndERIName); System.out.println("systemStartDate = " + systemStartDate); System.out.println("systemEndDate = " + systemEndDate); @SuppressWarnings("unchecked") HashMap<String, Object> validNode = (HashMap<String, Object>) (docObject.get(validNodeName)); String validStartDate = (String) validNode.get(validStartERIName); String validEndDate = (String) validNode.get(validEndERIName); System.out.println("validStartDate = " + validStartDate); System.out.println("validEndDate = " + validEndDate); assertTrue("Valid start date check failed", (validStartDate.equals("2001-01-01T00:00:00") && validEndDate.equals("2011-12-31T23:59:59") && systemStartDate.equals("2005-01-01T00:00:01-08:00") && systemEndDate.equals("2010-01-01T00:00:01-08:00"))); } } System.out.println("Number of results using SQB = " + count); assertEquals("Wrong number of results", 1, count); }
From source file:org.carrot2.core.ProcessingResultTest.java
private JsonNode getJsonRootNode(final String jsonString) throws IOException, JsonParseException { final JsonParser jsonParser = new JsonFactory().createJsonParser(new StringReader(jsonString)); final ObjectMapper mapper = new ObjectMapper(); final JsonNode root = mapper.readTree(jsonParser); return root;//from www . j av a2 s . c o m }
From source file:io.fabric8.maven.core.util.KubernetesResourceUtil.java
private static Map<String, Object> readFragment(File file, String ext) throws IOException { ObjectMapper mapper = new ObjectMapper("json".equals(ext) ? new JsonFactory() : new YAMLFactory()); TypeReference<HashMap<String, Object>> typeRef = new TypeReference<HashMap<String, Object>>() { };/*w ww . ja va 2s. com*/ try { Map<String, Object> ret = mapper.readValue(file, typeRef); return ret != null ? ret : new HashMap<String, Object>(); } catch (JsonProcessingException e) { throw new JsonMappingException(String.format("[%s] %s", file, e.getMessage()), e.getLocation(), e); } }
From source file:de.tudarmstadt.ukp.dkpro.core.io.brat.BratWriter.java
private void writeAnnotations(JCas aJCas) throws IOException { BratAnnotationDocument doc = new BratAnnotationDocument(); List<FeatureStructure> relationFS = new ArrayList<>(); Map<BratEventAnnotation, FeatureStructure> eventFS = new LinkedHashMap<>(); // Go through all the annotations but only handle the ones that have no references to // other annotations. for (FeatureStructure fs : selectAll(aJCas)) { // Skip document annotation if (fs == aJCas.getDocumentAnnotationFs()) { continue; }//from w ww . j ava 2 s.c o m // Skip excluded types if (excludeTypes.contains(fs.getType().getName())) { getLogger().debug("Excluding [" + fs.getType().getName() + "]"); continue; } if (spanTypes.contains(fs.getType().getName())) { writeTextAnnotation(doc, (AnnotationFS) fs); } else if (parsedRelationTypes.containsKey(fs.getType().getName())) { relationFS.add(fs); } else if (hasNonPrimitiveFeatures(fs) && (fs instanceof AnnotationFS)) { // else if (parsedEventTypes.containsKey(fs.getType().getName())) { BratEventAnnotation event = writeEventAnnotation(doc, (AnnotationFS) fs); eventFS.put(event, fs); } else if (fs instanceof AnnotationFS) { warnings.add("Assuming annotation type [" + fs.getType().getName() + "] is span"); writeTextAnnotation(doc, (AnnotationFS) fs); } else { warnings.add("Skipping annotation with type [" + fs.getType().getName() + "]"); } } // Handle relations now since now we can resolve their targets to IDs. for (FeatureStructure fs : relationFS) { writeRelationAnnotation(doc, fs); } // Handle event slots now since now we can resolve their targets to IDs. for (Entry<BratEventAnnotation, FeatureStructure> e : eventFS.entrySet()) { writeSlots(doc, e.getKey(), e.getValue()); } switch (filenameSuffix) { case ".ann": try (Writer out = new OutputStreamWriter(getOutputStream(aJCas, filenameSuffix), "UTF-8")) { doc.write(out); break; } case ".html": case ".json": String template; if (filenameSuffix.equals(".html")) { template = IOUtils.toString(getClass().getResource("html/template.html")); } else { template = "{ \"collData\" : ##COLL-DATA## , \"docData\" : ##DOC-DATA## }"; } JsonFactory jfactory = new JsonFactory(); try (Writer out = new OutputStreamWriter(getOutputStream(aJCas, filenameSuffix), "UTF-8")) { String docData; try (StringWriter buf = new StringWriter()) { try (JsonGenerator jg = jfactory.createGenerator(buf)) { jg.useDefaultPrettyPrinter(); doc.write(jg, aJCas.getDocumentText()); } docData = buf.toString(); } String collData; try (StringWriter buf = new StringWriter()) { try (JsonGenerator jg = jfactory.createGenerator(buf)) { jg.useDefaultPrettyPrinter(); conf.write(jg); } collData = buf.toString(); } template = StringUtils.replaceEach(template, new String[] { "##COLL-DATA##", "##DOC-DATA##" }, new String[] { collData, docData }); out.write(template); } conf = new BratConfiguration(); break; default: throw new IllegalArgumentException("Unknown file format: [" + filenameSuffix + "]"); } }
From source file:com.neoteric.starter.metrics.report.elastic.ElasticsearchReporter.java
private void checkForIndexTemplate() { try {// w ww. ja v a 2 s. c om HttpURLConnection connection = openConnection("/_template/metrics_template", "HEAD"); connection.disconnect(); boolean isTemplateMissing = connection.getResponseCode() == HttpURLConnection.HTTP_NOT_FOUND; // nothing there, lets create it if (isTemplateMissing) { LOGGER.debug("No metrics template found in elasticsearch. Adding..."); HttpURLConnection putTemplateConnection = openConnection("/_template/metrics_template", "PUT"); JsonGenerator json = new JsonFactory().createGenerator(putTemplateConnection.getOutputStream()); json.writeStartObject(); json.writeStringField("template", index + "*"); json.writeObjectFieldStart("mappings"); json.writeObjectFieldStart("_default_"); json.writeObjectFieldStart("_all"); json.writeBooleanField("enabled", false); json.writeEndObject(); json.writeObjectFieldStart("properties"); json.writeObjectFieldStart("name"); json.writeObjectField("type", "string"); json.writeObjectField("index", "not_analyzed"); json.writeEndObject(); json.writeEndObject(); json.writeEndObject(); json.writeEndObject(); json.writeEndObject(); json.flush(); putTemplateConnection.disconnect(); if (putTemplateConnection.getResponseCode() != HttpStatus.OK.value()) { LOGGER.error( "Error adding metrics template to elasticsearch: {}/{}" + putTemplateConnection.getResponseCode(), putTemplateConnection.getResponseMessage()); } } checkedForIndexTemplate = true; } catch (IOException e) { LOGGER.error("Error when checking/adding metrics template to elasticsearch", e); } }
From source file:com.adobe.communities.ugc.migration.importer.ImportFileUploadServlet.java
private void saveExplodedFiles(final ResourceResolver resolver, final Resource folder, final JSONWriter writer, final ZipInputStream zipInputStream, final String basePath) throws ServletException { // we need the closeShieldInputStream to prevent the zipInputStream from being closed during resolver.create() final CloseShieldInputStream closeShieldInputStream = new CloseShieldInputStream(zipInputStream); // fileResourceProperties and folderProperties will be reused inside the while loop final Map<String, Object> fileResourceProperties = new HashMap<String, Object>(); fileResourceProperties.put(JcrConstants.JCR_PRIMARYTYPE, JcrConstants.NT_FILE); final Map<String, Object> folderProperties = new HashMap<String, Object>(); folderProperties.put(JcrConstants.JCR_PRIMARYTYPE, "sling:Folder"); ZipEntry zipEntry;//from w ww . j a va 2s . c om try { zipEntry = zipInputStream.getNextEntry(); } catch (final IOException e) { throw new ServletException("Unable to read entries from uploaded zip archive", e); } final List<Resource> toDelete = new ArrayList<Resource>(); while (zipEntry != null) { // store files under the provided folder try { final String name = ResourceUtil.normalize("/" + zipEntry.getName()); if (null == name) { // normalize filename and if they aren't inside upload path, don't store them continue; } Resource parent = folder; Resource subFolder = null; for (final String subFolderName : name.split("/")) { // check if the sub-folder already exists subFolder = resolver.getResource(parent, subFolderName); if (null == subFolder || subFolder instanceof NonExistingResource) { // create the sub-folder subFolder = resolver.create(parent, subFolderName, folderProperties); } parent = subFolder; } if (!zipEntry.isDirectory()) { // first represent the file as a resource final Resource file = resolver.create(subFolder, "file", fileResourceProperties); // now store its data as a jcr:content node final Map<String, Object> fileProperties = new HashMap<String, Object>(); byte[] bytes = IOUtils.toByteArray(closeShieldInputStream); fileProperties.put(JcrConstants.JCR_DATA, new String(bytes, "UTF8")); fileProperties.put(JcrConstants.JCR_PRIMARYTYPE, "nt:resource"); resolver.create(file, JcrConstants.JCR_CONTENT, fileProperties); // if provided a basePath, import immediately if (StringUtils.isNotBlank(basePath) && null != file && !(file instanceof NonExistingResource)) { Resource fileContent = file.getChild(JcrConstants.JCR_CONTENT); if (null != fileContent && !(fileContent instanceof NonExistingResource)) { final ValueMap contentVM = fileContent.getValueMap(); InputStream inputStream = (InputStream) contentVM.get(JcrConstants.JCR_DATA); if (inputStream != null) { final JsonParser jsonParser = new JsonFactory().createParser(inputStream); jsonParser.nextToken(); // get the first token String resName = basePath + name.substring(0, name.lastIndexOf(".json")); Resource resource = resolver.getResource(resName); if (resource == null) { // voting does not have a node under articles resource = resolver.getResource(resName.substring(0, resName.lastIndexOf("/"))); } try { importFile(jsonParser, resource, resolver); toDelete.add(file); } catch (final Exception e) { // add the file name to our response ONLY if we failed to import it writer.value(name); // we want to log the reason we weren't able to import, but don't stop importing LOG.error(e.getMessage()); } } } } else if (StringUtils.isBlank(basePath) && null != file && !(file instanceof NonExistingResource)) { // add the file name to our response writer.value(name); } } resolver.commit(); zipEntry = zipInputStream.getNextEntry(); } catch (final IOException e) { // convert any IOExceptions into ServletExceptions throw new ServletException(e.getMessage(), e); } catch (final JSONException e) { // convert any JSONExceptions into ServletExceptions throw new ServletException(e.getMessage(), e); } } closeShieldInputStream.close(); // delete any files that were successfully imported if (!toDelete.isEmpty()) { for (final Resource deleteResource : toDelete) { deleteResource(deleteResource); } } }