Java Code Examples for com.fasterxml.jackson.core.JsonParser#isExpectedStartArrayToken()

The following examples show how to use com.fasterxml.jackson.core.JsonParser#isExpectedStartArrayToken() . 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: StdCallbackContext.java    From cloudformation-cli-java-plugin with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
private Object readCollection(Class<?> type, JsonParser p, DeserializationContext ctxt) throws IOException {
    if (!p.isExpectedStartArrayToken()) {
        throw new JsonParseException(p, "Expected array for encoded object got " + p.currentToken());
    }
    try {
        Collection<Object> value = (Collection<Object>) type.getDeclaredConstructor().newInstance();
        p.nextToken(); // move to next token
        do {
            Object val = readObject(p, ctxt);
            value.add(val);
        } while (p.nextToken() != JsonToken.END_ARRAY);
        return value;
    } catch (IllegalAccessException | InstantiationException | NoSuchMethodException | InvocationTargetException e) {
        throw new IOException("Can not create empty constructor collection class " + type + " @ "
            + p.getCurrentLocation(), e);
    }
}
 
Example 2
Source File: AvroGenericRecordMapper.java    From divolte-collector with Apache License 2.0 6 votes vote down vote up
private List<?> readArray(final JsonParser parser,
                          final Schema targetSchema) throws IOException {
    Preconditions.checkArgument(targetSchema.getType() == Schema.Type.ARRAY);
    final List<?> result;
    final Schema elementType = targetSchema.getElementType();
    if (parser.isExpectedStartArrayToken()) {
        final List<Object> builder = new ArrayList<>();
        while (JsonToken.END_ARRAY != parser.nextToken()) {
            builder.add(read(parser, elementType));
        }
        result = builder;
    } else if (reader.isEnabled(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY)) {
        result = Collections.singletonList(read(parser, elementType));
    } else {
        throw mappingException(parser, targetSchema);
    }
    return result;
}
 
Example 3
Source File: StdCallbackContext.java    From cloudformation-cli-java-plugin with Apache License 2.0 5 votes vote down vote up
private Object readEncoded(JsonParser p, DeserializationContext ctxt) throws IOException {
    if (!p.isExpectedStartArrayToken()) {
        throw new JsonParseException(p, "Expected array for encoded object got " + p.currentToken());
    }

    Object value = null;
    JsonToken next = p.nextToken();
    if (next != JsonToken.VALUE_STRING) {
        throw new JsonParseException(p, "Encoded Class value not present " + next);
    }
    String typeName = p.getText();
    p.nextToken(); // fwd to next
    ClassLoader loader = Thread.currentThread().getContextClassLoader();
    if (loader == null) {
        loader = getClass().getClassLoader();
    }
    try {
        Class<?> type = loader.loadClass(typeName);
        if (Collection.class.isAssignableFrom(type)) {
            value = readCollection(type, p, ctxt);
        } else if (Map.class.isAssignableFrom(type)) {
            value = readMap(type, p, ctxt);
        } else {
            JsonDeserializer<Object> deser = ctxt.findRootValueDeserializer(ctxt.constructType(type));
            value = deser.deserialize(p, ctxt);
        }
    } catch (ClassNotFoundException e) {
        throw new JsonParseException(p, "Type name encoded " + typeName + " could not be loaded", e);
    }
    if (p.nextToken() != JsonToken.END_ARRAY) {
        throw new JsonParseException(p, "Encoded expected end of ARRAY marker " + p.currentToken());
    }
    return value;
}
 
Example 4
Source File: IgnorePlurals.java    From algoliasearch-client-java-2 with MIT License 5 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public IgnorePlurals deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {

  if (p.isExpectedStartArrayToken()) {
    List languages = p.readValueAs(List.class);
    return IgnorePlurals.of(languages);
  }

  BooleanDeserializer booleanDeserializer = new BooleanDeserializer(Boolean.TYPE, Boolean.FALSE);
  return IgnorePlurals.of(booleanDeserializer.deserialize(p, ctxt));
}
 
Example 5
Source File: BaseCollectionDeserializer.java    From jackson-datatypes-collections with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public T deserialize(JsonParser p, DeserializationContext ctxt)
        throws IOException {
    // Should usually point to START_ARRAY
    if (p.isExpectedStartArrayToken()) {
        return _deserializeContents(p, ctxt);
    }
    // But may support implicit arrays from single values?
    if (ctxt.isEnabled(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY)) {
        return _deserializeFromSingleValue(p, ctxt);
    }
    return (T) ctxt.handleUnexpectedToken(getValueType(ctxt), p);
}
 
