Java Code Examples for com.fasterxml.jackson.core.JsonToken#equals()

The following examples show how to use com.fasterxml.jackson.core.JsonToken#equals() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: UriDeserializer.java    From Partner-Center-Java with MIT License 6 votes vote down vote up
@Override
public URI deserialize(JsonParser parser, DeserializationContext context)
		throws IOException, JsonProcessingException
{
	JsonToken currentToken = parser.getCurrentToken();
	if (currentToken.equals(JsonToken.VALUE_STRING))
	{
		String linkUri = parser.getText().trim();

        try
        {
			return new URI (linkUri);
		}
        catch (URISyntaxException e)
        {
			PartnerLog.getInstance().logError(e.toString());
		}
	}
	else if(currentToken.equals(JsonToken.VALUE_NULL))
	{
		return null;
	}
	
	context.handleUnexpectedToken(URI.class, parser); 
	throw JsonMappingException.from(parser, null);
}
 
Example 2
Source File: JsonJacksonFormat.java    From jigsaw-payment with Apache License 2.0 6 votes vote down vote up
/**
 * Parse a text-format message from {@code input} and merge the contents into {@code builder}.
 * Extensions will be recognized if they are registered in {@code extensionRegistry}.
 * @throws IOException
 */
public void merge(JsonParser parser,
						 ExtensionRegistry extensionRegistry,
                         Message.Builder builder) throws IOException {

    JsonToken token = parser.nextToken();
    if (token.equals(JsonToken.START_OBJECT)) {
    	token = parser.nextToken();
    }
    while (token != null && !token.equals(JsonToken.END_OBJECT)) {
    	mergeField(parser, extensionRegistry, builder);
    	token = parser.nextToken();
    }

    // Test to make sure the tokenizer has reached the end of the stream.
    if (parser.nextToken() != null) {
        throw new RuntimeException("Expecting the end of the stream, but there seems to be more data!  Check the input for a valid JSON format.");
    }
}
 
Example 3
Source File: JsonProcessor.java    From odata with Apache License 2.0 6 votes vote down vote up
/**
 * Process an embedded object.
 *
 * @param jsonParser the parser
 * @return map with embedded object key:values
 * @throws IOException If unable to read input parser
 */
private Object getEmbeddedObject(JsonParser jsonParser) throws IOException {
    LOG.info("Start parsing an embedded object.");
    Map<String, Object> embeddedMap = new HashMap<>();
    while (jsonParser.nextToken() != JsonToken.END_OBJECT) {
        String key = jsonParser.getText();
        jsonParser.nextToken();
        JsonToken token = jsonParser.getCurrentToken();
        if (token == JsonToken.START_ARRAY) {
            Object embeddedArray = getCollectionValue(jsonParser);
            embeddedMap.put(key, embeddedArray);
        } else if (token == JsonToken.START_OBJECT) {
            Object embeddedObject = getEmbeddedObject(jsonParser);
            embeddedMap.put(key, embeddedObject);
        } else {
            if (token.equals(JsonToken.VALUE_NULL)) {
                embeddedMap.put(key, null);
            } else {
                embeddedMap.put(key, jsonParser.getText());
            }
        }
    }
    return embeddedMap;
}
 
Example 4
Source File: JsonJacksonFormat.java    From jigsaw-payment with Apache License 2.0 6 votes vote down vote up
private void handleMissingField(String fieldName, JsonParser parser,
                                       ExtensionRegistry extensionRegistry,
                                       UnknownFieldSet.Builder builder) throws IOException {

    JsonToken token = parser.nextToken();
    if (token.equals(JsonToken.START_OBJECT)) {
        // Message structure
    	token = parser.nextToken(); // skip name
    	while (token != null && !token.equals(JsonToken.END_OBJECT)) {
            handleMissingField(fieldName, parser, extensionRegistry, builder);
            token = parser.nextToken(); // get } or field name
        }
    } else if (token.equals(JsonToken.START_ARRAY)) {
        // Collection
        do {
            handleMissingField(fieldName, parser, extensionRegistry, builder);
            token = parser.getCurrentToken(); // got value or ]
        } while (token != null && !token.equals(JsonToken.END_ARRAY));
    } else {
        // Primitive value
    	// NULL, INT, BOOL, STRING
    	// nothing to do..
    }
}
 
