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

The following examples show how to use com.fasterxml.jackson.core.JsonParser#close() . 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: JsonIOUtil.java    From protostuff with Apache License 2.0 6 votes vote down vote up
/**
 * Merges the {@code message} from the {@link InputStream} using the given {@code schema}.
 * <p>
 * The {@link LinkedBuffer}'s internal byte array will be used when reading the message.
 */
public static <T> void mergeFrom(InputStream in, T message, Schema<T> schema,
        boolean numeric, LinkedBuffer buffer) throws IOException
{
    final IOContext context = new IOContext(DEFAULT_JSON_FACTORY._getBufferRecycler(),
            in, false);
    final JsonParser parser = newJsonParser(in, buffer.buffer, 0, 0, false, context);
    try
    {
        mergeFrom(parser, message, schema, numeric);
    }
    finally
    {
        parser.close();
    }
}
 
Example 2
Source File: ReadMapTest.java    From jackson-jr with Apache License 2.0 6 votes vote down vote up
private void _testLargeJson(int size) throws Exception {
    Map<String, Object> map = new HashMap<String, Object>();
    for (int i = 0; i < size; i++) {
        map.put("" + i, new HashMap<String, Object>());
    }
    String json = JSON.std.asString(map);
    Map<?,?> result = JSON.std.mapFrom(json);
    assertNotNull(result);
    assertEquals(size, result.size());

    JsonParser p = parserFor(json);
    result = JSON.std.mapFrom(p);
    assertNotNull(result);
    assertEquals(size, result.size());
    p.close();
}
 
Example 3
Source File: JsonIOUtil.java    From protostuff with Apache License 2.0 6 votes vote down vote up
/**
 * Parses the {@code messages} from the stream using the given {@code schema}.
 */
public static <T> List<T> parseListFrom(InputStream in, Schema<T> schema,
        boolean numeric) throws IOException
{
    final IOContext context = new IOContext(DEFAULT_JSON_FACTORY._getBufferRecycler(),
            in, false);
    final JsonParser parser = newJsonParser(in, context.allocReadIOBuffer(), 0, 0,
            true, context);
    // final JsonParser parser = DEFAULT_JSON_FACTORY.createJsonParser(in);
    try
    {
        return parseListFrom(parser, schema, numeric);
    }
    finally
    {
        parser.close();
    }
}
 
Example 4
Source File: ReadSequencesTest.java    From jackson-jr with Apache License 2.0 6 votes vote down vote up
public void testBeanSequence() throws Exception
{
    final String INPUT = aposToQuotes("{'id':1, 'msg':'foo'} {'id':2, 'msg':'Same'} null   ");

    // First, managed
    ValueIterator<Bean> it = JSON.std.beanSequenceFrom(Bean.class, INPUT);
    _verifyBeanSequence(it);
    it.close();

    // and parser we create
    JsonParser p = JSON.std.createParser(new StringReader(INPUT));

    it = JSON.std.beanSequenceFrom(Bean.class, p);
    _verifyBeanSequence(it);
    it.close();
    p.close();
}
 
Example 5
Source File: JsonIOUtils.java    From dremio-oss with Apache License 2.0 6 votes vote down vote up
/**
 * Merges the {@code message} with the byte array using the given {@code schema}.
 */
public static <T> void mergeFrom(byte[] data, int offset, int length, T message,
                                 Schema<T> schema, boolean numeric) throws IOException {
  final IOContext context = new IOContext(DEFAULT_JSON_FACTORY._getBufferRecycler(),
    data, false);
  final JsonParser parser = newJsonParser(null, data, offset, offset + length, false,
    context);
  /*
   * final JsonParser parser = DEFAULT_JSON_FACTORY.createJsonParser(data, offset, length);
   */
  try {
    mergeFrom(parser, message, schema, numeric);
  } finally {
    parser.close();
  }
}
 
Example 6
Source File: ReadSequencesTest.java    From jackson-jr with Apache License 2.0 5 votes vote down vote up
public void testAnySequence() throws Exception
{
    final String INPUT = aposToQuotes("'hello world!' 127 true [ 1, 2, 3]\nnull { 'msg':'none'}   ");

    // First, managed
    ValueIterator<Object> it = JSON.std.anySequenceFrom(INPUT);
    assertNotNull(it.getParser());
    assertNotNull(it.getCurrentLocation());

    _verifyAnySequence(it);
    it.close();
    assertFalse(it.hasNext());
    assertFalse(it.hasNextValue());

    // and then parser we create
    JsonParser p = JSON.std.createParser(new ByteArrayInputStream(INPUT.getBytes("UTF-8")));

    it = JSON.std.anySequenceFrom(p);
    _verifyAnySequence(it);
    it.close();
    p.close();

    // Plus should not hurt to try close()ing more (no effect either)
    it.close();
    it.close();

    // and finally, test early close() top
    it = JSON.std.anySequenceFrom(INPUT);
    assertNotNull(it.next());
    it.close();
}
 