Example 6
Source File: PCollectionsCollectionDeserializer.java    From jackson-datatypes-collections with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public T deserialize(JsonParser p, DeserializationContext ctxt)
        throws IOException
{
    // Should usually point to START_ARRAY
    if (p.isExpectedStartArrayToken()) {
        return _deserializeContents(p, ctxt);
    }
    // But may support implicit arrays from single values?
    if (ctxt.isEnabled(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY)) {
        return _deserializeFromSingleValue(p, ctxt);
    }
    return (T) ctxt.handleUnexpectedToken(getValueType(ctxt), p);
}
 
Example 7
Source File: JSONSchemaPropsOrArraySerDe.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
@Override
public JSONSchemaPropsOrArray deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
  JSONSchemaPropsOrArrayBuilder builder = new JSONSchemaPropsOrArrayBuilder();
  if (jsonParser.isExpectedStartObjectToken()) {
    builder.withSchema(
      jsonParser.readValueAs(JSONSchemaProps.class));
  } else if (jsonParser.isExpectedStartArrayToken()) {
    builder.withJSONSchemas(jsonParser.<List<JSONSchemaProps>>readValueAs(new TypeReference<List<JSONSchemaProps>>() {}));
  }
  return builder.build();
}
 
Example 8
Source File: BaseCollectionDeserializer.java    From jackson-datatypes-collections with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public T deserialize(JsonParser p, DeserializationContext ctxt)
        throws IOException {
    // Should usually point to START_ARRAY
    if (p.isExpectedStartArrayToken()) {
        return _deserializeContents(p, ctxt);
    }
    // But may support implicit arrays from single values?
    if (ctxt.isEnabled(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY)) {
        return _deserializeFromSingleValue(p, ctxt);
    }
    return (T) ctxt.handleUnexpectedToken(getValueType(ctxt), p);
}
 
Example 9
Source File: ArrayBlockingQueueDeserializer.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public Collection<Object> deserialize(JsonParser p, DeserializationContext ctxt,
        Collection<Object> result0) throws IOException
{
    if (result0 != null) {
        return super.deserialize(p, ctxt, result0);
    }
    // Ok: must point to START_ARRAY (or equivalent)
    if (!p.isExpectedStartArrayToken()) {
        return handleNonArray(p, ctxt, new ArrayBlockingQueue<Object>(1));
    }
    result0 = super.deserialize(p, ctxt, new ArrayList<Object>());
    return new ArrayBlockingQueue<Object>(result0.size(), false, result0);
}
 
Example 10
Source File: UserProfileFieldsDeserializer.java    From slack-client with Apache License 2.0 5 votes vote down vote up
@Override
public Optional<Map<String, ProfileField>> deserialize(JsonParser parser,
                                                       DeserializationContext context) throws IOException {
  ObjectCodec codec = parser.getCodec();
  if (parser.isExpectedStartArrayToken()) {
    parser.skipChildren();
    return Optional.empty();
  }
  Map<String, ProfileField> fieldMap = codec.readValue(parser, new TypeReference<Map<String, ProfileField>>() {});
  return fieldMap.isEmpty() ? Optional.empty() : Optional.of(fieldMap);
}
 
Example 11
Source File: SdkPojoDeserializer.java    From cloudformation-cli-java-plugin with Apache License 2.0 5 votes vote down vote up
private List<Object> readList(SdkField<?> field, JsonParser p, DeserializationContext ctxt) throws IOException {
    if (!p.isExpectedStartArrayToken()) {
        throw new JsonMappingException(p, "Expecting array start token got " + p.currentToken());
    }

    ListTrait trait = field.getTrait(ListTrait.class);
    SdkField<?> valueType = trait.memberFieldInfo();
    List<Object> value = new ArrayList<>();
    while (p.nextToken() != JsonToken.END_ARRAY) {
        value.add(readObject(valueType, p, ctxt));
    }
    return value;
}
 
