Java 类com.fasterxml.jackson.core.JsonParser.Feature 实例源码

项目:hive-jq-udtf    文件:JsonQueryUDTF.java   
private StructObjectInspector initialize(final ObjectInspector jsonArg, final ObjectInspector jqArg, final List<ObjectInspector> nameAndTypeArgs) throws UDFArgumentException {
    this.in = Arguments.asString(jsonArg, "JSON");

    try {
        this.jq = JsonQuery.compile(Arguments.asConstantNonNullString(jqArg, "JQ"));
    } catch (final JsonQueryException e) {
        throw new UDFArgumentException("JQ is invalid: " + e.getMessage());
    }

    this.marshaller = ResultObjectMarshallers.create(Arguments.asConstantNonNullStrings(nameAndTypeArgs, "TYPE or NAME:TYPE"));

    this.scope = new Scope();
    this.mapper = new ObjectMapper(new JsonFactory().enable(Feature.ALLOW_UNQUOTED_CONTROL_CHARS));

    return marshaller.objectInspector();
}
项目:GitHub    文件:AsyncMissingValuesInArrayTest.java   
@Test
  public void testArrayInnerComma() throws Exception {
  String json = "[\"a\",, \"b\"]";

  AsyncReaderWrapper p = createParser(factory, json);

  assertEquals(JsonToken.START_ARRAY, p.nextToken());

  assertToken(JsonToken.VALUE_STRING, p.nextToken());
  assertEquals("a", p.currentText());

  if (!features.contains(Feature.ALLOW_MISSING_VALUES)) {
    assertUnexpected(p, ',');
    return;
  }

  assertToken(JsonToken.VALUE_NULL, p.nextToken());

  assertToken(JsonToken.VALUE_STRING, p.nextToken());
  assertEquals("b", p.currentText());

  assertEquals(JsonToken.END_ARRAY, p.nextToken());
  assertEnd(p);
}
项目:GitHub    文件:AsyncMissingValuesInArrayTest.java   
@Test
public void testArrayLeadingComma() throws Exception {
  String json = "[,\"a\", \"b\"]";

  AsyncReaderWrapper p = createParser(factory, json);

  assertEquals(JsonToken.START_ARRAY, p.nextToken());

  if (!features.contains(Feature.ALLOW_MISSING_VALUES)) {
    assertUnexpected(p, ',');
    return;
  }

  assertToken(JsonToken.VALUE_NULL, p.nextToken());

  assertToken(JsonToken.VALUE_STRING, p.nextToken());
  assertEquals("a", p.currentText());

  assertToken(JsonToken.VALUE_STRING, p.nextToken());
  assertEquals("b", p.currentText());

  assertEquals(JsonToken.END_ARRAY, p.nextToken());
  assertEnd(p);
  p.close();
}
项目:GitHub    文件:AsyncMissingValuesInObjectTest.java   
@Test
public void testObjectTrailingComma() throws Exception {
  String json = "{\"a\": true, \"b\": false,}";

  AsyncReaderWrapper p = createParser(factory, json);

  assertEquals(JsonToken.START_OBJECT, p.nextToken());

  assertToken(JsonToken.FIELD_NAME, p.nextToken());
  assertEquals("a", p.currentText());
  assertToken(JsonToken.VALUE_TRUE, p.nextToken());

  assertToken(JsonToken.FIELD_NAME, p.nextToken());
  assertEquals("b", p.currentText());
  assertToken(JsonToken.VALUE_FALSE, p.nextToken());

  if (features.contains(Feature.ALLOW_TRAILING_COMMA)) {
    assertToken(JsonToken.END_OBJECT, p.nextToken());
    assertEnd(p);
  } else {
    assertUnexpected(p, '}');
  }
  p.close();
}
项目:GitHub    文件:TrailingCommasTest.java   
@SuppressWarnings("resource")
@Test
public void testArrayInnerComma() throws Exception {
  String json = "[\"a\",, \"b\"]";

  JsonParser p = createParser(factory, mode, json);

  assertEquals(JsonToken.START_ARRAY, p.nextToken());

  assertToken(JsonToken.VALUE_STRING, p.nextToken());
  assertEquals("a", p.getText());

  if (!features.contains(Feature.ALLOW_MISSING_VALUES)) {
    assertUnexpected(p, ',');
    return;
  }

  assertToken(JsonToken.VALUE_NULL, p.nextToken());

  assertToken(JsonToken.VALUE_STRING, p.nextToken());
  assertEquals("b", p.getText());

  assertEquals(JsonToken.END_ARRAY, p.nextToken());
  assertEnd(p);
}
项目:GitHub    文件:TrailingCommasTest.java   
@SuppressWarnings("resource")
@Test
public void testArrayLeadingComma() throws Exception {
  String json = "[,\"a\", \"b\"]";

  JsonParser p = createParser(factory, mode, json);

  assertEquals(JsonToken.START_ARRAY, p.nextToken());

  if (!features.contains(Feature.ALLOW_MISSING_VALUES)) {
    assertUnexpected(p, ',');
    return;
  }

  assertToken(JsonToken.VALUE_NULL, p.nextToken());

  assertToken(JsonToken.VALUE_STRING, p.nextToken());
  assertEquals("a", p.getText());

  assertToken(JsonToken.VALUE_STRING, p.nextToken());
  assertEquals("b", p.getText());

  assertEquals(JsonToken.END_ARRAY, p.nextToken());
  assertEnd(p);
  p.close();
}
项目:GitHub    文件:TrailingCommasTest.java   
@Test
public void testObjectTrailingComma() throws Exception {
  String json = "{\"a\": true, \"b\": false,}";

  JsonParser p = createParser(factory, mode, json);

  assertEquals(JsonToken.START_OBJECT, p.nextToken());

  assertToken(JsonToken.FIELD_NAME, p.nextToken());
  assertEquals("a", p.getText());
  assertToken(JsonToken.VALUE_TRUE, p.nextToken());

  assertToken(JsonToken.FIELD_NAME, p.nextToken());
  assertEquals("b", p.getText());
  assertToken(JsonToken.VALUE_FALSE, p.nextToken());

  if (features.contains(Feature.ALLOW_TRAILING_COMMA)) {
    assertToken(JsonToken.END_OBJECT, p.nextToken());
    assertEnd(p);
  } else {
    assertUnexpected(p, '}');
  }
  p.close();
}
项目:dremio-oss    文件:LogicalPlanPersistence.java   
public LogicalPlanPersistence(SabotConfig conf, ScanResult scanResult) {
  mapper = new ObjectMapper();

  SimpleModule deserModule = new SimpleModule("LogicalExpressionDeserializationModule")
      .addDeserializer(LogicalExpression.class, new LogicalExpression.De(conf))
      .addDeserializer(SchemaPath.class, new SchemaPath.De());

  mapper.registerModule(new AfterburnerModule());
  mapper.registerModule(deserModule);
  mapper.enable(SerializationFeature.INDENT_OUTPUT);
  mapper.configure(Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
  mapper.configure(JsonGenerator.Feature.QUOTE_FIELD_NAMES, true);
  mapper.configure(Feature.ALLOW_COMMENTS, true);
  registerSubtypes(LogicalOperatorBase.getSubTypes(scanResult));
  registerSubtypes(StoragePluginConfigBase.getSubTypes(scanResult));
  registerSubtypes(FormatPluginConfigBase.getSubTypes(scanResult));
}
项目:geoportal-server-harvester    文件:AgsClient.java   
/**
 * Reads service information.
 *
 * @param folder folder
 * @param si service info obtained through {@link listContent}
 * @return service response
 * @throws URISyntaxException if invalid URL
 * @throws IOException if accessing token fails
 */
public ServerResponse readServiceInformation(String folder, ServiceInfo si) throws URISyntaxException, IOException {
  String url = rootUrl.toURI().resolve("rest/services/").resolve(StringUtils.stripToEmpty(folder)).resolve(si.name + "/" + si.type).toASCIIString();
  HttpGet get = new HttpGet(url + String.format("?f=%s", "json"));

  try (CloseableHttpResponse httpResponse = httpClient.execute(get); InputStream contentStream = httpResponse.getEntity().getContent();) {
    if (httpResponse.getStatusLine().getStatusCode()>=400) {
      throw new HttpResponseException(httpResponse.getStatusLine().getStatusCode(), httpResponse.getStatusLine().getReasonPhrase());
    }
    String responseContent = IOUtils.toString(contentStream, "UTF-8");
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    mapper.configure(Feature.ALLOW_NON_NUMERIC_NUMBERS, true);
    mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    ServerResponse response = mapper.readValue(responseContent, ServerResponse.class);
    response.url = url;
    response.json = responseContent;
    return response;
  }
}
项目:simbest-cores    文件:JacksonObjectMapperConfig.java   
public JacksonObjectMapperConfig() {
    super();

    this.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);        
    //this.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false); 不增加,避免key值为null,而避免节点消失
    this.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    this.configure(Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true); 

    //this.setSerializationInclusion(Include.NON_EMPTY); //对象转字符串时,只转化非空字段 zjs 需要占位

    //SimpleModule module = new SimpleModule();
       SimpleModule module = new SimpleModule("HTML XSS Serializer",
               new Version(1, 0, 0, "FINAL", "com.simbest", "ep-jsonmodule"));
       module.addSerializer(new JsonHtmlXssSerializer(String.class));
       module.addDeserializer(Date.class, new CustomJsonDateDeseralizer());
       // Add more here ...
       registerModule(module);
}
项目:coordinated-entry    文件:MatchProcessLog.java   
public void setStatusMessage(String statusMessage) {
    try {
        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(Feature.ALLOW_UNQUOTED_FIELD_NAMES,true);
        mapper.configure(Feature.ALLOW_SINGLE_QUOTES,true);
        mapper.configure(Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true);
        JsonNode node = mapper.readValue(statusMessage.getBytes(), JsonNode.class);
        this.statusMessage = node.get("statusMessage").asText();
        this.additionalInfo = node.get("additionalInfo");
        this.step = node.get("step").asText();
    } catch (Exception e) {
        System.out.println(statusMessage);
    //  e.printStackTrace();
    }

}
项目:drill    文件:LogicalPlanPersistence.java   
public LogicalPlanPersistence(DrillConfig conf, ScanResult scanResult) {
  mapper = new ObjectMapper();

  SimpleModule deserModule = new SimpleModule("LogicalExpressionDeserializationModule")
      .addDeserializer(LogicalExpression.class, new LogicalExpression.De(conf))
      .addDeserializer(SchemaPath.class, new SchemaPath.De());

  mapper.registerModule(deserModule);
  mapper.enable(SerializationFeature.INDENT_OUTPUT);
  mapper.configure(Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
  mapper.configure(JsonGenerator.Feature.QUOTE_FIELD_NAMES, true);
  mapper.configure(Feature.ALLOW_COMMENTS, true);
  registerSubtypes(LogicalOperatorBase.getSubTypes(scanResult));
  registerSubtypes(StoragePluginConfigBase.getSubTypes(scanResult));
  registerSubtypes(FormatPluginConfigBase.getSubTypes(scanResult));
}
项目:hawkular-bus    文件:AbstractMessage.java   
/**
 * Convenience static method that reads a JSON string from the given stream and converts the JSON
 * string to a particular message object. The input stream will remain open so the caller can
 * stream any extra data that might appear after it.
 *
 * Because of the way the JSON parser works, some extra data might have been read from the stream
 * that wasn't part of the JSON message but was part of the extra data that came with it. Because of this,
 * the caller should no longer use the given stream but instead read the extra data via the returned
 * object (see {@link BasicMessageWithExtraData#getBinaryData()}) since it will handle this condition
 * properly.
 *
 * @param in input stream that has a JSON string at the head.
 * @param clazz the class whose instance is represented by the JSON string
 *
 * @return a POJO that contains a message object that was represented by the JSON string found
 *         in the stream. This returned POJO will also contain a {@link BinaryData} object that you
 *         can use to stream any additional data that came in the given input stream.
 */
public static <T extends BasicMessage> BasicMessageWithExtraData<T> fromJSON(InputStream in, Class<T> clazz) {
    final T obj;
    final byte[] remainder;
    try (JsonParser parser = new JsonFactory().configure(Feature.AUTO_CLOSE_SOURCE, false).createParser(in)) {
        Method buildObjectMapperForDeserializationMethod = findBuildObjectMapperForDeserializationMethod(clazz);

        final ObjectMapper mapper = (ObjectMapper) buildObjectMapperForDeserializationMethod.invoke(null);
        if (FailOnUnknownProperties.class.isAssignableFrom(clazz)) {
            mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, true);
        }

        obj = mapper.readValue(parser, clazz);
        final ByteArrayOutputStream remainderStream = new ByteArrayOutputStream();
        final int released = parser.releaseBuffered(remainderStream);
        remainder = (released > 0) ? remainderStream.toByteArray() : new byte[0];
    } catch (Exception e) {
        throw new IllegalArgumentException("Stream cannot be converted to JSON object of type [" + clazz + "]", e);
    }
    return new BasicMessageWithExtraData<T>(obj, new BinaryData(remainder, in));
}
项目:hawkular-commons    文件:AbstractMessage.java   
/**
 * Convenience static method that reads a JSON string from the given stream and converts the JSON
 * string to a particular message object. The input stream will remain open so the caller can
 * stream any extra data that might appear after it.
 *
 * Because of the way the JSON parser works, some extra data might have been read from the stream
 * that wasn't part of the JSON message but was part of the extra data that came with it. Because of this,
 * the caller should no longer use the given stream but instead read the extra data via the returned
 * object (see {@link BasicMessageWithExtraData#getBinaryData()}) since it will handle this condition
 * properly.
 *
 * @param in input stream that has a JSON string at the head.
 * @param clazz the class whose instance is represented by the JSON string
 *
 * @return a POJO that contains a message object that was represented by the JSON string found
 *         in the stream. This returned POJO will also contain a {@link BinaryData} object that you
 *         can use to stream any additional data that came in the given input stream.
 */