Example 7
Source File: HostResource.java    From floodlight_with_topoguard with Apache License 2.0 5 votes vote down vote up
protected void jsonToHostDefinition(String json, HostDefinition host) throws IOException {
    MappingJsonFactory f = new MappingJsonFactory();
    JsonParser jp;
    
    try {
        jp = f.createJsonParser(json);
    } catch (JsonParseException e) {
        throw new IOException(e);
    }
    
    jp.nextToken();
    if (jp.getCurrentToken() != JsonToken.START_OBJECT) {
        throw new IOException("Expected START_OBJECT");
    }
    
    while (jp.nextToken() != JsonToken.END_OBJECT) {
        if (jp.getCurrentToken() != JsonToken.FIELD_NAME) {
            throw new IOException("Expected FIELD_NAME");
        }
        
        String n = jp.getCurrentName();
        jp.nextToken();
        if (jp.getText().equals("")) 
            continue;
        else if (n.equals("attachment")) {
            while (jp.nextToken() != JsonToken.END_OBJECT) {
                String field = jp.getCurrentName();
                if (field.equals("id")) {
                    host.attachment = jp.getText();
                } else if (field.equals("mac")) {
                    host.mac = jp.getText();
                }
            }
        }
    }
    
    jp.close();
}
 
Example 8
Source File: JsonWeatherParser.java    From openhab1-addons with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void parseInto(String r, Weather weather) throws Exception {
    JsonFactory jsonFactory = new JsonFactory();
    JsonParser jp = jsonFactory.createParser(r);

    jp.nextValue();
    handleToken(jp, null, weather);
    jp.close();

    super.parseInto(r, weather);
}
 
Example 9
Source File: JSONConnectionHandlerManager.java    From Kore with Apache License 2.0 5 votes vote down vote up
private void processJSONInput(String input) {
    try {
        synchronized (clientResponses) {
            LogUtils.LOGD(TAG, "processJSONInput: " + input);
            JsonParser parser = objectMapper.getFactory().createParser(input);
            ObjectNode jsonRequest = objectMapper.readTree(parser);

            int methodId = jsonRequest.get(ID_NODE).asInt();
            String method = jsonRequest.get(METHOD_NODE).asText();

            methodIdsHandled.put(String.valueOf(methodId), new MethodPendingState(method));

            if (clientResponses.get(String.valueOf(methodId)) != null)
                return;

            ConnectionHandler connectionHandler = handlersByType.get(method);
            if (connectionHandler != null) {
                ArrayList<JsonResponse> responses = connectionHandler.getResponse(method, jsonRequest);
                if (responses != null) {
                    clientResponses.put(String.valueOf(methodId), responses);
                }
            }

            parser.close();
        }
    } catch (IOException e) {
        LogUtils.LOGD(TAG, "processJSONInput: error parsing: " + input);
        LogUtils.LOGE(TAG, e.getMessage());
    }
}
 
Example 10
Source File: ReadListTest.java    From jackson-jr with Apache License 2.0 5 votes vote down vote up
public void testSimpleList() throws Exception
{
    final String INPUT = "[1,2,3]";

    _verifySimpleList(JSON.std.anyFrom(INPUT), INPUT);
    // but same should be possible with explicit call as well
    _verifySimpleList(JSON.std.listFrom(INPUT), INPUT);

    JsonParser p = parserFor(INPUT);
    _verifySimpleList(JSON.std.listFrom(p), INPUT);
    assertFalse(p.hasCurrentToken());
    p.close();
}
 