Example 12
Source File: Sequence.java    From dremio-oss with Apache License 2.0 4 votes vote down vote up
@Override
public LogicalOperator deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException,
    JsonProcessingException {
  ObjectIdGenerator<Integer> idGenerator = new ObjectIdGenerators.IntSequenceGenerator();
  JsonLocation start = jp.getCurrentLocation();
  JsonToken t = jp.getCurrentToken();
  LogicalOperator parent = null;
  LogicalOperator first = null;
  LogicalOperator prev = null;
  Integer id = null;

  while (true) {
    String fieldName = jp.getText();
    t = jp.nextToken();
    switch (fieldName) { // switch on field names.
    case "@id":
      id = _parseIntPrimitive(jp, ctxt);
      break;
    case "input":
      JavaType tp = ctxt.constructType(LogicalOperator.class);
      JsonDeserializer<Object> d = ctxt.findRootValueDeserializer(tp);
      parent = (LogicalOperator) d.deserialize(jp, ctxt);
      break;

    case "do":
      if (!jp.isExpectedStartArrayToken()) {
        throwE(
            jp,
            "The do parameter of sequence should be an array of SimpleOperators.  Expected a JsonToken.START_ARRAY token but received a "
                + t.name() + "token.");
      }

      int pos = 0;
      while ((t = jp.nextToken()) != JsonToken.END_ARRAY) {
        // logger.debug("Reading sequence child {}.", pos);
        JsonLocation l = jp.getCurrentLocation(); // get current location
                                                  // first so we can
                                                  // correctly reference the
                                                  // start of the object in
                                                  // the case that the type
                                                  // is wrong.
        LogicalOperator o = jp.readValueAs(LogicalOperator.class);

        if (pos == 0) {
          if (!(o instanceof SingleInputOperator) && !(o instanceof SourceOperator)) {
            throwE(
                l,
                "The first operator in a sequence must be either a ZeroInput or SingleInput operator.  The provided first operator was not. It was of type "
                    + o.getClass().getName());
          }
          first = o;
        } else {
          if (!(o instanceof SingleInputOperator)) {
            throwE(l, "All operators after the first must be single input operators.  The operator at position "
                + pos + " was not. It was of type " + o.getClass().getName());
          }
          SingleInputOperator now = (SingleInputOperator) o;
          now.setInput(prev);
        }
        prev = o;

        pos++;
      }
      break;
    default:
      throwE(jp, "Unknown field name provided for Sequence: " + jp.getText());
    }

    t = jp.nextToken();
    if (t == JsonToken.END_OBJECT) {
      break;
    }
  }

  if (first == null) {
    throwE(start, "A sequence must include at least one operator.");
  }
  if ((parent == null && first instanceof SingleInputOperator)
      || (parent != null && first instanceof SourceOperator)) {
    throwE(start,
        "A sequence must either start with a ZeroInputOperator or have a provided input. It cannot have both or neither.");
  }

  if (parent != null && first instanceof SingleInputOperator) {
    ((SingleInputOperator) first).setInput(parent);
  }

  // set input reference.
  if (id != null) {

    ReadableObjectId rid = ctxt.findObjectId(id, idGenerator, null);
    rid.bindItem(prev);
    // logger.debug("Binding id {} to item {}.", rid.id, rid.item);

  }

  return first;
}
 
Example 13
Source File: CustomCollectionDeserializer.java    From caravan with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public Object deserialize(JsonParser p, DeserializationContext ctxt,
    Object result)
    throws IOException {
  // Ok: must point to START_ARRAY (or equivalent)
  if (!p.isExpectedStartArrayToken()) {
    return handleNonArray(p, ctxt, (Collection<Object>) result);
  }
  // [databind#631]: Assign current value, to be accessible by custom serializers
  p.setCurrentValue(result);

  JsonDeserializer<Object> valueDes = _valueDeserializer;
  final TypeDeserializer typeDeser = _valueTypeDeserializer;
  CollectionReferringAccumulator referringAccumulator =
      (valueDes.getObjectIdReader() == null) ? null :
          new CollectionReferringAccumulator(_containerType.getContentType().getRawClass(), (Collection<Object>) result);

  JsonToken t;
  while ((t = p.nextToken()) != JsonToken.END_ARRAY) {
    try {
      Object value;
      if (t == JsonToken.VALUE_NULL) {
        if (_skipNullValues) {
          continue;
        }
        value = _nullProvider.getNullValue(ctxt);
      } else if (typeDeser == null) {
        value = valueDes.deserialize(p, ctxt);
      } else {
        value = valueDes.deserializeWithType(p, ctxt, typeDeser);
      }
      if (referringAccumulator != null) {
        referringAccumulator.add(value);
      } else {
        ((Collection<Object>) result).add(value);
      }
    } catch (UnresolvedForwardReference reference) {
      if (referringAccumulator == null) {
        throw JsonMappingException
            .from(p, "Unresolved forward reference but no identity info", reference);
      }
      Referring ref = referringAccumulator.handleUnresolvedReference(reference);
      reference.getRoid().appendReferring(ref);
    } catch (Exception e) {
      boolean wrap = (ctxt == null) || ctxt.isEnabled(DeserializationFeature.WRAP_EXCEPTIONS);
      if (!wrap) {
        ClassUtil.throwIfRTE(e);
      }
      throw JsonMappingException.wrapWithPath(e, result, ((Collection<Object>) result).size());
    }
  }
  return result;
}
 