public static <T extends BasicMessage> BasicMessageWithExtraData<T> fromJSON(InputStream in, Class<T> clazz) {
    final T obj;
    final byte[] remainder;
    try (JsonParser parser = new JsonFactory().configure(Feature.AUTO_CLOSE_SOURCE, false).createParser(in)) {
        Method buildObjectMapperForDeserializationMethod = findBuildObjectMapperForDeserializationMethod(clazz);

        final ObjectMapper mapper = (ObjectMapper) buildObjectMapperForDeserializationMethod.invoke(null);
        if (FailOnUnknownProperties.class.isAssignableFrom(clazz)) {
            mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, true);
        }

        obj = mapper.readValue(parser, clazz);
        final ByteArrayOutputStream remainderStream = new ByteArrayOutputStream();
        final int released = parser.releaseBuffered(remainderStream);
        remainder = (released > 0) ? remainderStream.toByteArray() : new byte[0];
    } catch (Exception e) {
        throw new IllegalArgumentException("Stream cannot be converted to JSON object of type [" + clazz + "]", e);
    }
    return new BasicMessageWithExtraData<T>(obj, new BinaryData(remainder, in));
}
项目:logsniffer    文件:CoreAppConfig.java   
@Bean
public ObjectMapper jsonObjectMapper() {
    final ObjectMapper jsonMapper = new ObjectMapper();
    jsonMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
    jsonMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    jsonMapper.configure(Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
    jsonMapper.configure(Feature.ALLOW_SINGLE_QUOTES, true);
    jsonMapper.configure(MapperFeature.DEFAULT_VIEW_INCLUSION, false);

    final SimpleModule module = new SimpleModule("FieldsMapping", Version.unknownVersion());
    module.setSerializerModifier(new BeanSerializerModifier() {
        @Override
        public JsonSerializer<?> modifyMapSerializer(final SerializationConfig config, final MapType valueType,
                final BeanDescription beanDesc, final JsonSerializer<?> serializer) {
            if (FieldsMap.class.isAssignableFrom(valueType.getRawClass())) {
                return new FieldsMapMixInLikeSerializer();
            } else {
                return super.modifyMapSerializer(config, valueType, beanDesc, serializer);
            }
        }
    });
    jsonMapper.registerModule(module);
    return jsonMapper;
}
项目:QuizUpWinner    文件:UTF8StreamJsonParser.java   
private void _skipComment()
{
  if (!isEnabled(JsonParser.Feature.ALLOW_COMMENTS))
    _reportUnexpectedChar(47, "maybe a (non-standard) comment? (not recognized as one since Feature 'ALLOW_COMMENTS' not enabled for parser)");
  if ((this._inputPtr >= this._inputEnd) && (!loadMore()))
    _reportInvalidEOF(" in a comment");
  byte[] arrayOfByte = this._inputBuffer;
  int i = this._inputPtr;
  this._inputPtr = (i + 1);
  int j = 0xFF & arrayOfByte[i];
  if (j == 47)
  {
    _skipCppComment();
    return;
  }
  if (j == 42)
  {
    _skipCComment();
    return;
  }
  _reportUnexpectedChar(j, "was expecting either '*' or '/' for a comment");
}
项目:QuizUpWinner    文件:UTF8StreamJsonParser.java   
private int _verifyNoLeadingZeroes()
{
  if ((this._inputPtr >= this._inputEnd) && (!loadMore()))
    return 48;
  int i = 0xFF & this._inputBuffer[this._inputPtr];
  int j = i;
  if ((i < 48) || (j > 57))
    return 48;
  if (!isEnabled(JsonParser.Feature.ALLOW_NUMERIC_LEADING_ZEROS))
    reportInvalidNumber("Leading zeroes not allowed");
  this._inputPtr = (1 + this._inputPtr);
  if (j == 48)
    do
    {
      if ((this._inputPtr >= this._inputEnd) && (!loadMore()))
        break;
      int k = 0xFF & this._inputBuffer[this._inputPtr];
      j = k;
      if ((k < 48) || (j > 57))
        return 48;
      this._inputPtr = (1 + this._inputPtr);
    }
    while (j == 48);
  return j;
}
项目:QuizUpWinner    文件:ReaderBasedJsonParser.java   
private void _skipComment()
{
  if (!isEnabled(JsonParser.Feature.ALLOW_COMMENTS))
    _reportUnexpectedChar(47, "maybe a (non-standard) comment? (not recognized as one since Feature 'ALLOW_COMMENTS' not enabled for parser)");
  if ((this._inputPtr >= this._inputEnd) && (!loadMore()))
    _reportInvalidEOF(" in a comment");
  char[] arrayOfChar = this._inputBuffer;
  int i = this._inputPtr;
  this._inputPtr = (i + 1);
  int j = arrayOfChar[i];
  if (j == 47)
  {
    _skipCppComment();
    return;
  }
  if (j == 42)
  {
    _skipCComment();
    return;
  }
  _reportUnexpectedChar(j, "was expecting either '*' or '/' for a comment");
}
项目:QuizUpWinner    文件:ReaderBasedJsonParser.java   
private char _verifyNoLeadingZeroes()
{
  if ((this._inputPtr >= this._inputEnd) && (!loadMore()))
    return '0';
  char c1 = this._inputBuffer[this._inputPtr];
  char c2 = c1;
  if ((c1 < '0') || (c2 > '9'))
    return '0';
  if (!isEnabled(JsonParser.Feature.ALLOW_NUMERIC_LEADING_ZEROS))
    reportInvalidNumber("Leading zeroes not allowed");
  this._inputPtr = (1 + this._inputPtr);
  if (c2 == '0')
    do
    {
      if ((this._inputPtr >= this._inputEnd) && (!loadMore()))
        break;
      char c3 = this._inputBuffer[this._inputPtr];
      c2 = c3;
      if ((c3 < '0') || (c2 > '9'))
        return '0';
      this._inputPtr = (1 + this._inputPtr);
    }
    while (c2 == '0');
  return c2;
}
项目:Stud.IP-FileSync    文件:JacksonRequest.java   
/**
 * Parse response into data model object.
 * 
 * @param unwrap Unwrap datamodel
 * @return Response datamodel
 * @throws IOException
 */
public T parseResponse() throws IOException {
    ObjectReader reader = MAPPER.readerFor(datamodel).without(Feature.AUTO_CLOSE_SOURCE);
    if (datamodel.isAnnotationPresent(JsonRootName.class)) {
        reader = reader.with(DeserializationFeature.UNWRAP_ROOT_VALUE);
    }

    try (final InputStream is = response.getStream()) {
        final T result = reader.readValue(is);

        /*
         * ObjectReader.readValue might not consume the entire inputstream,
         * we skip everything after the json root element.
         * This is needed for proper http connection reuse (keep alive).
         */
        is.skip(Long.MAX_VALUE);

        return result;
    }
}
项目:vethrfolnir-mu    文件:DataMappingService.java   
@Inject
private void load() {
    if(assetManager == null) {
        throw new RuntimeException("AssetManaget has not been set in your setup! Mapping service cannot be performed!");
    }

    defaultTypeFactory = TypeFactory.defaultInstance();

    jsonMapper.setVisibilityChecker(jsonMapper.getDeserializationConfig().getDefaultVisibilityChecker()
            .withCreatorVisibility(JsonAutoDetect.Visibility.NONE)
            .withFieldVisibility(JsonAutoDetect.Visibility.ANY)
            .withGetterVisibility(JsonAutoDetect.Visibility.NONE)
            .withIsGetterVisibility(JsonAutoDetect.Visibility.NONE)
            .withSetterVisibility(JsonAutoDetect.Visibility.NONE));

    jsonMapper.configure(SerializationFeature.INDENT_OUTPUT, true).configure(Feature.ALLOW_COMMENTS, true);

    defaultPrettyPrinter = new DefaultPrettyPrinter();
    defaultPrettyPrinter.indentArraysWith(new Lf2SpacesIndenter());
}
项目:cm_ext    文件:JsonSdlObjectMapper.java   
/**
 * We construct a new jackson object mapper for the parser since we want to
 * add some configuration that we don't want to apply to our global object
 * mapper. This object mapper has the following features:
 *
 * 1. Does not fail if there is an unknown element in the json file, by default.
 * It simply ignores the element and continues reading. This can be reconfigured.
 *
 * 2. We use Mr. Bean for bean materialization during deserialization. Mr Bean
 * uses ASM to create classes at runtime that conform to your abstract class
 * or interface. This allows us to define an immutable interface for the
 * service descriptor and not have to write out all the concrete classes.
 *
 * 3. We add mixin classes to the object mapper to let jackson know of
 * property name remaps.
 * @return
 */
private ObjectMapper createObjectMapper() {
  final Map<Class<?>, Class<?>> mixins = new HashMap<Class<?>, Class<?>>() {{
    put(Parameter.class, ParameterMixin.class);
    put(ConfigGenerator.class, GeneratorMixin.class);
    put(DependencyExtension.class, DependencyExtensionMixin.class);
    put(PlacementRuleDescriptor.class, PlacementRuleMixin.class);
    put(SslServerDescriptor.class, SslServerDescriptorTypeMixin.class);
    put(SslClientDescriptor.class, SslClientDescriptorTypeMixin.class);
  }};

  ObjectMapper m = new ObjectMapper();
  m.registerModule(new SimpleModule() {
    @Override
    public void setupModule(SetupContext context) {
      for (Entry<Class<?>, Class<?>> entry : mixins.entrySet()) {
        context.setMixInAnnotations(entry.getKey(), entry.getValue());
      }
    }
  });
  m.registerModule(new MrBeanModule());
  m.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,
          false);
  m.configure(Feature.ALLOW_COMMENTS, true);
  return m;
}
项目:range    文件:RangeConfigLoader.java   
public RangeConfig loadRangeConfig() {
    try {
        if (source == null) {
            source = Files.newInputStream(this.configFile.toPath());
        }
        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
        mapper.configure(Feature.ALLOW_COMMENTS, true);
        mapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true);
        RangeConfig config = mapper.readValue(this.source, RangeConfig.class);
        logger.info("Loaded range configuration '{}': {}", this.configFile, config);
        return config;
    } catch (IOException e) {
        logger.error("Failed to load range configuration from {}: {}", this.configFile, e);
        return null;
    }
}
项目:druid-api    文件:JSONParseSpec.java   
@JsonCreator
public JSONParseSpec(
    @JsonProperty("timestampSpec") TimestampSpec timestampSpec,
    @JsonProperty("dimensionsSpec") DimensionsSpec dimensionsSpec,
    @JsonProperty("flattenSpec") JSONPathSpec flattenSpec,
    @JsonProperty("featureSpec") Map<String, Boolean> featureSpec
)
{
  super(timestampSpec, dimensionsSpec);
  this.objectMapper = new ObjectMapper();
  this.flattenSpec = flattenSpec != null ? flattenSpec : new JSONPathSpec(true, null);
  this.featureSpec = (featureSpec == null) ? new HashMap<String, Boolean>() : featureSpec;
  for (Map.Entry<String, Boolean> entry : this.featureSpec.entrySet()) {
    Feature feature = Feature.valueOf(entry.getKey());
    objectMapper.configure(feature, entry.getValue());
  }
}
项目:kiji-rest    文件:KijiRestEntityId.java   
/**
 * Create KijiRestEntityId from a string input, which can be a json string or a raw hbase rowKey.
 * This method is used for entity ids specified from the URL.
 *
 * @param entityId string of the row.
 * @param layout of the table in which the entity id belongs.
 *        If null, then long components may not be recognized.
 * @return a properly constructed KijiRestEntityId.
 * @throws IOException if KijiRestEntityId can not be properly constructed.
 */