Example 11
Source File: ImportUtils.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public static void importFederatedUsersFromStream(KeycloakSession session, String realmName, ObjectMapper mapper, InputStream is) throws IOException {
    RealmProvider model = session.realms();
    JsonFactory factory = mapper.getJsonFactory();
    JsonParser parser = factory.createJsonParser(is);
    try {
        parser.nextToken();

        while (parser.nextToken() == JsonToken.FIELD_NAME) {
            if ("realm".equals(parser.getText())) {
                parser.nextToken();
                String currRealmName = parser.getText();
                if (!currRealmName.equals(realmName)) {
                    throw new IllegalStateException("Trying to import users into invalid realm. Realm name: " + realmName + ", Expected realm name: " + currRealmName);
                }
            } else if ("federatedUsers".equals(parser.getText())) {
                parser.nextToken();

                if (parser.getCurrentToken() == JsonToken.START_ARRAY) {
                    parser.nextToken();
                }

                // TODO: support for more transactions per single users file (if needed)
                List<UserRepresentation> userReps = new ArrayList<UserRepresentation>();
                while (parser.getCurrentToken() == JsonToken.START_OBJECT) {
                    UserRepresentation user = parser.readValueAs(UserRepresentation.class);
                    userReps.add(user);
                    parser.nextToken();
                }

                importFederatedUsers(session, model, realmName, userReps);

                if (parser.getCurrentToken() == JsonToken.END_ARRAY) {
                    parser.nextToken();
                }
            }
        }
    } finally {
        parser.close();
    }
}
 
Example 12
Source File: ReadSimpleTest.java    From jackson-jr with Apache License 2.0 5 votes vote down vote up
private void _testArray(String input, int expCount) throws Exception
{
    Object ob;

    // first: can explicitly request an array:
    ob = JSON.std.arrayFrom(input);
    assertTrue(ob instanceof Object[]);
    assertEquals(expCount, ((Object[]) ob).length);
    assertEquals(input, JSON.std.asString(ob));

    // via parser, too
    JsonParser p = parserFor(input);
    ob = JSON.std.arrayFrom(p);
    assertTrue(ob instanceof Object[]);
    assertEquals(expCount, ((Object[]) ob).length);
    assertEquals(input, JSON.std.asString(ob));
    p.close();

    // or, with "List of Any"
    ob = JSON.std
            .arrayOfFrom(Object.class, input);
    assertTrue(ob instanceof Object[]);
    assertEquals(expCount, ((Object[]) ob).length);
    assertEquals(input, JSON.std.asString(ob));

    ob = JSON.std
          .with(JSON.Feature.READ_JSON_ARRAYS_AS_JAVA_ARRAYS)
          .arrayOfFrom(Object.class, input);
    assertTrue(ob instanceof Object[]);
    assertEquals(expCount, ((Object[]) ob).length);
    assertEquals(input, JSON.std.asString(ob));
    
    // or by changing default mapping:
    ob = JSON.std.with(Feature.READ_JSON_ARRAYS_AS_JAVA_ARRAYS).anyFrom(input);
    assertTrue(ob instanceof Object[]);
    assertEquals(expCount, ((Object[]) ob).length);
    assertEquals(input, JSON.std.asString(ob));
}
 
Example 13
Source File: JsonCredentials.java    From ibm-cos-sdk-java with Apache License 2.0 5 votes vote down vote up
/**
 * Reads the specified input stream as a stream of json object content and
 * extracts the IBM api key and resource instance id from the object.
 *
 * @param inputStream
 *            The input stream containing the IBM credential properties.
 *
 * @throws IOException
 *             If any problems occur while reading from the input stream.
 */
public JsonCredentials(InputStream stream) throws IOException {
	
	try {
		JsonParser parser = jsonFactory.createParser(stream);
           parse(parser);
           parser.close();
       } finally {
           try {stream.close();} catch (Exception e) {}
       }

	if(!isNullOrEmpty(apiKey) && !isNullOrEmpty(serviceInstanceId))
		iamEnabled = true;
	if(!isNullOrEmpty(accessKey) && !isNullOrEmpty(secretAccessKey))
		hmacEnabled = true;
	
	if (!iamEnabled && !hmacEnabled) {
		throw new IllegalArgumentException(
				"The specified json doesn't contain the expected properties 'apikey', 'resource_instance_id', 'access_key_id' and 'secret_access_key'.");
	}
	
	// HMAC takes precedence over IAM
	if(hmacEnabled) {
		this.apiKey = null;
		this.serviceInstanceId = null;
		this.iamEnabled = false;
	} else {
		this.accessKey = null;
		this.secretAccessKey = null;
		this.iamEnabled = true;
	}

}
 
Example 14
Source File: Tinode.java    From tindroid with Apache License 2.0 4 votes vote down vote up
/**
 * Parse JSON received from the server into {@link ServerMessage}
 *
 * @param jsonMessage message to parse
 * @return ServerMessage or null
 */