Example 5
Source File: AbstractCipherResourceEncryptor.java    From spring-cloud-config with Apache License 2.0 6 votes vote down vote up
protected String decryptWithJacksonParser(String text, String name, String[] profiles,
		JsonFactory factory) throws IOException {
	Set<String> valsToDecrpyt = new HashSet<String>();
	JsonParser parser = factory.createParser(text);
	JsonToken token;

	while ((token = parser.nextToken()) != null) {
		if (token.equals(JsonToken.VALUE_STRING)
				&& parser.getValueAsString().startsWith(CIPHER_MARKER)) {
			valsToDecrpyt.add(parser.getValueAsString().trim());
		}
	}

	for (String value : valsToDecrpyt) {
		String decryptedValue = decryptValue(value.replace(CIPHER_MARKER, ""), name,
				profiles);
		text = text.replace(value, decryptedValue);
	}

	return text;
}
 
Example 6
Source File: BooleanStringDeserializer.java    From entando-core with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public Boolean deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
    JsonToken currentToken = jp.getCurrentToken();

    if (currentToken.equals(JsonToken.VALUE_STRING)) {
        String text = jp.getText().trim();
        if (TRUE.equalsIgnoreCase(text)) {
            return Boolean.TRUE;
        } else if (FALSE.equalsIgnoreCase(text)) {
            return Boolean.FALSE;
        } else {
            logger.warn("only {}, {} and {}, {} values are supported as boolean input", TRUE, "\"true\"", FALSE, "\"false\"");
            ;
            return null;
        }

    } else if (currentToken.equals(JsonToken.VALUE_NULL)) {
        return null;
    } else if (currentToken.equals(JsonToken.VALUE_TRUE)) {
        return Boolean.TRUE;
    } else if (currentToken.equals(JsonToken.VALUE_FALSE)) {
        return Boolean.FALSE;

    }
    throw ctxt.mappingException(Boolean.class);
}
 
Example 7
Source File: RemoveStopWords.java    From algoliasearch-client-java-2 with MIT License 6 votes vote down vote up
@Override
public RemoveStopWords deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
  JsonToken currentToken = p.getCurrentToken();

  if (currentToken.equals(JsonToken.VALUE_FALSE) || currentToken.equals(JsonToken.VALUE_TRUE)) {
    return RemoveStopWords.of(p.getBooleanValue());
  }

  if (currentToken == JsonToken.START_ARRAY) {

    List<String> removeStopWords = new ArrayList<>();

    while (p.nextToken() != JsonToken.END_ARRAY) {
      removeStopWords.add(p.getValueAsString());
    }
    return RemoveStopWords.of(removeStopWords);
  }

  throw new AlgoliaRuntimeException("Unsupported deserialization for RemoveStopWords");
}
 
Example 8
Source File: AroundRadius.java    From algoliasearch-client-java-2 with MIT License 5 votes vote down vote up
@Override
public AroundRadius deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
  JsonToken currentToken = p.getCurrentToken();
  if (currentToken.equals(JsonToken.VALUE_STRING)) {
    return AroundRadius.of(p.getValueAsString());
  }

  return AroundRadius.of(p.getIntValue());
}
 
Example 9
Source File: JsonCasDeserializer.java    From termsuite-core with Apache License 2.0 5 votes vote down vote up
private static void FillTermOccAnnotations(JsonParser parser , JsonToken token, TermOccAnnotation toa, CAS cas) throws IOException, CASException {
    if (token.equals(JsonToken.FIELD_NAME)){
        switch (parser.getCurrentName()){
            case F_PATTERN :
                String[] patternTable = parser.nextTextValue().split(" ");
                StringArray stringArray = new StringArray(cas.getJCas(), patternTable.length);

                for (int i = 0; i < patternTable.length; i++){
                    stringArray.set(i,patternTable[i]);
                }
                toa.setPattern(stringArray);
                break;

            case F_SPOTTING_RULE_NAME :
                toa.setSpottingRuleName(parser.nextTextValue());
                break;
            case F_TERM_KEY :
                toa.setTermKey(parser.nextTextValue());
                break;
            case F_WORDS :
                fillWords(toa,cas);
                break;
            case F_BEGIN :
                toa.setBegin(parser.nextIntValue(0));
                break;
            case F_END :
                toa.setEnd(parser.nextIntValue(0));
                break;
        }
    }
}
 