public static KijiRestEntityId createFromUrl(
    final String entityId,
    final KijiTableLayout layout) throws IOException {
  if (entityId.startsWith(HBASE_ROW_KEY_PREFIX)
      || entityId.startsWith(HBASE_HEX_ROW_KEY_PREFIX)) {
    return new KijiRestEntityId(entityId);
  } else {
    final JsonParser parser = new JsonFactory().createJsonParser(entityId)
        .enable(Feature.ALLOW_COMMENTS)
        .enable(Feature.ALLOW_SINGLE_QUOTES)
        .enable(Feature.ALLOW_UNQUOTED_FIELD_NAMES);
    final JsonNode node = BASIC_MAPPER.readTree(parser);
    return create(node, layout);
  }
}
项目:kiji-rest    文件:KijiRestEntityId.java   
/**
 * Create a list of KijiRestEntityIds from a string input, which can be a json array of valid
 * entity id strings and/or valid hbase row keys.
 * This method is used for entity ids specified from the URL.
 *
 * @param entityIdListString string of a json array of rows identifiers.
 * @param layout of the table in which the entity id belongs.
 *        If null, then long components may not be recognized.
 * @return a properly constructed list of KijiRestEntityIds.
 * @throws IOException if KijiRestEntityId list can not be properly constructed.
 */