@SuppressWarnings("WeakerAccess")
protected ServerMessage parseServerMessageFromJson(String jsonMessage) {
    ServerMessage msg = new ServerMessage();
    try {
        ObjectMapper mapper = Tinode.getJsonMapper();
        JsonParser parser = mapper.getFactory().createParser(jsonMessage);

        // Sanity check: verify that we got "Json Object":
        if (parser.nextToken() != JsonToken.START_OBJECT) {
            throw new JsonParseException(parser, "Packet must start with an object",
                    parser.getCurrentLocation());
        }
        // Iterate over object fields:
        while (parser.nextToken() != JsonToken.END_OBJECT) {
            String name = parser.getCurrentName();
            parser.nextToken();
            JsonNode node = mapper.readTree(parser);
            switch (name) {
                case "ctrl":
                    msg.ctrl = mapper.readValue(node.traverse(), MsgServerCtrl.class);
                    break;
                case "pres":
                    msg.pres = mapper.readValue(node.traverse(), MsgServerPres.class);
                    break;
                case "info":
                    msg.info = mapper.readValue(node.traverse(), MsgServerInfo.class);
                    break;
                case "data":
                    msg.data = mapper.readValue(node.traverse(), MsgServerData.class);
                    break;
                case "meta":
                    if (node.has("topic")) {
                        msg.meta = mapper.readValue(node.traverse(),
                                getTypeOfMetaPacket(node.get("topic").asText()));
                    } else {
                        Log.w(TAG, "Failed to parse {meta}: missing topic name");
                    }
                    break;
                default:  // Unrecognized field, ignore
                    Log.w(TAG, "Unknown field in packet: '" + name + "'");
                    break;
            }
        }
        parser.close(); // important to close both parser and underlying reader
    } catch (IOException e) {
        e.printStackTrace();
    }

    return msg.isValid() ? msg : null;
}
 
Example 15
Source File: JwtHelper.java    From MaxKey with Apache License 2.0 4 votes vote down vote up
static HeaderParameters parseParams(byte[] header) {
	JsonParser jp = null;
	try {
		jp = f.createJsonParser(header);
		String alg = null, enc = null, iv = null;
		jp.nextToken();
		while (jp.nextToken() != JsonToken.END_OBJECT) {
			String fieldname = jp.getCurrentName();
			jp.nextToken();
			if (!JsonToken.VALUE_STRING.equals(jp.getCurrentToken())) {
				throw new IllegalArgumentException("Header fields must be strings");
			}
			String value = jp.getText();
			if ("alg".equals(fieldname)) {
				if (alg != null) {
					throw new IllegalArgumentException("Duplicate 'alg' field");
				}
				alg = value;
			} else if ("enc".equals(fieldname)) {
				if (enc != null) {
					throw new IllegalArgumentException("Duplicate 'enc' field");
				}
				enc = value;
			} if ("iv".equals(fieldname)) {
				if (iv != null) {
					throw new IllegalArgumentException("Duplicate 'iv' field");
				}
				iv = jp.nextToken().asString();
			} else if ("typ".equals(fieldname)) {
				if (!"JWT".equalsIgnoreCase(value)) {
					throw new IllegalArgumentException("typ is not \"JWT\"");
				}
			}
		}

		return new HeaderParameters(alg, enc, iv);
	} catch (IOException io) {
		throw new RuntimeException(io);
	} finally {
		if (jp != null) {
			try {
				jp.close();
			} catch (IOException ignore) {
			}
		}
	}
}
 
Example 16
Source File: JsonResponseHandler.java    From ibm-cos-sdk-java with Apache License 2.0 4 votes vote down vote up
/**
 * @see HttpResponseHandler#handle(HttpResponse)
 */
