List of usage examples for com.fasterxml.jackson.core JsonParser nextToken
public abstract JsonToken nextToken() throws IOException, JsonParseException;
From source file:org.apache.manifoldcf.agents.output.amazoncloudsearch.AmazonCloudSearchConnector.java
private String parseMessage(JsonParser parser) throws JsonParseException, IOException { while (parser.nextToken() != JsonToken.END_ARRAY) { String name = parser.getCurrentName(); if ("message".equalsIgnoreCase(name)) { parser.nextToken();/* ww w.j ava2 s .com*/ return parser.getText(); } } return null; }
From source file:com.microsoft.windowsazure.storage.table.TableParser.java
/** * Reserved for internal use. Parses the operation response as a collection of entities. Reads entity data from the * specified input stream using the specified class type and optionally projects each entity result with the * specified resolver into an {@link ODataPayload} containing a collection of {@link TableResult} objects. * /*from w w w . j a v a2s. co m*/ * @param inStream * The <code>InputStream</code> to read the data to parse from. * @param clazzType * The class type <code>T</code> implementing {@link TableEntity} for the entities returned. Set to * <code>null</code> to ignore the returned entities and copy only response properties into the * {@link TableResult} objects. * @param resolver * An {@link EntityResolver} instance to project the entities into instances of type <code>R</code>. Set * to <code>null</code> to return the entities as instances of the class type <code>T</code>. * @param opContext * An {@link OperationContext} object used to track the execution of the operation. * @return * An {@link ODataPayload} containing a collection of {@link TableResult} objects with the parsed operation * response. * @throws ParseException * if an error occurs while parsing the stream. * @throws InstantiationException * if an error occurs while constructing the result. * @throws IllegalAccessException * if an error occurs in reflection while parsing the result. * @throws StorageException * if a storage service error occurs. * @throws IOException * if an error occurs while accessing the stream. * @throws JsonParseException * if an error occurs while parsing the stream. */ @SuppressWarnings("unchecked") private static <T extends TableEntity, R> ODataPayload<?> parseJsonQueryResponse(final InputStream inStream, final Class<T> clazzType, final EntityResolver<R> resolver, final TableRequestOptions options, final OperationContext opContext) throws ParseException, InstantiationException, IllegalAccessException, StorageException, JsonParseException, IOException { ODataPayload<T> corePayload = null; ODataPayload<R> resolvedPayload = null; ODataPayload<?> commonPayload = null; JsonParser parser = createJsonParserFromStream(inStream); try { if (resolver != null) { resolvedPayload = new ODataPayload<R>(); commonPayload = resolvedPayload; } else { corePayload = new ODataPayload<T>(); commonPayload = corePayload; } if (!parser.hasCurrentToken()) { parser.nextToken(); } ODataUtilities.assertIsStartObjectJsonToken(parser); // move into data parser.nextToken(); // if there is a clazz type and if JsonNoMetadata, create a classProperties dictionary to use for type inference once // instead of querying the cache many times HashMap<String, PropertyPair> classProperties = null; if (options.getTablePayloadFormat() == TablePayloadFormat.JsonNoMetadata && clazzType != null) { classProperties = PropertyPair.generatePropertyPairs(clazzType); } while (parser.getCurrentToken() != null) { if (parser.getCurrentToken() == JsonToken.FIELD_NAME && parser.getCurrentName().equals(ODataConstants.VALUE)) { // move to start of array parser.nextToken(); ODataUtilities.assertIsStartArrayJsonToken(parser); // go to properties parser.nextToken(); while (parser.getCurrentToken() == JsonToken.START_OBJECT) { final TableResult res = parseJsonEntity(parser, clazzType, classProperties, resolver, options, opContext); if (corePayload != null) { corePayload.tableResults.add(res); } if (resolver != null) { resolvedPayload.results.add((R) res.getResult()); } else { corePayload.results.add((T) res.getResult()); } parser.nextToken(); } ODataUtilities.assertIsEndArrayJsonToken(parser); } parser.nextToken(); } } finally { parser.close(); } return commonPayload; }
From source file:com.netflix.hollow.jsonadapter.HollowJsonAdapter.java
private int addSubArray(JsonParser parser, String arrayType, HollowWriteRecord arrayRec) throws IOException { JsonToken token = parser.nextToken(); arrayRec.reset();//w w w .ja va 2 s . c o m HollowCollectionSchema schema = (HollowCollectionSchema) hollowSchemas.get(arrayType); ObjectFieldMapping valueRec = null; ObjectMappedFieldPath fieldMapping = null; while (token != JsonToken.END_ARRAY) { int elementOrdinal; if (token == JsonToken.START_OBJECT || token == JsonToken.START_ARRAY) { elementOrdinal = parseSubType(parser, token, schema.getElementType()); } else { if (valueRec == null) { valueRec = getObjectFieldMapping(schema.getElementType()); fieldMapping = valueRec.getSingleFieldMapping(); } addObjectField(parser, token, fieldMapping); elementOrdinal = valueRec.build(-1); } if (arrayRec instanceof HollowListWriteRecord) { ((HollowListWriteRecord) arrayRec).addElement(elementOrdinal); } else { ((HollowSetWriteRecord) arrayRec).addElement(elementOrdinal); } token = parser.nextToken(); } return stateEngine.add(arrayType, arrayRec); }
From source file:org.usrz.libs.webtools.resources.ServeResource.java
private Response produce(String path) throws Exception { /* Basic check for null/empty path */ if ((path == null) || (path.length() == 0)) return NOT_FOUND; /* Get our resource file, potentially a ".less" file for CSS */ Resource resource = manager.getResource(path); if ((resource == null) && path.endsWith(".css")) { path = path.substring(0, path.length() - 4) + ".less"; resource = manager.getResource(path); }/*from w w w .j a va2 s . c o m*/ /* If the root is incorrect, log this, if not found, 404 it! */ if (resource == null) return NOT_FOUND; /* Ok, we have a resource on disk, this can be potentially long ... */ final String fileName = resource.getFile().getName(); /* Check and validated our cache */ Entry cached = cache.computeIfPresent(resource, (r, entry) -> entry.resource.hasChanged() ? null : entry); /* If we have no cache, we *might* want to cache something */ if (cached == null) { /* What to do, what to do? */ if ((fileName.endsWith(".css") && minify) || fileName.endsWith(".less")) { /* Lessify CSS and cache */ xlog.debug("Lessifying resource \"%s\"", fileName); cached = new Entry(resource, lxess.convert(resource, minify), styleMediaType); } else if (fileName.endsWith(".js") && minify) { /* Uglify JavaScript and cache */ xlog.debug("Uglifying resource \"%s\"", fileName); cached = new Entry(resource, uglify.convert(resource.readString(), minify, minify), scriptMediaType); } else if (fileName.endsWith(".json")) { /* Strip comments and normalize JSON */ xlog.debug("Normalizing JSON resource \"%s\"", fileName); /* All to do with Jackson */ final Reader reader = resource.read(); final StringWriter writer = new StringWriter(); final JsonParser parser = json.createParser(reader); final JsonGenerator generator = json.createGenerator(writer); /* Not minifying? Means pretty printing! */ if (!minify) generator.useDefaultPrettyPrinter(); /* Get our schtuff through the pipeline */ parser.nextToken(); generator.copyCurrentStructure(parser); generator.flush(); generator.close(); reader.close(); parser.close(); /* Cached results... */ cached = new Entry(resource, writer.toString(), jsonMediaType); } /* Do we have anything to cache? */ if (cached != null) { xlog.debug("Caching resource \"%s\"", fileName); cache.put(resource, cached); } } /* Prepare our basic response from either cache or file */ final ResponseBuilder response = Response.ok(); if (cached != null) { /* Response from cache */ xlog.trace("Serving cached resource \"%s\"", fileName); response.entity(cached.contents).lastModified(new Date(resource.lastModifiedAt())).type(cached.type); } else { /* Response from a file */ xlog.trace("Serving file-based resource \"%s\"", fileName); /* If text/* or application/javascript, append encoding */ MediaType type = MediaTypes.get(fileName); if (type.getType().equals("text") || scriptMediaType.isCompatible(type)) { type = type.withCharset(charsetName); } /* Our file is served! */ response.entity(resource.getFile()).lastModified(new Date(resource.lastModifiedAt())).type(type); } /* Caching headers and build response */ final Date expires = Date.from(Instant.now().plus(cacheDuration)); return response.cacheControl(cacheControl).expires(expires).build(); }
From source file:org.mongojack.internal.object.BsonObjectGenerator.java
@Override public void copyCurrentStructure(JsonParser jp) throws IOException { JsonToken t = jp.getCurrentToken();//from ww w .j av a 2 s .c o m // Let'string handle field-name separately first if (t == JsonToken.FIELD_NAME) { writeFieldName(jp.getCurrentName()); t = jp.nextToken(); // fall-through to copy the associated value } switch (t) { case START_ARRAY: writeStartArray(); while (jp.nextToken() != JsonToken.END_ARRAY) { copyCurrentStructure(jp); } writeEndArray(); break; case START_OBJECT: writeStartObject(); while (jp.nextToken() != JsonToken.END_OBJECT) { copyCurrentStructure(jp); } writeEndObject(); break; default: // others are simple: copyCurrentEvent(jp); } }
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 w w .ja va 2 s.com 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); } } }
From source file:com.netflix.hollow.jsonadapter.HollowJsonAdapter.java
@Override protected int processRecord(JsonParser parser) throws IOException { initHollowWriteRecordsIfNecessary(); //parser.nextToken(); return parseSubType(parser, parser.nextToken(), typeName); }
From source file:com.netflix.hollow.jsonadapter.HollowJsonAdapter.java
private int addStructuredMap(JsonParser parser, String mapTypeName, HollowMapWriteRecord mapRec) throws IOException { JsonToken token = parser.nextToken(); mapRec.reset();//from www . j av a 2 s. c om HollowMapSchema schema = (HollowMapSchema) hollowSchemas.get(mapTypeName); while (token != JsonToken.END_ARRAY) { if (token == JsonToken.START_OBJECT) { int keyOrdinal = -1, valueOrdinal = -1; while (token != JsonToken.END_OBJECT) { if (token == JsonToken.START_OBJECT || token == JsonToken.START_ARRAY) { if ("key".equals(parser.getCurrentName())) keyOrdinal = parseSubType(parser, token, schema.getKeyType()); else if ("value".equals(parser.getCurrentName())) valueOrdinal = parseSubType(parser, token, schema.getValueType()); } token = parser.nextToken(); } mapRec.addEntry(keyOrdinal, valueOrdinal); } token = parser.nextToken(); } return stateEngine.add(schema.getName(), mapRec); }
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 va 2 s . c om*/ 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.datagator.api.client.MatrixDeserializer.java
@Override public SimpleMatrix deserialize(JsonParser jp, DeserializationContext cntx) throws IOException, JsonProcessingException { int rowsCount = -1; int columnsCount = -1; int bodyRow = -1; int bodyColumn = -1; ArrayList<ArrayList<Object>> columnHeaders = null; JsonToken token = jp.getCurrentToken(); // FIELD_NAME if (!token.equals(JsonToken.FIELD_NAME)) { throw new RuntimeException(String.format("Unexpected token %s", token)); }/*w ww . jav a2 s. c o m*/ while (token.equals(JsonToken.FIELD_NAME)) { String name = jp.getText(); token = jp.nextToken(); if (name.equals("columnHeaders")) { if (!token.equals(JsonToken.VALUE_NUMBER_INT)) { throw new RuntimeException(String.format("Unexpected token %s", token)); } bodyRow = jp.getIntValue(); } else if (name.equals("rowHeaders")) { if (!token.equals(JsonToken.VALUE_NUMBER_INT)) { throw new RuntimeException(String.format("Unexpected token %s", token)); } bodyColumn = jp.getIntValue(); } else if (name.equals("rows")) { if (bodyRow < 0 || bodyColumn < 0) { throw new RuntimeException( "Unexpected property order 'columnHeaders' and 'rowHeaders' should precede 'rows'."); } columnHeaders = parseRows(jp, bodyRow, bodyColumn); } else if (name.equals("rowsCount")) { if (!token.equals(JsonToken.VALUE_NUMBER_INT)) { throw new RuntimeException(String.format("Unexpected token %s", token)); } rowsCount = jp.getIntValue(); } else if (name.equals("columnsCount")) { if (!token.equals(JsonToken.VALUE_NUMBER_INT)) { throw new RuntimeException(String.format("Unexpected token %s", token)); } columnsCount = jp.getIntValue(); } else { throw new RuntimeException(String.format("Unexpected property '%s'", name)); } token = jp.nextToken(); // FIELD_NAME } if (!(0 <= bodyRow && bodyRow <= rowsCount)) { throw new RuntimeException("Invalid Matrix shape"); } if (!(0 <= bodyColumn && bodyColumn <= columnsCount)) { throw new RuntimeException("Invalid Matrix shape"); } // special case: size of empty matrix is 1 x 0 if ((columnsCount == 0) && (rowsCount != 1)) { throw new RuntimeException("Invalid Matrix shape"); } Object[][] rows = new Object[bodyRow][]; for (int r = 0; r < bodyRow; r++) { rows[r] = columnHeaders.get(r).toArray(); } return new SimpleMatrix(bodyRow, bodyColumn, rows, rowsCount, columnsCount); }