Example 10
Source File: JsonCasDeserializer.java    From termsuite-core with Apache License 2.0 5 votes vote down vote up
private static void fillSdi(JsonParser parser , JsonToken token, SourceDocumentInformation sdi) throws IOException {
    if (token.equals(JsonToken.FIELD_NAME)){
        switch (parser.getCurrentName()){
            case F_URI :
                sdi.setUri(parser.nextTextValue());
                break;
            case F_OFFSET_IN_SOURCE :
                sdi.setOffsetInSource(parser.nextIntValue(0));
                break;
            case F_DOCUMENT_INDEX :
                sdi.setDocumentIndex(parser.nextIntValue(0));
                break;
            case F_NB_DOCUMENTS :
                sdi.setNbDocuments(parser.nextIntValue(0));
                break;
            case F_DOCUMENT_SIZE :
                sdi.setDocumentSize(parser.nextIntValue(0));
                break;
            case F_CUMULATED_DOCUMENT_SIZE :
                sdi.setCumulatedDocumentSize(parser.nextLongValue(0));
                break;
            case F_CORPUS_SIZE :
                sdi.setCorpusSize(parser.nextLongValue(0));
                break;
            case F_LAST_SEGMENT :
                sdi.setLastSegment(parser.nextBooleanValue());
                break;
            case F_BEGIN :
                sdi.setBegin(parser.nextIntValue(0));
                break;
            case F_END :
                sdi.setEnd(parser.nextIntValue(0));
                break;
        }
    }
}
 
Example 11
Source File: NpmPublishParser.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Requires that the current token is of a specified type.
 */
private void requireToken(final JsonToken token) throws IOException {
  if (!token.equals(currentToken())) {
    throw new IllegalStateException(
        "Expected " + token + " but found " + currentToken() + " at " + jsonParser.getCurrentLocation());
  }
}
 
Example 12
Source File: Distinct.java    From algoliasearch-client-java-2 with MIT License 5 votes vote down vote up
@Override
public Distinct deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
  JsonToken currentToken = p.getCurrentToken();
  if (currentToken.equals(JsonToken.VALUE_NUMBER_INT)) {
    return Distinct.of(p.getIntValue());
  }

  return Distinct.of(p.getBooleanValue());
}
 
Example 13
Source File: Event.java    From data-highway with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("deprecation")
private void expect(JsonToken token, JsonToken expected, DeserializationContext context)
  throws JsonMappingException {
  if (!token.equals(expected)) {
    context.mappingException("Expected JsonToken %s but got %s", expected, token);
  }
}
 
Example 14
Source File: JSONReader.java    From bigquery-etl-dataflow-sample with Apache License 2.0 5 votes vote down vote up
/**
 * Reads an MusicBrainzDataObject from a json string.
 *
 * @param objectName - the namespace for the object
 * @param json       the json string
 * @return
 */
public static MusicBrainzDataObject readObject(String objectName, String json) {
  MusicBrainzDataObject datum = new MusicBrainzDataObject(objectName);
  JsonFactory factory = new JsonFactory();
  try {
    JsonParser parser = factory.createParser(json);
    parser.setCodec(new ObjectMapper());
    while (!parser.isClosed()) {
      JsonToken token = parser.nextToken();

      if (token != null && token.equals(JsonToken.START_OBJECT)) {

        JsonNode jsonTree = parser.readValueAsTree();
        jsonTree.fields().forEachRemaining(entry -> {
          if (entry.getValue() != null) {
            Object value = nodeValueToObject(entry.getValue());
            if (value == null) {
              //  NOOP - unknown node type
            } else {
              datum.addColumnValue(entry.getKey(), nodeValueToObject(entry.getValue()));
            }
          } else {
            logger.warn("null value for entry : " + entry.getKey());
          }
        });
      }
    }
  } catch (Exception e) {
    logger.error("parse exception", e);
  }
  return datum;
}
 
Example 15
Source File: JsonJacksonFormat.java    From jigsaw-payment with Apache License 2.0 5 votes vote down vote up
private Object handleObject(JsonParser parser,
                                   ExtensionRegistry extensionRegistry,
                                   Message.Builder builder,
                                   FieldDescriptor field,
                                   ExtensionRegistry.ExtensionInfo extension,
                                   boolean unknown) throws IOException {

    Message.Builder subBuilder;
    if (extension == null) {
        subBuilder = builder.newBuilderForField(field);
    } else {
        subBuilder = extension.defaultInstance.newBuilderForType();
    }

    JsonToken token = parser.getCurrentToken();
    if (JsonToken.VALUE_NULL == token) {
        return null;
    }

    if (unknown) {
    	ByteString data = ByteString.copyFrom(parser.getBinaryValue());
        try {
            subBuilder.mergeFrom(data);
            return subBuilder.build();
        } catch (InvalidProtocolBufferException e) {
            throw new RuntimeException("Failed to build " + field.getFullName() + " from " + data);
        }
    }

    //token = parser.nextToken();
    if (token.equals(JsonToken.START_OBJECT)) {
     token = parser.nextToken();
     while (token != null && !token.equals(JsonToken.END_OBJECT)) {
         mergeField(parser, extensionRegistry, subBuilder);
         token = parser.nextToken();
     }
    }
    return subBuilder.build();
}
 