Example 14
Source File: BeanAsArrayDeserializer.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
@Override
public Object deserialize(JsonParser p, DeserializationContext ctxt, Object bean)
    throws IOException
{
    // [databind#631]: Assign current value, to be accessible by custom serializers
    p.setCurrentValue(bean);

    if (!p.isExpectedStartArrayToken()) {
        return _deserializeFromNonArray(p, ctxt);
    }
    
    /* No good way to verify that we have an array... although could I guess
     * check via JsonParser. So let's assume everything is working fine, for now.
     */
    if (_injectables != null) {
        injectValues(ctxt, bean);
    }
    final SettableBeanProperty[] props = _orderedProperties;
    int i = 0;
    final int propCount = props.length;
    while (true) {
        if (p.nextToken() == JsonToken.END_ARRAY) {
            return bean;
        }
        if (i == propCount) {
            break;
        }
        SettableBeanProperty prop = props[i];
        if (prop != null) { // normal case
            try {
                prop.deserializeAndSet(p, ctxt, bean);
            } catch (Exception e) {
                wrapAndThrow(e, bean, prop.getName(), ctxt);
            }
        } else { // just skip?
            p.skipChildren();
        }
        ++i;
    }
    
    // Ok; extra fields? Let's fail, unless ignoring extra props is fine
    if (!_ignoreAllUnknown && ctxt.isEnabled(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)) {
        ctxt.reportWrongTokenException(this, JsonToken.END_ARRAY,
                "Unexpected JSON values; expected at most %d properties (in JSON Array)",
                propCount);
        // never gets here
    }
    // otherwise, skip until end
    do {
        p.skipChildren();
    } while (p.nextToken() != JsonToken.END_ARRAY);
    return bean;
}
 
Example 15
Source File: BeanAsArrayDeserializer.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
@Override
public Object deserialize(JsonParser p, DeserializationContext ctxt)
    throws IOException
{
    // Let's delegate just in case we got a JSON Object (could error out, alternatively?)
    if (!p.isExpectedStartArrayToken()) {
        return _deserializeFromNonArray(p, ctxt);
    }
    if (!_vanillaProcessing) {
        return _deserializeNonVanilla(p, ctxt);
    }
    final Object bean = _valueInstantiator.createUsingDefault(ctxt);
    // [databind#631]: Assign current value, to be accessible by custom serializers
    p.setCurrentValue(bean);

    final SettableBeanProperty[] props = _orderedProperties;
    int i = 0;
    final int propCount = props.length;
    while (true) {
        if (p.nextToken() == JsonToken.END_ARRAY) {
            return bean;
        }
        if (i == propCount) {
            break;
        }
        SettableBeanProperty prop = props[i];
        if (prop != null) { // normal case
            try {
                prop.deserializeAndSet(p, ctxt, bean);
            } catch (Exception e) {
                wrapAndThrow(e, bean, prop.getName(), ctxt);
            }
        } else { // just skip?
            p.skipChildren();
        }
        ++i;
    }
    // Ok; extra fields? Let's fail, unless ignoring extra props is fine
    if (!_ignoreAllUnknown && ctxt.isEnabled(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)) {
        ctxt.reportWrongTokenException(this, JsonToken.END_ARRAY,
                "Unexpected JSON values; expected at most %d properties (in JSON Array)",
                propCount);
        // never gets here
    }
    // otherwise, skip until end
    do {
        p.skipChildren();
    } while (p.nextToken() != JsonToken.END_ARRAY);
    return bean;
}
 