public static List<KijiRestEntityId> createListFromUrl(
    final String entityIdListString,
    final KijiTableLayout layout) throws IOException {
  final JsonParser parser = new JsonFactory().createJsonParser(entityIdListString)
      .enable(Feature.ALLOW_COMMENTS)
      .enable(Feature.ALLOW_SINGLE_QUOTES)
      .enable(Feature.ALLOW_UNQUOTED_FIELD_NAMES);
  final JsonNode jsonNode = BASIC_MAPPER.readTree(parser);

  List<KijiRestEntityId> kijiRestEntityIds = Lists.newArrayList();

  if (jsonNode.isArray()) {
    for (JsonNode node : jsonNode) {
      if (node.isTextual()) {
        kijiRestEntityIds.add(createFromUrl(node.textValue(), layout));
      } else {
        kijiRestEntityIds.add(createFromUrl(node.toString(), layout));
      }
    }
  } else {
    throw new IOException("The entity id list string is not a valid json array.");
  }

  return kijiRestEntityIds;
}
项目:buck    文件:TargetsCommandTest.java   
@Test
public void testJsonOutputForBuildTarget()
    throws IOException, BuildFileParseException, InterruptedException {
  // run `buck targets` on the build file and parse the observed JSON.
  Iterable<TargetNode<?, ?>> nodes = buildTargetNodes(filesystem, "//:test-library");

  targetsCommand.printJsonForTargets(
      params, executor, nodes, ImmutableMap.of(), ImmutableSet.of());
  String observedOutput = console.getTextWrittenToStdOut();
  JsonNode observed = ObjectMappers.READER.readTree(ObjectMappers.createParser(observedOutput));

  // parse the expected JSON.
  String expectedJson = workspace.getFileContents("TargetsCommandTestBuckJson1.js");
  JsonNode expected =
      ObjectMappers.READER.readTree(
          ObjectMappers.createParser(expectedJson).enable(Feature.ALLOW_COMMENTS));

  assertEquals("Output from targets command should match expected JSON.", expected, observed);
  assertEquals("Nothing should be printed to stderr.", "", console.getTextWrittenToStdErr());
}
项目:buck    文件:TargetsCommandTest.java   
@Test
public void testJsonOutputWithDirectDependencies() throws IOException {
  // Run Buck targets command on a case where the deps and direct_dependencies differ
  ProcessResult result = workspace.runBuckCommand("targets", "--json", "//:B");

  // Parse the observed JSON.
  JsonNode observed =
      ObjectMappers.READER.readTree(
          ObjectMappers.createParser(result.getStdout()).enable(Feature.ALLOW_COMMENTS));

  // Parse the expected JSON.
  String expectedJson = workspace.getFileContents("TargetsCommandTestBuckJson2.js");
  JsonNode expected =
      ObjectMappers.READER.readTree(
          ObjectMappers.createParser(expectedJson).enable(Feature.ALLOW_COMMENTS));

  assertThat(
      "Output from targets command should match expected JSON.", observed, is(equalTo(expected)));
  assertThat(
      "Nothing should be printed to stderr.", console.getTextWrittenToStdErr(), is(equalTo("")));
}
项目:GitHub    文件:ParserMinimalBase.java   
/**
 * Method called to report a problem with unquoted control character.
 * Note: starting with version 1.4, it is possible to suppress
 * exception by enabling {@link Feature#ALLOW_UNQUOTED_CONTROL_CHARS}.
 */