Example 16
Source File: TimeDeserializer.java    From paseto with MIT License 5 votes vote down vote up
@Override
public Long deserialize(JsonParser p, DeserializationContext ctxt)
		throws IOException, JsonProcessingException {
	JsonToken token = p.getCurrentToken();

	if (token.equals(JsonToken.VALUE_STRING)) {
		return Token.DATETIME_FORMATTER.parse(p.getValueAsString()).toEpochSecond();
	} else {
		return getNullValue(ctxt);
	}
}
 
Example 17
Source File: AbstractConfigurationValidator.java    From deprecated-security-advanced-modules with Apache License 2.0 5 votes vote down vote up
private boolean checkDatatypes() throws Exception {
    String contentAsJson = XContentHelper.convertToJson(content, false, XContentType.JSON);
    try (JsonParser parser = factory.createParser(contentAsJson)) {
        JsonToken token = null;
        while ((token = parser.nextToken()) != null) {
            if (token.equals(JsonToken.FIELD_NAME)) {
                String currentName = parser.getCurrentName();
                DataType dataType = allowedKeys.get(currentName);
                if (dataType != null) {
                    JsonToken valueToken = parser.nextToken();
                    switch (dataType) {
                        case STRING:
                            if (!valueToken.equals(JsonToken.VALUE_STRING)) {
                                wrongDatatypes.put(currentName, "String expected");
                            }
                            break;
                        case ARRAY:
                            if (!valueToken.equals(JsonToken.START_ARRAY) && !valueToken.equals(JsonToken.END_ARRAY)) {
                                wrongDatatypes.put(currentName, "Array expected");
                            }
                            break;
                        case OBJECT:
                            if (!valueToken.equals(JsonToken.START_OBJECT) && !valueToken.equals(JsonToken.END_OBJECT)) {
                                wrongDatatypes.put(currentName, "Object expected");
                            }
                            break;
                    }
                }
            }
        }
        return wrongDatatypes.isEmpty();
    }
}
 
Example 18
Source File: JsonJacksonFormat.java    From jigsaw-payment with Apache License 2.0 4 votes vote down vote up
/**
 * Parse a single field from {@code parser} and merge it into {@code builder}. If a ',' is
 * detected after the field ends, the next field will be parsed automatically
 * @throws IOException
 * @throws JsonParseException
 */
protected void mergeField(JsonParser parser,
                               ExtensionRegistry extensionRegistry,
                               Message.Builder builder) throws JsonParseException, IOException {
    FieldDescriptor field = null;
    Descriptor type = builder.getDescriptorForType();
    boolean unknown = false;
    ExtensionRegistry.ExtensionInfo extension = null;
    JsonToken token = parser.getCurrentToken();

    if (token != null) {
        String name = parser.getCurrentName();

        if (name.contains(".")) {
        	// should be an extension
        	extension = extensionRegistry.findExtensionByName(name);
            if (extension == null) {
                throw new RuntimeException("Extension \""
                		+ name + "\" not found in the ExtensionRegistry.");
            } else if (extension.descriptor.getContainingType() != type) {
                throw new RuntimeException("Extension \"" + name
                		+ "\" does not extend message type \""
                		+ type.getFullName() + "\".");
            }

        	field = extension.descriptor;
        } else {
        	field = type.findFieldByName(name);
        }

        // Group names are expected to be capitalized as they appear in the
        // .proto file, which actually matches their type names, not their field
        // names.
        if (field == null) {
            // Explicitly specify US locale so that this code does not break when
            // executing in Turkey.
            String lowerName = name.toLowerCase(Locale.US);
            field = type.findFieldByName(lowerName);
            // If the case-insensitive match worked but the field is NOT a group,
            if ((field != null) && (field.getType() != FieldDescriptor.Type.GROUP)) {
                field = null;
            }
        }
        // Again, special-case group names as described above.
        if ((field != null) && (field.getType() == FieldDescriptor.Type.GROUP)
            && !field.getMessageType().getName().equals(name)
            && !field.getMessageType().getFullName().equalsIgnoreCase(name) /* extension */) {
            field = null;
        }

        // Last try to lookup by field-index if 'name' is numeric,
        // which indicates a possible unknown field
        if (field == null && TextUtils.isDigits(name)) {
            field = type.findFieldByNumber(Integer.parseInt(name));
            unknown = true;
        }

        // no throwing exceptions if field not found, since it could be a different version.
        if (field == null) {
        	UnknownFieldSet.Builder unknownsBuilder = UnknownFieldSet.newBuilder();
        	handleMissingField(name, parser, extensionRegistry, unknownsBuilder);
        	builder.setUnknownFields(unknownsBuilder.build());
        }
    }

    if (field != null) {
    	token = parser.nextToken();

        boolean array = token.equals(JsonToken.START_ARRAY);

        if (array) {
        	token = parser.nextToken();
            while (!token.equals(JsonToken.END_ARRAY)) {
                handleValue(parser, extensionRegistry, builder, field, extension, unknown);
                token = parser.nextToken();
            }
        } else {
            handleValue(parser, extensionRegistry, builder, field, extension, unknown);
        }
    }
}
 