public AmazonWebServiceResponse<T> handle(HttpResponse response) throws Exception {
    log.trace("Parsing service response JSON");

    String CRC32Checksum = response.getHeaders().get("x-amz-crc32");

    JsonParser jsonParser = null;

    if (shouldParsePayloadAsJson()) {
        jsonParser = jsonFactory.createParser(response.getContent());
    }

    try {
        AmazonWebServiceResponse<T> awsResponse = new AmazonWebServiceResponse<T>();
        JsonUnmarshallerContext unmarshallerContext = new JsonUnmarshallerContextImpl(
                jsonParser, simpleTypeUnmarshallers, customTypeMarshallers, response);
        registerAdditionalMetadataExpressions(unmarshallerContext);

        T result = responseUnmarshaller.unmarshall(unmarshallerContext);

        // Make sure we read all the data to get an accurate CRC32 calculation.
        // See https://github.com/aws/aws-sdk-java/issues/1018
        if (shouldParsePayloadAsJson() && response.getContent() != null) {
            IOUtils.drainInputStream(response.getContent());
        }

        if (CRC32Checksum != null) {
            long serverSideCRC = Long.parseLong(CRC32Checksum);
            long clientSideCRC = response.getCRC32Checksum();
            if (clientSideCRC != serverSideCRC) {
                throw new CRC32MismatchException(
                        "Client calculated crc32 checksum didn't match that calculated by server side");
            }
        }

        awsResponse.setResult(result);

        Map<String, String> metadata = unmarshallerContext.getMetadata();
        metadata.put(ResponseMetadata.AWS_REQUEST_ID,
                     response.getHeaders().get(X_AMZN_REQUEST_ID_HEADER));
        awsResponse.setResponseMetadata(new ResponseMetadata(metadata));

        log.trace("Done parsing service response");
        return awsResponse;
    } finally {
        if (shouldParsePayloadAsJson()) {
            try {
                jsonParser.close();
            } catch (IOException e) {
                log.warn("Error closing json parser", e);
            }
        }
    }
}
 
Example 17
Source File: TableDeserializer.java    From azure-storage-android with Apache License 2.0 4 votes vote down vote up
/**
 * Reserved for internal use. Parses the operation response as an entity. Reads entity data from the specified
 * <code>JsonParser</code> using the specified class type and optionally projects the entity result with the
 * specified resolver into a {@link TableResult} object.
 * 
 * @param inStream
 *            The <code>InputStream</code> to read the data to parse from.
 * @param format
 *            The {@link TablePayloadFormat} to use for parsing.
 * @param options
 *            A {@link TableRequestOptions} object that specifies execution options such as retry policy and timeout
 *            settings for the operation.
 * @param httpStatusCode
 *            The HTTP status code returned with the operation response.
 * @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 entitys as 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} object with the parsed operation response.
 * @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.
 */
static <T extends TableEntity, R> TableResult parseSingleOpResponse(final InputStream inStream,
        final TableRequestOptions options, final int httpStatusCode, final Class<T> clazzType,
        final EntityResolver<R> resolver, final OperationContext opContext) throws 
        InstantiationException, IllegalAccessException, StorageException, JsonParseException, IOException {
    JsonParser parser = createJsonParserFromStream(inStream);

    try {
        final TableResult res = parseJsonEntity(parser, clazzType,
                null /*HashMap<String, PropertyPair> classProperties*/, resolver, options, opContext);
        res.setHttpStatusCode(httpStatusCode);
        return res;
    }
    finally {
        parser.close();
    }
}
 
Example 18
Source File: MonitorsResource.java    From floodlight_with_topoguard with Apache License 2.0 4 votes vote down vote up
protected LBMonitor jsonToMonitor(String json) throws IOException {
    MappingJsonFactory f = new MappingJsonFactory();
    JsonParser jp;
    LBMonitor monitor = new LBMonitor();
    
    try {
        jp = f.createJsonParser(json);
    } catch (JsonParseException e) {
        throw new IOException(e);
    }
    
    jp.nextToken();
    if (jp.getCurrentToken() != JsonToken.START_OBJECT) {
        throw new IOException("Expected START_OBJECT");
    }
    
    while (jp.nextToken() != JsonToken.END_OBJECT) {
        if (jp.getCurrentToken() != JsonToken.FIELD_NAME) {
            throw new IOException("Expected FIELD_NAME");
        }
        
        String n = jp.getCurrentName();
        jp.nextToken();
        if (jp.getText().equals("")) 
            continue;
        else if (n.equals("monitor")) {
            while (jp.nextToken() != JsonToken.END_OBJECT) {
                String field = jp.getCurrentName();
                
                if (field.equals("id")) {
                    monitor.id = jp.getText();
                    continue;
                } 
                if (field.equals("name")) {
                    monitor.name = jp.getText();
                    continue;
                }
                if (field.equals("type")) {
                    monitor.type = Short.parseShort(jp.getText());
                    continue;
                }
                if (field.equals("delay")) {
                    monitor.delay = Short.parseShort(jp.getText());
                    continue;
                }
                if (field.equals("timeout")) {
                    monitor.timeout = Short.parseShort(jp.getText());
                    continue;
                }
                if (field.equals("attempts_before_deactivation")) {
                    monitor.attemptsBeforeDeactivation = Short.parseShort(jp.getText());
                    continue;
                }
                if (field.equals("network_id")) {
                    monitor.netId = jp.getText();
                    continue;
                }
                if (field.equals("address")) {
                    monitor.address = Integer.parseInt(jp.getText());
                    continue;
                }
                if (field.equals("protocol")) {
                    monitor.protocol = Byte.parseByte(jp.getText());
                    continue;
                }
                if (field.equals("port")) {
                    monitor.port = Short.parseShort(jp.getText());
                    continue;
                }
                if (field.equals("admin_state")) {
                    monitor.adminState = Short.parseShort(jp.getText());
                    continue;
                }
                if (field.equals("status")) {
                    monitor.status = Short.parseShort(jp.getText());
                    continue;
                }
                
                log.warn("Unrecognized field {} in " +
                        "parsing Vips", 
                        jp.getText());
            }
        }
    }
    jp.close();

    return monitor;
}
 