Example 16
Source File: BaseCollectionDeserializer.java    From jackson-datatypes-collections with Apache License 2.0 4 votes vote down vote up
@Override
public T deserialize(JsonParser p, DeserializationContext ctxt)
        throws IOException {
    Intermediate intermediate = createIntermediate();

    if (p.isExpectedStartArrayToken()) {
        JsonToken t;
        while ((t = p.nextToken()) != JsonToken.END_ARRAY) {
            String str;
            if (t == JsonToken.VALUE_STRING) {
                str = p.getText();
            } else {
                CharSequence cs = (CharSequence) ctxt.handleUnexpectedToken(getValueType(ctxt), p);
                str = cs.toString();
            }
            if (str.length() != 1) {
                ctxt.reportInputMismatch(this,
                                         "Cannot convert a JSON String of length %d into a char element of " +
                                         "char array",
                                         str.length());
            }
            intermediate.add(str.charAt(0));
        }
        return finish(intermediate);
    }

    char[] chars = p.getTextCharacters();
    if (p.getTextOffset() == 0 && p.getTextLength() == chars.length) {
        intermediate.addAll(chars);
    } else {
        int i = 0;
        // first, copy in batches of BATCH_COPY_SIZE
        if ((p.getTextLength() - i) >= BATCH_COPY_SIZE) {
            char[] buf = new char[BATCH_COPY_SIZE];
            do {
                System.arraycopy(chars, p.getTextOffset() + i, buf, 0, BATCH_COPY_SIZE);
                intermediate.addAll(buf);
                i += BATCH_COPY_SIZE;
            } while ((p.getTextLength() - i) >= BATCH_COPY_SIZE);
        }
        // and finally, copy the remainder.
        if (p.getTextLength() > i) {
            char[] tail = Arrays.copyOfRange(
                    chars, p.getTextOffset() + i, p.getTextOffset() + p.getTextLength());
            intermediate.addAll(tail);
        }
    }
    return finish(intermediate);
}
 
Example 17
Source File: YearMonthDeserializer.java    From jackson-modules-java8 with Apache License 2.0 4 votes vote down vote up
@Override
public YearMonth deserialize(JsonParser parser, DeserializationContext context) throws IOException
{
    if (parser.hasToken(JsonToken.VALUE_STRING)) {
        String string = parser.getText().trim();
        if (string.length() == 0) {
            if (!isLenient()) {
                return _failForNotLenient(parser, context, JsonToken.VALUE_STRING);
            }
            return null;
        }
        try {
            return YearMonth.parse(string, _formatter);
        } catch (DateTimeException e) {
            return _handleDateTimeFormatException(context, e, _formatter, string);
        }
    }
    if (parser.isExpectedStartArrayToken()) {
        JsonToken t = parser.nextToken();
        if (t == JsonToken.END_ARRAY) {
            return null;
        }
        if ((t == JsonToken.VALUE_STRING || t == JsonToken.VALUE_EMBEDDED_OBJECT)
                && context.isEnabled(DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS)) {
            final YearMonth parsed = deserialize(parser, context);
            if (parser.nextToken() != JsonToken.END_ARRAY) {
                handleMissingEndArrayForSingle(parser, context);
            }
            return parsed;            
        }
        if (t != JsonToken.VALUE_NUMBER_INT) {
            _reportWrongToken(context, JsonToken.VALUE_NUMBER_INT, "years");
        }
        int year = parser.getIntValue();
        int month = parser.nextIntValue(-1);
        if (month == -1) {
            if (!parser.hasToken(JsonToken.VALUE_NUMBER_INT)) {
                _reportWrongToken(context, JsonToken.VALUE_NUMBER_INT, "months");
            }
            month = parser.getIntValue();
        }
        if (parser.nextToken() != JsonToken.END_ARRAY) {
            throw context.wrongTokenException(parser, handledType(), JsonToken.END_ARRAY,
                    "Expected array to end");
        }
        return YearMonth.of(year, month);
    }
    if (parser.hasToken(JsonToken.VALUE_EMBEDDED_OBJECT)) {
        return (YearMonth) parser.getEmbeddedObject();
    }
    return _handleUnexpectedToken(context, parser,
            JsonToken.VALUE_STRING, JsonToken.START_ARRAY);
}
 