protected void _throwUnquotedSpace(int i, String ctxtDesc) throws JsonParseException {
    // JACKSON-208; possible to allow unquoted control chars:
    if (!isEnabled(Feature.ALLOW_UNQUOTED_CONTROL_CHARS) || i > INT_SPACE) {
        char c = (char) i;
        String msg = "Illegal unquoted character ("+_getCharDesc(c)+"): has to be escaped using backslash to be included in "+ctxtDesc;
        _reportError(msg);
    }
}
项目:GitHub    文件:ParserMinimalBase.java   
protected char _handleUnrecognizedCharacterEscape(char ch) throws JsonProcessingException {
    // as per [JACKSON-300]
    if (isEnabled(Feature.ALLOW_BACKSLASH_ESCAPING_ANY_CHARACTER)) {
        return ch;
    }
    // and [JACKSON-548]
    if (ch == '\'' && isEnabled(Feature.ALLOW_SINGLE_QUOTES)) {
        return ch;
    }
    _reportError("Unrecognized character escape "+_getCharDesc(ch));
    return ch;
}
项目:GitHub    文件:AsyncMissingValuesInArrayTest.java   
public AsyncMissingValuesInArrayTest(Collection<JsonParser.Feature> features) {
    this.factory = new JsonFactory();
    this.features = new HashSet<JsonParser.Feature>(features);

    for (JsonParser.Feature feature : features) {
        factory.enable(feature);
    }
}
项目:GitHub    文件:AsyncMissingValuesInArrayTest.java   
@Parameterized.Parameters(name = "Features {0}")
public static Collection<EnumSet<JsonParser.Feature>> getTestCases()
{
    List<EnumSet<JsonParser.Feature>> cases = new ArrayList<EnumSet<JsonParser.Feature>>();
    cases.add(EnumSet.noneOf(JsonParser.Feature.class));
    cases.add(EnumSet.of(Feature.ALLOW_MISSING_VALUES));
    cases.add(EnumSet.of(Feature.ALLOW_TRAILING_COMMA));
    cases.add(EnumSet.of(Feature.ALLOW_MISSING_VALUES, Feature.ALLOW_TRAILING_COMMA));
    return cases;
}
项目:GitHub    文件:AsyncMissingValuesInArrayTest.java   
@Test
public void testArrayTrailingComma() throws Exception {
  String json = "[\"a\", \"b\",]";

  AsyncReaderWrapper p = createParser(factory, json);

  assertEquals(JsonToken.START_ARRAY, p.nextToken());

  assertToken(JsonToken.VALUE_STRING, p.nextToken());
  assertEquals("a", p.currentText());

  assertToken(JsonToken.VALUE_STRING, p.nextToken());
  assertEquals("b", p.currentText());

  // ALLOW_TRAILING_COMMA takes priority over ALLOW_MISSING_VALUES
  if (features.contains(Feature.ALLOW_TRAILING_COMMA)) {
    assertToken(JsonToken.END_ARRAY, p.nextToken());
    assertEnd(p);
  } else if (features.contains(Feature.ALLOW_MISSING_VALUES)) {
    assertToken(JsonToken.VALUE_NULL, p.nextToken());
    assertToken(JsonToken.END_ARRAY, p.nextToken());
    assertEnd(p);
  } else {
    assertUnexpected(p, ']');
  }
  p.close();
}
项目:GitHub    文件:AsyncMissingValuesInArrayTest.java   
@Test
public void testArrayTrailingCommas() throws Exception {
  String json = "[\"a\", \"b\",,]";

  AsyncReaderWrapper p = createParser(factory, json);

  assertEquals(JsonToken.START_ARRAY, p.nextToken());

  assertToken(JsonToken.VALUE_STRING, p.nextToken());
  assertEquals("a", p.currentText());

  assertToken(JsonToken.VALUE_STRING, p.nextToken());
  assertEquals("b", p.currentText());

  // ALLOW_TRAILING_COMMA takes priority over ALLOW_MISSING_VALUES
  if (features.contains(Feature.ALLOW_MISSING_VALUES) &&
      features.contains(Feature.ALLOW_TRAILING_COMMA)) {
    assertToken(JsonToken.VALUE_NULL, p.nextToken());
    assertToken(JsonToken.END_ARRAY, p.nextToken());
    assertEnd(p);
  } else if (features.contains(Feature.ALLOW_MISSING_VALUES)) {
    assertToken(JsonToken.VALUE_NULL, p.nextToken());
    assertToken(JsonToken.VALUE_NULL, p.nextToken());
    assertToken(JsonToken.END_ARRAY, p.nextToken());
    assertEnd(p);
  } else {
    assertUnexpected(p, ',');
  }
  p.close();
}
项目:GitHub    文件:AsyncMissingValuesInArrayTest.java   
@Test
public void testArrayTrailingCommasTriple() throws Exception {
  String json = "[\"a\", \"b\",,,]";

  AsyncReaderWrapper p = createParser(factory, json);

  assertEquals(JsonToken.START_ARRAY, p.nextToken());

  assertToken(JsonToken.VALUE_STRING, p.nextToken());
  assertEquals("a", p.currentText());

  assertToken(JsonToken.VALUE_STRING, p.nextToken());
  assertEquals("b", p.currentText());

  // ALLOW_TRAILING_COMMA takes priority over ALLOW_MISSING_VALUES
  if (features.contains(Feature.ALLOW_MISSING_VALUES) &&
      features.contains(Feature.ALLOW_TRAILING_COMMA)) {
    assertToken(JsonToken.VALUE_NULL, p.nextToken());
    assertToken(JsonToken.VALUE_NULL, p.nextToken());
    assertToken(JsonToken.END_ARRAY, p.nextToken());
    assertEnd(p);
  } else if (features.contains(Feature.ALLOW_MISSING_VALUES)) {
    assertToken(JsonToken.VALUE_NULL, p.nextToken());
    assertToken(JsonToken.VALUE_NULL, p.nextToken());
    assertToken(JsonToken.VALUE_NULL, p.nextToken());
    assertToken(JsonToken.END_ARRAY, p.nextToken());
    assertEnd(p);
  } else {
    assertUnexpected(p, ',');
  }
  p.close();
}
项目:GitHub    文件:AsyncMissingValuesInObjectTest.java   
public AsyncMissingValuesInObjectTest(Collection<JsonParser.Feature> features) {
    this.factory = new JsonFactory();
    this.features = new HashSet<JsonParser.Feature>(features);

    for (JsonParser.Feature feature : features) {
        factory.enable(feature);
    }
}
项目:GitHub    文件:AsyncMissingValuesInObjectTest.java   
@Parameterized.Parameters(name = "Features {0}")
public static Collection<EnumSet<JsonParser.Feature>> getTestCases()
{
    List<EnumSet<JsonParser.Feature>> cases = new ArrayList<EnumSet<JsonParser.Feature>>();
    cases.add(EnumSet.noneOf(JsonParser.Feature.class));
    cases.add(EnumSet.of(Feature.ALLOW_MISSING_VALUES));
    cases.add(EnumSet.of(Feature.ALLOW_TRAILING_COMMA));
    cases.add(EnumSet.of(Feature.ALLOW_MISSING_VALUES, Feature.ALLOW_TRAILING_COMMA));
    return cases;
}
项目:GitHub    文件:TrailingCommasTest.java   
public TrailingCommasTest(int mode, List<Feature> features) {
  this.factory = new JsonFactory();
  this.features = new HashSet<JsonParser.Feature>(features);

  for (JsonParser.Feature feature : features) {
    factory.enable(feature);
  }

  this.mode = mode;
}
项目:GitHub    文件:TrailingCommasTest.java   
@Parameterized.Parameters(name = "Mode {0}, Features {1}")
public static Collection<Object[]> getTestCases() {
  ArrayList<Object[]> cases = new ArrayList<Object[]>();

  for (int mode : ALL_MODES) {
    cases.add(new Object[]{mode, Collections.emptyList()});
    cases.add(new Object[]{mode, Arrays.asList(Feature.ALLOW_MISSING_VALUES)});
    cases.add(new Object[]{mode, Arrays.asList(Feature.ALLOW_TRAILING_COMMA)});
    cases.add(new Object[]{mode, Arrays.asList(Feature.ALLOW_MISSING_VALUES, Feature.ALLOW_TRAILING_COMMA)});
  }

  return cases;
}
项目:GitHub    文件:TrailingCommasTest.java   
@Test
public void testArrayTrailingComma() throws Exception {
  String json = "[\"a\", \"b\",]";

  JsonParser p = createParser(factory, mode, json);

  assertEquals(JsonToken.START_ARRAY, p.nextToken());

  assertToken(JsonToken.VALUE_STRING, p.nextToken());
  assertEquals("a", p.getText());

  assertToken(JsonToken.VALUE_STRING, p.nextToken());
  assertEquals("b", p.getText());

  // ALLOW_TRAILING_COMMA takes priority over ALLOW_MISSING_VALUES
  if (features.contains(Feature.ALLOW_TRAILING_COMMA)) {
    assertToken(JsonToken.END_ARRAY, p.nextToken());
    assertEnd(p);
  } else if (features.contains(Feature.ALLOW_MISSING_VALUES)) {
    assertToken(JsonToken.VALUE_NULL, p.nextToken());
    assertToken(JsonToken.END_ARRAY, p.nextToken());
    assertEnd(p);
  } else {
    assertUnexpected(p, ']');
  }
  p.close();
}