Example 19
Source File: MembersResource.java    From floodlight_with_topoguard with Apache License 2.0 4 votes vote down vote up
protected LBMember jsonToMember(String json) throws IOException {
    MappingJsonFactory f = new MappingJsonFactory();
    JsonParser jp;
    LBMember member = new LBMember();
    
    try {
        jp = f.createJsonParser(json);
    } catch (JsonParseException e) {
        throw new IOException(e);
    }
    
    jp.nextToken();
    if (jp.getCurrentToken() != JsonToken.START_OBJECT) {
        throw new IOException("Expected START_OBJECT");
    }
    
    while (jp.nextToken() != JsonToken.END_OBJECT) {
        if (jp.getCurrentToken() != JsonToken.FIELD_NAME) {
            throw new IOException("Expected FIELD_NAME");
        }
        
        String n = jp.getCurrentName();
        jp.nextToken();
        if (jp.getText().equals("")) 
            continue;
        if (n.equals("id")) {
            member.id = jp.getText();
            continue;
        } else
        if (n.equals("address")) {
            member.address = IPv4.toIPv4Address(jp.getText());
            continue;
        } else
        if (n.equals("port")) {
            member.port = Short.parseShort(jp.getText());
            continue;
        } else
        if (n.equals("connection_limit")) {
            member.connectionLimit = Integer.parseInt(jp.getText());
            continue;
        } else
        if (n.equals("admin_state")) {
            member.adminState = Short.parseShort(jp.getText());
            continue;
        } else
        if (n.equals("status")) {
            member.status = Short.parseShort(jp.getText());
            continue;
        } else
        if (n.equals("pool_id")) {
            member.poolId = jp.getText();
            continue;
        } 
        
        log.warn("Unrecognized field {} in " +
                "parsing Members", 
                jp.getText());
    }
    jp.close();

    return member;
}
 
Example 20
Source File: StreamingEvent.java    From invest-openapi-java-sdk with Apache License 2.0 4 votes vote down vote up
@Override
public StreamingEvent deserialize(JsonParser p, DeserializationContext ctxt)
        throws IOException, JsonProcessingException {

    final ObjectNode node = (ObjectNode) p.getCodec().readTree(p);
    final JsonNode eventNameNode = node.get("event");

    if (eventNameNode == null || !eventNameNode.isTextual()) {
        throw new JsonParseException(p, "No type field 'event'.");
    }

    final String eventName = eventNameNode.asText();
    final JsonNode payloadNode = node.get("payload");

    if (payloadNode == null || !payloadNode.isObject()) {
        throw new JsonParseException(p, "No data field 'payload'.");
    }

    final ObjectMapper mapper = new ObjectMapper();
    mapper.registerModule(new JavaTimeModule());

    StreamingEvent result;
    switch (eventName) {
        case "candle":
            result = mapper.readValue(mapper.writeValueAsString(payloadNode), Candle.class);
            break;
        case "orderbook":
            result = mapper.readValue(mapper.writeValueAsString(payloadNode), Orderbook.class);
            break;
        case "instrument_info":
            result = mapper.readValue(mapper.writeValueAsString(payloadNode), InstrumentInfo.class);
            break;
        case "error":
            result = mapper.readValue(mapper.writeValueAsString(payloadNode), Error.class);
            break;
        default:
            throw new JsonParseException(p, "Unknown event type.");
    }

    p.close();

    return result;
}