Example 18
Source File: MonthDayDeserializer.java    From jackson-modules-java8 with Apache License 2.0 4 votes vote down vote up
@Override
public MonthDay deserialize(JsonParser parser, DeserializationContext context) throws IOException
{
    if (parser.hasToken(JsonToken.VALUE_STRING)) {
        String string = parser.getValueAsString().trim();
        try {
            if (_formatter == null) {
                return MonthDay.parse(string);
            }
            return MonthDay.parse(string, _formatter);
        } catch (DateTimeException e) {
            return _handleDateTimeFormatException(context, e, _formatter, string);
        }
    }
    if (parser.isExpectedStartArrayToken()) {
        JsonToken t = parser.nextToken();
        if (t == JsonToken.END_ARRAY) {
            return null;
        }
        if ((t == JsonToken.VALUE_STRING || t == JsonToken.VALUE_EMBEDDED_OBJECT)
                && context.isEnabled(DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS)) {
            final MonthDay parsed = deserialize(parser, context);
            if (parser.nextToken() != JsonToken.END_ARRAY) {
                handleMissingEndArrayForSingle(parser, context);
            }
            return parsed;
        }
        if (t != JsonToken.VALUE_NUMBER_INT) {
            _reportWrongToken(context, JsonToken.VALUE_NUMBER_INT, "month");
        }
        int month = parser.getIntValue();
        int day = parser.nextIntValue(-1);
        if (day == -1) {
            if (!parser.hasToken(JsonToken.VALUE_NUMBER_INT)) {
                _reportWrongToken(context, JsonToken.VALUE_NUMBER_INT, "day");
            }
            day = parser.getIntValue();
        }
        if (parser.nextToken() != JsonToken.END_ARRAY) {
            throw context.wrongTokenException(parser, handledType(), JsonToken.END_ARRAY,
                    "Expected array to end");
        }
        return MonthDay.of(month, day);
    }
    if (parser.hasToken(JsonToken.VALUE_EMBEDDED_OBJECT)) {
        return (MonthDay) parser.getEmbeddedObject();
    }
    return _handleUnexpectedToken(context, parser,
            JsonToken.VALUE_STRING, JsonToken.START_ARRAY);
}
 
Example 19
Source File: IterableXDeserializer.java    From cyclops with Apache License 2.0 4 votes vote down vote up
@Override
public IterableX<?> deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {


    if (!p.isExpectedStartArrayToken()) {
        return (IterableX)ctxt.handleUnexpectedToken(handledType(),p);
    }

  List multi = new ArrayList();

    JsonToken t;
    while ((t = p.nextToken()) != JsonToken.END_ARRAY) {
        Object value;

        if (t == JsonToken.VALUE_NULL) {
            value = null;
        } else if (typeDeserializerForValue == null) {
            value = valueDeserializer.deserialize(p, ctxt);
        } else {
            value = valueDeserializer.deserializeWithType(p, ctxt, typeDeserializerForValue);
        }
        multi.add(value);
    }

  if(Vector.class.isAssignableFrom(elementType))
    return Vector.fromIterable(multi);

  if(Seq.class.isAssignableFrom(elementType))
    return Seq.fromIterable(multi);
  if(LazySeq.class.isAssignableFrom(elementType))
    return LazySeq.fromIterable(multi);
  if(LazyString.class.isAssignableFrom(elementType))
    return LazyString.fromLazySeq((LazySeq)LazySeq.fromIterable(multi));
  if(IntMap.class.isAssignableFrom(elementType))
    return IntMap.fromIterable(multi);
  if(ReactiveSeq.class.isAssignableFrom(elementType))
    return ReactiveSeq.fromIterable(multi);
  if(Streamable.class.isAssignableFrom(elementType))
    return Streamable.fromIterable(multi);
  if(BankersQueue.class.isAssignableFrom(elementType))
    return BankersQueue.fromIterable(multi);
  if(Bag.class.isAssignableFrom(elementType))
    return Bag.fromIterable(multi);
  if(cyclops.data.HashSet.class.isAssignableFrom(elementType))
    return HashSet.fromIterable(multi);
  if(cyclops.data.TrieSet.class.isAssignableFrom(elementType))
    return TrieSet.fromIterable(multi);
  if(cyclops.data.TreeSet.class.isAssignableFrom(elementType))
    return TreeSet.fromIterable(multi,(Comparator)Comparator.naturalOrder());

  Optional<Method> m = streamMethod.computeIfAbsent(elementType, c->Stream.of(c.getMethods())
                                                                    .filter(method -> "fromIterable".equals(method.getName()))
                                                                    .filter(method -> method.getParameterCount()==1)
                                                                      .findFirst()
                                                                    .map(m2->{ m2.setAccessible(true); return m2;}));
  IterableX x = m.map(mt -> (IterableX) new Invoker().executeMethod(multi, mt, itX)).orElse(null);

  return x;

}
 