Example 19
Source File: MessageDeserializer.java    From jackson-datatype-protobuf with Apache License 2.0 4 votes vote down vote up
@Override
protected void populate(
        V builder,
        JsonParser parser,
        DeserializationContext context
) throws IOException {
  JsonToken token = parser.getCurrentToken();
  if (token == JsonToken.START_ARRAY) {
    token = parser.nextToken();
  }

  switch (token) {
    case END_OBJECT:
      return;
    case START_OBJECT:
      token = parser.nextToken();
      if (token == JsonToken.END_OBJECT) {
        return;
      }
      break;
    default:
      break; // make findbugs happy
  }

  final Descriptor descriptor = builder.getDescriptorForType();
  final Map<String, FieldDescriptor> fieldLookup = buildFieldLookup(descriptor, context);
  final Map<String, ExtensionInfo> extensionLookup;
  if (builder instanceof ExtendableMessageOrBuilder<?>) {
    extensionLookup = buildExtensionLookup(descriptor, context);
  } else {
    extensionLookup = Collections.emptyMap();
  }

  do {
    if (!token.equals(JsonToken.FIELD_NAME)) {
      throw reportWrongToken(JsonToken.FIELD_NAME, context, "");
    }

    String name = parser.getCurrentName();
    FieldDescriptor field = fieldLookup.get(name);
    Message defaultInstance = null;
    if (field == null) {
      ExtensionInfo extensionInfo = extensionLookup.get(name);
      if (extensionInfo != null) {
        field = extensionInfo.descriptor;
        defaultInstance = extensionInfo.defaultInstance;
      }
    }

    if (field == null) {
      context.handleUnknownProperty(parser, this, builder, name);
      parser.nextToken();
      parser.skipChildren();
      continue;
    }

    parser.nextToken();
    setField(builder, field, defaultInstance, parser, context);
  } while ((token = parser.nextToken()) != JsonToken.END_OBJECT);
}
 
Example 20
Source File: JsonCasDeserializer.java    From termsuite-core with Apache License 2.0 4 votes vote down vote up
private static void fillWordAnnotations(JsonParser parser, JsonToken token, WordAnnotation wa) throws IOException {
    if (token.equals(JsonToken.FIELD_NAME)){
        switch (parser.getCurrentName()){
            case F_CATEGORY :
                wa.setCategory(parser.nextTextValue());
                break;
            case F_LEMMA :
                wa.setLemma(parser.nextTextValue());
                break;
            case F_STEM :
                wa.setStem(parser.nextTextValue());
                break;
            case F_TAG :
                wa.setTag(parser.nextTextValue());
                break;
            case F_SUB_CATEGORY :
                wa.setSubCategory(parser.nextTextValue());
                break;
            case F_REGEX_LABEL :
                wa.setRegexLabel(parser.nextTextValue());
                break;
            case F_NUMBER :
                wa.setNumber(parser.nextTextValue());
                break;
            case F_GENDER :
                wa.setGender(parser.nextTextValue());
                break;
            case F_CASE :
                wa.setCase(parser.nextTextValue());
                break;
            case F_MOOD :
                wa.setMood(parser.nextTextValue());
                break;
            case F_TENSE :
                wa.setTense(parser.nextTextValue());
                break;
            case F_PERSON :
                wa.setPerson(parser.nextTextValue());
                break;
            case F_DEGREE :
                wa.setDegree(parser.nextTextValue());
                break;
            case F_FORMATION :
                wa.setFormation(parser.nextTextValue());
                break;
            case F_LABELS :
                wa.setLabels(parser.nextTextValue());
                break;
            case F_BEGIN :
                wa.setBegin(parser.nextIntValue(0));
                break;
            case F_END :
                wa.setEnd(parser.nextIntValue(0));
                break;
        }
    }
}