List of usage examples for com.fasterxml.jackson.core JsonToken END_OBJECT
JsonToken END_OBJECT
To view the source code for com.fasterxml.jackson.core JsonToken END_OBJECT.
Click Source Link
From source file:io.apiman.manager.api.exportimport.json.JsonImportReader.java
public void readClientVersions() throws Exception { current = nextToken();/* ww w .ja va 2s.co m*/ if (current == JsonToken.END_ARRAY) { return; } while (nextToken() != JsonToken.END_ARRAY) { // Traverse each client definition while (nextToken() != JsonToken.END_OBJECT) { if (jp.getCurrentName().equals(ClientVersionBean.class.getSimpleName())) { current = nextToken(); ClientVersionBean clientBean = jp.readValueAs(ClientVersionBean.class); dispatcher.clientVersion(clientBean); } else { OrgElementsEnum fieldName = OrgElementsEnum.valueOf(jp.getCurrentName()); current = nextToken(); switch (fieldName) { case Policies: processEntities(PolicyBean.class, dispatcher::clientPolicy); break; case Contracts: processEntities(ContractBean.class, dispatcher::clientContract); break; default: throw new RuntimeException("Unhandled entity " + fieldName + " with token " + current); } } } } }
From source file:org.helm.notation2.wsadapter.MonomerWSLoader.java
/** * Private routine to deserialize JSON containing monomer categorization data. * This is done manually to give more freedom regarding data returned by the * webservice./*from w w w .ja v a 2 s . c o m*/ * * @param parser the JSONParser containing JSONData. * @return List containing the monomer categorization * * @throws JsonParseException * @throws IOException */ private static List<CategorizedMonomer> deserializeEditorCategorizationConfig(JsonParser parser) throws JsonParseException, IOException { List<CategorizedMonomer> config = new LinkedList<CategorizedMonomer>(); CategorizedMonomer currentMonomer = null; parser.nextToken(); while (parser.hasCurrentToken()) { String fieldName = parser.getCurrentName(); JsonToken token = parser.getCurrentToken(); if (JsonToken.START_OBJECT.equals(token)) { currentMonomer = new CategorizedMonomer(); } else if (JsonToken.END_OBJECT.equals(token)) { config.add(currentMonomer); } if (fieldName != null) { switch (fieldName) { // id is first field case "monomerID": parser.nextToken(); currentMonomer.setMonomerID(parser.getText()); break; case "monomerName": parser.nextToken(); currentMonomer.setMonomerName(parser.getText()); break; case "naturalAnalogon": parser.nextToken(); currentMonomer.setNaturalAnalogon(parser.getText()); break; case "monomerType": parser.nextToken(); currentMonomer.setMonomerType(parser.getText()); break; case "polymerType": parser.nextToken(); currentMonomer.setPolymerType(parser.getText()); break; case "category": parser.nextToken(); currentMonomer.setCategory(parser.getText()); break; case "shape": parser.nextToken(); currentMonomer.setShape(parser.getText()); break; case "fontColor": parser.nextToken(); currentMonomer.setFontColor(parser.getText()); break; case "backgroundColor": parser.nextToken(); currentMonomer.setBackgroundColor(parser.getText()); break; default: break; } } parser.nextToken(); } return config; }
From source file:com.quinsoft.zeidon.standardoe.ActivateOisFromJsonStream.java
private void readEntity(String entityName) throws Exception { // Keeps track of whether the entity list starts with a [ or not. If there // is no [ then we are done reading entities of this type when we find the // end of the object. boolean entityArray = false; int twinCount = 0; JsonToken token = jp.getCurrentToken(); if (token == JsonToken.START_ARRAY) { token = jp.nextToken();/*from ww w.j av a 2 s. c om*/ entityArray = true; // Entity list started with [ } assert token == JsonToken.START_OBJECT; EntityDef entityDef = lodDef.getEntityDef(entityName, true, true); // Read tokens until we find the token that ends the current list of entities. while ((token = jp.nextToken()) != null) { twinCount++; if (token == JsonToken.END_ARRAY) break; if (token == JsonToken.END_OBJECT) { // If we get here then this should indicate an empty OI. Get the next // token, verify that it's an END_ARRAY, and return. token = jp.nextToken(); assert token == JsonToken.END_ARRAY; break; } // If there are multiple twins then the token is START_OBJECT to // indicate a new EI. if (token == JsonToken.START_OBJECT) { assert twinCount > 1; // Assert that we already created at least one EI. token = jp.nextToken(); } assert token == JsonToken.FIELD_NAME; EntityInstanceImpl ei = (EntityInstanceImpl) view.cursor(entityDef).createEntity(CursorPosition.LAST, CREATE_FLAGS); List<AttributeMeta> attributeMetas = new ArrayList<>(); // Read tokens until we find the token that ends the current entity. EntityMeta entityMeta = DEFAULT_ENTITY_META; while ((token = jp.nextToken()) != JsonToken.END_OBJECT) { String fieldName = jp.getCurrentName(); if (token == JsonToken.FIELD_NAME || token == JsonToken.START_OBJECT) token = jp.nextToken(); if (StringUtils.equals(fieldName, ".meta")) { entityMeta = readEntityMeta(ei); // Now that we have everything we can perform some processing. if (entityMeta.isLinkedSource) linkSources.put(entityMeta.entityKey, ei); else if (entityMeta.linkedSource != null) ei.linkInstances(linkSources.get(entityMeta.linkedSource)); continue; } if (fieldName.startsWith(".")) { AttributeMeta am = readAttributeMeta(ei, fieldName); attributeMetas.add(am); continue; } // Is this the start of an entity. if (token == JsonToken.START_ARRAY || token == JsonToken.START_OBJECT) { boolean recursiveChild = false; // Validate that the entity name is valid. EntityDef childEntity = lodDef.getEntityDef(fieldName, true, true); if (childEntity.getParent() != entityDef) { // Check to see the childEntity is a recursive child. if (entityDef.isRecursive()) { view.cursor(entityDef).setToSubobject(); recursiveChild = true; } else throw new ZeidonException("Parse error: %s is not a child of %s", fieldName, entityName); } readEntity(fieldName); if (recursiveChild) view.resetSubobject(); continue; } if (StringUtils.equals(jp.getText(), fieldName)) // If jp points to attr name, get next token. token = jp.nextToken(); // This better be an attribute // Try getting the attribute. We won't throw an exception (yet) if there // is no attribute with a matching name. AttributeDef attributeDef = entityDef.getAttribute(fieldName, false, true); if (attributeDef == null) { // We didn't find an attribute with a name matching fieldName. Do we allow // dynamic attributes for this entity? if (options.getAllowableDynamicEntities() == null || !options.getAllowableDynamicEntities().contains(entityDef.getName())) { entityDef.getAttribute(fieldName); // This will throw the exception. } // We are allowing dynamic attributes. Create one. DynamicAttributeDefConfiguration config = new DynamicAttributeDefConfiguration(); config.setAttributeName(fieldName); attributeDef = entityDef.createDynamicAttributeDef(config); } else if (attributeDef.isDerived()) // We'll ignore derived attributes. continue; Domain domain = attributeDef.getDomain(); Object internalValue = domain.convertExternalValue(task, ei.getAttribute(attributeDef), attributeDef, null, jp.getText()); ei.getAttribute(attributeDef).setInternalValue(internalValue, !attributeDef.isKey()); if (incremental) { // Since incremental flags are set, assume the attribute hasn't been // updated. We'll be told later if it has. AttributeValue attrib = ei.getInternalAttribute(attributeDef); attrib.setUpdated(false); } else { // If we just set the key then we'll assume the entity has // already been created. if (attributeDef.isKey()) ei.setIncrementalFlags(IncrementalEntityFlags.UPDATED); } } // while ( ( token = jp.nextToken() ) != JsonToken.END_OBJECT )... // Apply all the attribute metas to correctly set the attribute flags. for (AttributeMeta am : attributeMetas) am.apply(ei); // Now that we've updated everything, set the flags. if (incremental) { ei.setCreated(entityMeta.created); ei.setUpdated(entityMeta.updated); ei.setDeleted(entityMeta.deleted); ei.setIncluded(entityMeta.included); ei.setExcluded(entityMeta.excluded); if (entityMeta.incomplete) ei.setIncomplete(null); if (entityMeta.lazyLoaded != null) { String[] names = entityMeta.lazyLoaded.split(","); for (String name : names) ei.getEntitiesLoadedLazily().add(lodDef.getEntityDef(name, true, true)); } } // If the entity list didn't start with a [ then there is only one entity // in the list of twins so exit. if (entityArray == false) break; } // while ( ( token = jp.nextToken() ) != null )... }
From source file:com.amazonaws.services.cloudtrail.processinglibrary.serializer.AbstractEventSerializer.java
/** * Parse web identify session object/*from w w w .jav a 2 s. co m*/ * * @param sessionContext * @return the web identity session context * @throws IOException */ private WebIdentitySessionContext parseWebIdentitySessionContext(SessionContext sessionContext) throws IOException { if (this.jsonParser.nextToken() != JsonToken.START_OBJECT) { throw new JsonParseException("Not a WebIdentitySessionContext object", this.jsonParser.getCurrentLocation()); } WebIdentitySessionContext webIdFederationData = new WebIdentitySessionContext(); while (this.jsonParser.nextToken() != JsonToken.END_OBJECT) { String key = this.jsonParser.getCurrentName(); switch (key) { case "attributes": webIdFederationData.add(CloudTrailEventField.attributes.name(), this.parseAttributes()); break; case "federatedProvider": webIdFederationData.add(CloudTrailEventField.federatedProvider.name(), this.jsonParser.nextTextValue()); break; default: webIdFederationData.add(key, this.parseDefaultValue(key)); break; } } return webIdFederationData; }
From source file:com.github.heuermh.personalgenome.client.converter.JacksonPersonalGenomeConverter.java
@Override public Genotype parseGenotypes(final InputStream inputStream) { checkNotNull(inputStream);// www . j av a2 s . c om JsonParser parser = null; try { parser = jsonFactory.createParser(inputStream); parser.nextToken(); String id = null; String location = null; String interpretation = null; Map<String, String> values = new HashMap<String, String>(); while (parser.nextToken() != JsonToken.END_OBJECT) { String field = parser.getCurrentName(); parser.nextToken(); if ("id".equals(field)) { id = parser.getText(); } else { location = field; interpretation = parser.getText(); values.put(location, interpretation); } } return new Genotype(id, values); } catch (IOException e) { logger.warn("could not parse genotypes"); } finally { try { inputStream.close(); } catch (Exception e) { // ignored } try { parser.close(); } catch (Exception e) { // ignored } } return null; }
From source file:com.concentricsky.android.khanacademy.data.remote.LibraryUpdaterTask.java
private void parseDownloadUrls(JsonParser parser, ContentValues result) throws JsonParseException, IOException { // parser points at begin object token right now if (parser.getCurrentToken() == JsonToken.START_OBJECT) { while (parser.nextValue() != JsonToken.END_OBJECT) { String fieldName = parser.getCurrentName(); if (downloadUrlFields.contains(fieldName)) { result.put(fieldName + "url", parser.getValueAsString()); }/*from w w w.j a v a2 s . c o m*/ } } // else we must not have any download urls (null, '', something like that.) }
From source file:com.amazonaws.services.cloudtrail.processinglibrary.serializer.AbstractEventSerializer.java
/** * Parse session issuer object. It only happened on role session and federated session. * * @param sessionContext// www . j a va 2 s .c om * @return the session issuer object. * @throws IOException */ private SessionIssuer parseSessionIssuer(SessionContext sessionContext) throws IOException { if (this.jsonParser.nextToken() != JsonToken.START_OBJECT) { throw new JsonParseException("Not a SessionIssuer object", this.jsonParser.getCurrentLocation()); } SessionIssuer sessionIssuer = new SessionIssuer(); while (this.jsonParser.nextToken() != JsonToken.END_OBJECT) { String key = this.jsonParser.getCurrentName(); switch (key) { case "type": sessionIssuer.add(CloudTrailEventField.type.name(), this.jsonParser.nextTextValue()); break; case "principalId": sessionIssuer.add(CloudTrailEventField.principalId.name(), this.jsonParser.nextTextValue()); break; case "arn": sessionIssuer.add(CloudTrailEventField.arn.name(), this.jsonParser.nextTextValue()); break; case "accountId": sessionIssuer.add(CloudTrailEventField.accountId.name(), this.jsonParser.nextTextValue()); break; case "userName": sessionIssuer.add(CloudTrailEventField.userName.name(), this.jsonParser.nextTextValue()); break; default: sessionIssuer.add(key, this.parseDefaultValue(key)); break; } } return sessionIssuer; }
From source file:com.ntsync.shared.RequestGenerator.java
private static Map<Long, String> extractNewIdList(JsonParser jp) throws IOException { Map<Long, String> newIdMap = new HashMap<Long, String>(); while (jp.nextToken() != JsonToken.END_OBJECT) { String clientIdStr = jp.getCurrentName(); if (jp.nextToken() == null) { break; }/*from w ww .java 2s . c o m*/ String serverRowId = jp.getValueAsString(); try { Long clientRowId = Long.valueOf(clientIdStr); newIdMap.put(clientRowId, serverRowId); } catch (NumberFormatException ex) { LOG.warn("Invalid ID from server. Id:" + clientIdStr + " ServerId:" + serverRowId, ex); } } return newIdMap; }
From source file:org.apache.lucene.server.handlers.AddDocumentHandler.java
/** Parses the fields, which should look like {field1: * ..., field2: ..., ...} *///from w w w . j a v a 2 s . c om public static void parseFields(IndexState state, Document doc, JsonParser p) throws IOException { JsonToken token = p.nextToken(); if (token != JsonToken.START_OBJECT) { throw new IllegalArgumentException("fields should be an object"); } while (true) { token = p.nextToken(); if (token == JsonToken.END_OBJECT) { break; } assert token == JsonToken.FIELD_NAME; parseOneField(p, state, doc, p.getText()); } }
From source file:com.microsoft.windowsazure.storage.table.TableParser.java
/** * Reserved for internal use. Parses the operation response as an entity. Parses the result returned in the * specified stream in JSON format into a {@link TableResult} containing an entity of the specified class type * projected using the specified resolver. * /*from ww w . j a v a2 s . c o m*/ * @param parser * The <code>JsonParser</code> to read the data to parse from. * @param clazzType * The class type <code>T</code> implementing {@link TableEntity} for the entity returned. Set to * <code>null</code> to ignore the returned entity and copy only response properties into the * {@link TableResult} object. * @param resolver * An {@link EntityResolver} instance to project the entity into an instance of type <code>R</code>. Set * to <code>null</code> to return the entity as an instance of the class type <code>T</code>. * @param opContext * An {@link OperationContext} object used to track the execution of the operation. * @return * A {@link TableResult} containing the parsed entity result of the operation. * @throws IOException * if an error occurs while accessing the stream. * @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. */ private static <T extends TableEntity, R> TableResult parseJsonEntity(final JsonParser parser, final Class<T> clazzType, HashMap<String, PropertyPair> classProperties, final EntityResolver<R> resolver, final TableRequestOptions options, final OperationContext opContext) throws JsonParseException, IOException, ParseException, StorageException, InstantiationException, IllegalAccessException { final TableResult res = new TableResult(); final HashMap<String, EntityProperty> properties = new HashMap<String, EntityProperty>(); if (!parser.hasCurrentToken()) { parser.nextToken(); } ODataUtilities.assertIsStartObjectJsonToken(parser); parser.nextToken(); // get all metadata, if present while (parser.getCurrentName().startsWith(ODataConstants.ODATA_PREFIX)) { final String name = parser.getCurrentName().substring(ODataConstants.ODATA_PREFIX.length()); // get the value token parser.nextToken(); if (name.equals(ODataConstants.ETAG)) { String etag = parser.getValueAsString(); res.setEtag(etag); } // get the key token parser.nextToken(); } if (resolver == null && clazzType == null) { return res; } // get object properties while (parser.getCurrentToken() != JsonToken.END_OBJECT) { String key = Constants.EMPTY_STRING; String val = Constants.EMPTY_STRING; EdmType edmType = null; // checks if this property is preceded by an OData property type annotation if (options.getTablePayloadFormat() != TablePayloadFormat.JsonNoMetadata && parser.getCurrentName().endsWith(ODataConstants.ODATA_TYPE_SUFFIX)) { parser.nextToken(); edmType = EdmType.parse(parser.getValueAsString()); parser.nextValue(); key = parser.getCurrentName(); val = parser.getValueAsString(); } else { key = parser.getCurrentName(); parser.nextToken(); val = parser.getValueAsString(); edmType = evaluateEdmType(parser.getCurrentToken(), parser.getValueAsString()); } final EntityProperty newProp = new EntityProperty(val, edmType); properties.put(key, newProp); parser.nextToken(); } String partitionKey = null; String rowKey = null; Date timestamp = null; String etag = null; // Remove core properties from map and set individually EntityProperty tempProp = properties.remove(TableConstants.PARTITION_KEY); if (tempProp != null) { partitionKey = tempProp.getValueAsString(); } tempProp = properties.remove(TableConstants.ROW_KEY); if (tempProp != null) { rowKey = tempProp.getValueAsString(); } tempProp = properties.remove(TableConstants.TIMESTAMP); if (tempProp != null) { timestamp = tempProp.getValueAsDate(); if (res.getEtag() == null) { etag = getETagFromTimestamp(tempProp.getValueAsString()); res.setEtag(etag); } } // do further processing for type if JsonNoMetdata by inferring type information via resolver or clazzType if (options.getTablePayloadFormat() == TablePayloadFormat.JsonNoMetadata && (options.getPropertyResolver() != null || clazzType != null)) { if (options.getPropertyResolver() != null) { for (final Entry<String, EntityProperty> p : properties.entrySet()) { final String key = p.getKey(); final String value = p.getValue().getValueAsString(); EdmType edmType; // try to use the property resolver to get the type try { edmType = options.getPropertyResolver().propertyResolver(partitionKey, rowKey, key, value); } catch (Exception e) { throw new StorageException(StorageErrorCodeStrings.INTERNAL_ERROR, SR.CUSTOM_RESOLVER_THREW, Constants.HeaderConstants.HTTP_UNUSED_306, null, e); } // try to create a new entity property using the returned type try { final EntityProperty newProp = new EntityProperty(value, edmType); properties.put(p.getKey(), newProp); } catch (IllegalArgumentException e) { throw new StorageException(StorageErrorCodeStrings.INVALID_TYPE, String.format(SR.FAILED_TO_PARSE_PROPERTY, key, value, edmType), Constants.HeaderConstants.HTTP_UNUSED_306, null, e); } } } else if (clazzType != null) { if (classProperties == null) { classProperties = PropertyPair.generatePropertyPairs(clazzType); } for (final Entry<String, EntityProperty> p : properties.entrySet()) { PropertyPair propPair = classProperties.get(p.getKey()); if (propPair != null) { final EntityProperty newProp = new EntityProperty(p.getValue().getValueAsString(), propPair.type); properties.put(p.getKey(), newProp); } } } } // set the result properties, now that they are appropriately parsed res.setProperties(properties); // use resolver if provided, else create entity based on clazz type if (resolver != null) { res.setResult(resolver.resolve(partitionKey, rowKey, timestamp, res.getProperties(), res.getEtag())); } else if (clazzType != null) { // Generate new entity and return final T entity = clazzType.newInstance(); entity.setEtag(res.getEtag()); entity.setPartitionKey(partitionKey); entity.setRowKey(rowKey); entity.setTimestamp(timestamp); entity.readEntity(res.getProperties(), opContext); res.setResult(entity); } return res; }