Example 20
Source File: FilmlisteLesen.java    From MLib with GNU General Public License v3.0 4 votes vote down vote up
private void readData(JsonParser jp, ListeFilme listeFilme) throws IOException {
    JsonToken jsonToken;
    String sender = "", thema = "";

    if (jp.nextToken() != JsonToken.START_OBJECT) {
        throw new IllegalStateException("Expected data to start with an Object");
    }

    while ((jsonToken = jp.nextToken()) != null) {
        if (jsonToken == JsonToken.END_OBJECT) {
            break;
        }
        if (jp.isExpectedStartArrayToken()) {
            for (int k = 0; k < ListeFilme.MAX_ELEM; ++k) {
                listeFilme.metaDaten[k] = jp.nextTextValue();
            }
            break;
        }
    }
    while ((jsonToken = jp.nextToken()) != null) {
        if (jsonToken == JsonToken.END_OBJECT) {
            break;
        }
        if (jp.isExpectedStartArrayToken()) {
            // sind nur die Feldbeschreibungen, brauch mer nicht
            jp.nextToken();
            break;
        }
    }
    while (!Config.getStop() && (jsonToken = jp.nextToken()) != null) {
        if (jsonToken == JsonToken.END_OBJECT) {
            break;
        }
        if (jp.isExpectedStartArrayToken()) {
            DatenFilm datenFilm = new DatenFilm();
            for (int i = 0; i < DatenFilm.JSON_NAMES.length; ++i) {
                //if we are in FASTAUTO mode, we don´t need film descriptions.
                //this should speed up loading on low end devices...
                if (workMode == WorkMode.FASTAUTO) {
                    if (DatenFilm.JSON_NAMES[i] == DatenFilm.FILM_BESCHREIBUNG
                            || DatenFilm.JSON_NAMES[i] == DatenFilm.FILM_WEBSEITE
                            || DatenFilm.JSON_NAMES[i] == DatenFilm.FILM_GEO) {
                        jp.nextToken();
                        continue;
                    }
                }
                if (DatenFilm.JSON_NAMES[i] == DatenFilm.FILM_NEU) {
                    final String value = jp.nextTextValue();
                    //This value is unused...
                    //datenFilm.arr[DatenFilm.FILM_NEU_NR] = value;
                    datenFilm.setNew(Boolean.parseBoolean(value));
                } else {
                    datenFilm.arr[DatenFilm.JSON_NAMES[i]] = jp.nextTextValue();
                }

                /// für die Entwicklungszeit
                if (datenFilm.arr[DatenFilm.JSON_NAMES[i]] == null) {
                    datenFilm.arr[DatenFilm.JSON_NAMES[i]] = "";
                }
            }
            if (datenFilm.arr[DatenFilm.FILM_SENDER].isEmpty()) {
                datenFilm.arr[DatenFilm.FILM_SENDER] = sender;
            } else {
                sender = datenFilm.arr[DatenFilm.FILM_SENDER];
            }
            if (datenFilm.arr[DatenFilm.FILM_THEMA].isEmpty()) {
                datenFilm.arr[DatenFilm.FILM_THEMA] = thema;
            } else {
                thema = datenFilm.arr[DatenFilm.FILM_THEMA];
            }

            listeFilme.importFilmliste(datenFilm);
            if (milliseconds > 0) {
                // muss "rückwärts" laufen, da das Datum sonst 2x gebaut werden muss
                // wenns drin bleibt, kann mans noch ändern
                if (!checkDate(datenFilm)) {
                    listeFilme.remove(datenFilm);
                }
            }
        }
    }
}