javax.json.stream.JsonParser Java Examples

The following examples show how to use javax.json.stream.JsonParser. 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: MicroProfileMetricsIntegrationTest.java    From wildfly-camel with Apache License 2.0 6 votes vote down vote up
private void assertComplexMetricValue(CamelContext camelctx, String metricName, Number metricValue) throws Exception {
    String metrics = getMetrics();

    JsonParser parser = Json.createParser(new StringReader(metrics));
    Assert.assertTrue("Metrics endpoint content is empty", parser.hasNext());
    parser.next();

    JsonObject jsonObject = parser.getObject();
    JsonNumber result = null;
    String[] nameParts = metricName.split("\\.");
    for (int i = 0; i < nameParts.length; i++) {
        String jsonKey = i + 1 == nameParts.length ? nameParts[i] + ";camelContext=" + camelctx.getName() : nameParts[i];

        if (i + 1 == nameParts.length) {
            result = jsonObject.getJsonNumber(jsonKey);
            break;
        } else {
            jsonObject = jsonObject.getJsonObject(jsonKey);
        }
    }

    Assert.assertNotNull("Expected to find metric " + metricName, result);
    Assert.assertEquals("Expected metric " + metricName + " to have value " + metricValue, metricValue, result.intValue());
}
 
Example #2
Source File: JsonpReader.java    From incubator-batchee with Apache License 2.0 6 votes vote down vote up
@Override
public void open(final Serializable checkpoint) throws Exception {
    final ClassLoader loader = Thread.currentThread().getContextClassLoader();
    final JsonProvider provider = this.provider == null ? JsonProvider.provider() : JsonProvider.class.cast(loader.loadClass(this.provider));
    parser = provider.createParser(new FileInputStream(file));
    reader = new JsonPartialReader(provider, parser);

    if (skipRoot == null || "true".equalsIgnoreCase(skipRoot)) {
        final JsonParser.Event event = parser.next();
        if (event == JsonParser.Event.START_ARRAY) {
            end = JsonParser.Event.END_ARRAY;
        } else {
            end = JsonParser.Event.END_OBJECT;
        }
    }
    super.open(checkpoint);
}
 
Example #3
Source File: Index.java    From FHIR with Apache License 2.0 6 votes vote down vote up
private void parseFiles(JsonParser parser) {
    int i = 0;
    while (parser.hasNext()) {
        Event event = parser.next();
        switch (event) {
        case START_OBJECT:
            try {
                parseFile(parser);
            } catch (NullPointerException e) {
                log.log(Level.WARNING, "Skipping index entry " + i + " due to " +
                    "one or more missing required fields, beginning with: " + e.getMessage());
            }
            i++;
            break;
        case END_ARRAY:
            return;
        default:
            break;
        }
    }
}
 
Example #4
Source File: SoapFidoClient.java    From fido2 with GNU Lesser General Public License v2.1 6 votes vote down vote up
public static void printJson(String Input) {
    JsonParserFactory factory = Json.createParserFactory(null);
    JsonParser parser = factory.createParser(new StringReader(Input));

    System.out.println("\t{");
    while (parser.hasNext()) {
        Event event = parser.next();

        switch (event) {
            case KEY_NAME: {
                System.out.print("\t\"" + parser.getString() + "\" : \"");
                break;
            }
            case VALUE_STRING: {
                System.out.println(parser.getString() + "\",");
                break;
            }
        }
    }
    System.out.println("\t}");

}
 
Example #5
Source File: Client.java    From webex-java-sdk with MIT License 6 votes vote down vote up
public <T> LinkedResponse<List<T>> paginate(final Class<T> clazz, URL url) {
    LinkedResponse.BodyCreator<List<T>> function = new LinkedResponse.BodyCreator<List<T>>() {
        @Override
        public List<T> create(InputStream istream) {
            JsonParser parser = Json.createParser(istream);
            Client.this.scrollToItemsArray(parser);

            List<T> result = new ArrayList<T>();
            for (JsonParser.Event event = parser.next();
                 event == JsonParser.Event.START_OBJECT;
                 event = parser.next()) {
                result.add(readObject(clazz, parser));
            }
            return result;
        }
    };

    try {
        return new LinkedResponse<List<T>>(this, url, function);
    } catch (IOException e) {
        throw new SparkException("io error", e);
    }
}
 
Example #6
Source File: ParsingJSONFiles.java    From Java-Data-Analysis with MIT License 6 votes vote down vote up
public static ArrayList getList(JsonParser parser) {
    ArrayList list = new ArrayList();
    Event event = parser.next();  // advance past START_ARRAY
    while (!event.equals(Event.END_ARRAY)) {
        if (event.equals(Event.VALUE_STRING)) {
            list.add(parser.getString());
            event = parser.next();
        } else if (event.equals(Event.START_OBJECT)) {
            HashMap<String,Object> map = getMap(parser);
            list.add(map);
            event = parser.next();
        } else if (event.equals(Event.START_ARRAY)) {
            ArrayList subList = getList(parser);   //  recursion
            list.add(subList);
            event = parser.next();
        }
    }
    return list;
}
 
Example #7
Source File: JsonQueryMessageDecoder.java    From datawave with Apache License 2.0 6 votes vote down vote up
@Override
public QueryMessage decode(String s) throws DecodeException {
    MultivaluedMapImpl<String,String> map = new MultivaluedMapImpl<>();
    try (JsonParser parser = Json.createParser(new StringReader(s))) {
        while (parser.hasNext()) {
            if (parser.next() == JsonParser.Event.KEY_NAME) {
                String key = parser.getString();
                addValueToMap(key, parser, map);
            }
        }
    }
    if (map.size() == 1 && map.containsKey("cancel"))
        return new CancelMessage();
    else
        return new CreateQueryMessage(map);
}
 
Example #8
Source File: JsonXmlReader.java    From iaf with Apache License 2.0 6 votes vote down vote up
public boolean parse(String key, JsonParser parser) throws IOException, SAXException {
	Event event = parser.next();
	if (event.equals(Event.START_OBJECT)) {
		startElement("map", key);
		while ((event = parser.next())!=Event.END_OBJECT) {
			if (event!=Event.KEY_NAME) {
				throw new SAXException("expected key name at "+parser.getLocation());
			}
			key=parser.getString();
			parse(key,parser);
		};
		endElement("map");
	} else if (event==Event.END_ARRAY) {
		return false;
	} else if (event==Event.START_ARRAY) {
		startElement("array", key);
		while (parse(null,parser)); // parse array elements until the close
		endElement("array");
	} else {
		if (event==Event.VALUE_NULL) {
			simpleElement("null", key, null);
		} else {
			if (event==Event.VALUE_FALSE) {
				simpleElement("boolean", key, "false");
			} else {
				if (event==Event.VALUE_TRUE) {
					simpleElement("boolean", key, "true");
				} else {
					String value =parser.getString();
					if (event==Event.VALUE_NUMBER) {
						simpleElement("number", key, value);
					} else {
						simpleElement("string", key, value);
					}
				}
			}
		}
	}
	return true;
}
 
Example #9
Source File: BookDeserializer.java    From Java-EE-8-Sampler with MIT License 6 votes vote down vote up
@Override
public Book deserialize(JsonParser parser, DeserializationContext ctx, Type rtType) {
    Book book = null;
    while (parser.hasNext()) {
        JsonParser.Event event = parser.next();
        if (event == JsonParser.Event.KEY_NAME) {
            String className = parser.getString();
            parser.next();
            try {
                book = ctx.deserialize(Class.forName(className).asSubclass(Book.class), parser);
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        }
    }
    return book;
}
 
Example #10
Source File: VehicleDeserializer.java    From quarkus with Apache License 2.0 6 votes vote down vote up
@Override
public Vehicle deserialize(JsonParser parser, DeserializationContext ctx, Type rtType) {
    JsonObject json = parser.getObject();
    String type = json.getString("type");
    switch (type) {
        case "CAR":
            Car car = new Car();
            car.type = type;
            car.seatNumber = json.getInt("seatNumber");
            car.name = json.getString("name");
            return car;
        case "MOTO":
            Moto moto = new Moto();
            moto.type = type;
            moto.name = json.getString("name");
            moto.sideCar = json.getBoolean("sideCar");
            return moto;
        default:
            throw new RuntimeException("Type " + type + "not managed");
    }
}
 
Example #11
Source File: WeatherServiceTest.java    From tomee with Apache License 2.0 6 votes vote down vote up
private List<JsonItem> convertToMap(String s) {
    JsonParser expectedParser = Json.createParser(new StringReader(s));
    List<JsonItem> list = new ArrayList<>();
    while (expectedParser.hasNext()) {
        JsonParser.Event event = expectedParser.next();
        switch (event) {
            case KEY_NAME:
            case VALUE_STRING:
            case VALUE_NUMBER:
                list.add(new JsonItem(event, expectedParser.getValue().toString()));
                break;
            default:
                list.add(new JsonItem(event));
        }
    }
    return list;
}
 
Example #12
Source File: MessageDecoder.java    From javaee7-websocket with MIT License 6 votes vote down vote up
@Override
public boolean willDecode(String string) {
    boolean decodes = false;
    /* Convert the message into a map */
    messageMap = new HashMap<>();
    JsonParser parser = Json.createParser(new StringReader(string));
    while (parser.hasNext()) {
        if (parser.next() == JsonParser.Event.KEY_NAME) {
            String key = parser.getString();
            parser.next();
            String value = parser.getString();
            messageMap.put(key, value);
        }
    }
    /* Check the kind of message and if all fields are included */
    Set keys = messageMap.keySet();
    if (keys.contains("type")) {
        switch (messageMap.get("type")) {
            case "betMatchWinner":
                if (keys.contains("name"))
                    decodes = true;
                break;
        }
    }
    return decodes;
}
 
Example #13
Source File: JsonpTest.java    From ee8-sandbox with Apache License 2.0 5 votes vote down vote up
@Test
public void testJsonParser() {
    String key = "";
    String value = "";
    JsonParser parser = Json.createParser(JsonpTest.class.getResourceAsStream("/person.json"));
    while (parser.hasNext()) {
        JsonParser.Event e = parser.next();
        System.out.print(e.name());

        switch (e) {
            case START_ARRAY:
                if (key.equals("phoneNumbers")) {
                    parser.skipArray();
                }
                break;
            case KEY_NAME:
                key = parser.getString();
                System.out.print(" - " + parser.getString());
                break;
            case VALUE_STRING:
                System.out.print(" - " + parser.getString());
                if ("name".equals(key)) {
                    value = parser.getString();
                }
        }

        System.out.println();
    }

    assertEquals("Duke", value);
}
 
Example #14
Source File: AbstractDeserializer.java    From robozonky with Apache License 2.0 5 votes vote down vote up
@Override
public T deserialize(JsonParser parser, DeserializationContext ctx, Type rtType) {
    try {
        var id = parser.getString();
        return converter.apply(id);
    } catch (final Exception ex) {
        logger.warn("Received unknown value from Zonky: '{}'. This may be a problem, but we continue.",
                parser.getString());
        return defaultValue;
    }
}
 
Example #15
Source File: MicroProfileMetricsIntegrationTest.java    From wildfly-camel with Apache License 2.0 5 votes vote down vote up
private void assertSimpleMetricValue(CamelContext camelctx, String metricName, Number metricValue) throws Exception {
    String metrics = getMetrics();

    JsonParser parser = Json.createParser(new StringReader(metrics));
    Assert.assertTrue("Metrics endpoint content is empty", parser.hasNext());
    parser.next();

    JsonNumber jsonNumber = parser.getObject().getJsonNumber(metricName + ";camelContext=" + camelctx.getName());

    Assert.assertEquals("Expected to find metric" + metricName + " with value " + metricValue, metricValue, jsonNumber.intValue());
}
 
Example #16
Source File: JsonUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void whenUsingStreamingApiToQueryForSpecificProperty_thenExpectedValueIsReturned(
        ) throws IOException, ParseException {
    JsonParser jsonParser = Json.createParser(new StringReader(petshopJson));
    
    int count = 0;
    String result = null;
    
    while(jsonParser.hasNext()) {
        Event e = jsonParser.next();
        
        if (e == Event.KEY_NAME) {
            if(jsonParser.getString().equals("name")) {
               jsonParser.next();
               
               if(++count == 3) {
                   result = jsonParser.getString();
                   break;
               }
            }   
        }
    }
    
    assertEquals(
            "The query should return the 'name' property of the third pet from the list", 
            "Jake", 
            result);
}
 
Example #17
Source File: FEreturn.java    From fido2 with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Returns a pretty Json
 * @param Input
 * @return
 */
public String returnJSON(String Input) {
    String JSON_FORMAT_STRING = "%-10s";
    JsonParserFactory factory = Json.createParserFactory(null);

    StringBuilder sb;
    try (JsonParser parser = factory.createParser(new StringReader(Input))) {
        sb = new StringBuilder();
        sb.append("\n\t{\n");
        while (parser.hasNext()) {
            JsonParser.Event event = parser.next();

            switch (event) {
                case KEY_NAME: {
                    sb.append("\t\t\"");
                    sb.append(String.format(JSON_FORMAT_STRING, parser.getString()));
                    sb.append("\" : \"");
                    break;
                }
                case VALUE_STRING: {
                    sb.append(parser.getString()).append("\",\n");
                    break;
                }
            }
        }   sb.append("\t}");
    }

    return sb.toString();
}
 
Example #18
Source File: WeatherServiceTest.java    From tomee with Apache License 2.0 5 votes vote down vote up
private void removeStdDevValue(List<JsonItem> list) {
    // Check for value 7.xxxxxxxxxxxxx.
    Optional<JsonItem> stddevValue = list.stream().filter(item->item.event == JsonParser.Event.VALUE_NUMBER && item.value.startsWith("7.") && item.value.length() > 3).findFirst();
    assertTrue(stddevValue.isPresent());

    list.remove(stddevValue.get());
}
 
Example #19
Source File: UserDeserializer.java    From tomee with Apache License 2.0 5 votes vote down vote up
@Override
public User deserialize(JsonParser parser, DeserializationContext ctx, Type rtType) {
	JsonObject jo = parser.getObject();
	String name = jo.get("name").toString().replace("\"", "");
	if (jo.get("extra") != null) {
		name = name + jo.get("extra").toString().replace("\"", "");
	}
	User u = new User(Integer.parseInt(jo.get("id").toString()), name, null);

	return u;
}
 
Example #20
Source File: ActionMessage.java    From sample.daytrader7 with Apache License 2.0 5 votes vote down vote up
public void doDecoding(String jsonText) {
          
    String keyName = null;
    try 
    {
        // JSON parse
        JsonParser parser = Json.createParser(new StringReader(jsonText));
        while (parser.hasNext()) {
            JsonParser.Event event = parser.next();
            switch(event) {
            case KEY_NAME:
                keyName=parser.getString();
                break;
            case VALUE_STRING:
                if (keyName != null && keyName.equals("action")) {
                    decodedAction=parser.getString();
                }
                break;
            default:
                break;
            }
        }
    } catch (Exception e) {
        Log.error("ActionMessage:doDecoding(" + jsonText + ") --> failed", e);
    }
    
    if (Log.doTrace()) {
        if (decodedAction != null ) {
            Log.trace("ActionMessage:doDecoding -- decoded action -->" + decodedAction + "<--");
        } else {
            Log.trace("ActionMessage:doDecoding -- decoded action -->null<--");
        }
    }
    
}
 
Example #21
Source File: AuctionDataItemReader.java    From wow-auctions with GNU General Public License v3.0 5 votes vote down vote up
@Override
public Object readItem() throws Exception {
    while (parser.hasNext()) {
        JsonParser.Event event = parser.next();
        Auction auction = new Auction();
        switch (event) {
            case KEY_NAME:
                if (readAuctionItem(auction)) {
                    return auction;
                }
                break;
        }
    }
    return null;
}
 
Example #22
Source File: Client.java    From webex-java-sdk with MIT License 5 votes vote down vote up
private void scrollToItemsArray(JsonParser parser) {
    JsonParser.Event event;
    while (parser.hasNext()) {
        event = parser.next();
        if (event == JsonParser.Event.KEY_NAME &&  parser.getString().equals("items")) {
            break;
        }
    }

    event = parser.next();
    if (event != JsonParser.Event.START_ARRAY) {
        throw new SparkException("bad json");
    }
}
 
Example #23
Source File: BookDeserializer.java    From Java-EE-8-Sampler with MIT License 5 votes vote down vote up
@Override
public String deserialize(JsonParser parser, DeserializationContext ctx, Type rtType) {
    while (parser.hasNext()) {
        JsonParser.Event event = parser.next();
        if (event == JsonParser.Event.KEY_NAME) {
            String keyName = parser.getString();
            if (keyName.equals("id")) {
                return ctx.deserialize(String.class, parser);
            }
        }
        parser.next();
    }
    return "";
}
 
Example #24
Source File: JsonpReader.java    From incubator-batchee with Apache License 2.0 5 votes vote down vote up
@Override
protected Object doRead() throws Exception {
    JsonParser.Event event;
    do {
        event = parser.next();
    } while (
        (event != JsonParser.Event.START_OBJECT && event != end) ||
        (end == null && (event == JsonParser.Event.END_ARRAY ||
        event == JsonParser.Event.END_OBJECT)));
    if (!parser.hasNext()) {
        return null;
    }

    return reader.read(event);
}
 
Example #25
Source File: CustomConfigSource.java    From microprofile-sandbox with Apache License 2.0 5 votes vote down vote up
public Map<String, String> getProperties() {
    Map<String, String> m = new HashMap<String, String>();
    String jsonData = this.readFile(this.fileLocation);
    JsonParser parser = Json.createParser(new StringReader(jsonData));
    String key = null;
    while (parser.hasNext()) {
        final Event event = parser.next();
        switch (event) {
        case KEY_NAME:
            key = parser.getString();
            break;
        case VALUE_STRING:
            String string = parser.getString();
            m.put(key, string);
            break;
        case VALUE_NUMBER:
            BigDecimal number = parser.getBigDecimal();
            m.put(key, number.toString());
            break;
        case VALUE_TRUE:
            m.put(key, "true");
            break;
        case VALUE_FALSE:
            m.put(key, "false");
            break;
        default:
            break;
        }
    }
    parser.close();
    return m;
}
 
Example #26
Source File: ObjectIdDeserializer.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@Override
public ObjectId deserialize(JsonParser parser, DeserializationContext ctx, Type rtType) {
    String id = parser.getString();
    if (id != null) {
        return new ObjectId(id);
    }
    return null;
}
 
Example #27
Source File: JsonPartialReader.java    From incubator-batchee with Apache License 2.0 5 votes vote down vote up
public JsonStructure read(final JsonParser.Event event) {
    switch (event) {
        case START_OBJECT:
            final JsonObjectBuilder objectBuilder = provider.createObjectBuilder();
            parseObject(objectBuilder);
            return objectBuilder.build();
        case START_ARRAY:
            final JsonArrayBuilder arrayBuilder = provider.createArrayBuilder();
            parseArray(arrayBuilder);
            return arrayBuilder.build();
        default:
            throw new JsonParsingException("Unknown structure: " + parser.next(), parser.getLocation());
    }

}
 
Example #28
Source File: Pet.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
@Override
public StatusEnum deserialize(JsonParser parser, DeserializationContext ctx, Type rtType) {
    for (StatusEnum b : StatusEnum.values()) {
        if (String.valueOf(b.value).equals(parser.getString())) {
            return b;
        }
    }
    throw new IllegalArgumentException("Unexpected value '" + parser.getString() + "'");
}
 
Example #29
Source File: Index.java    From FHIR with Apache License 2.0 5 votes vote down vote up
public void load(Reader reader) {
    JsonParser parser = PARSER_FACTORY.createParser(reader);

    String keyName = null;
    while (parser.hasNext()) {
        Event event = parser.next();
        switch (event) {
        case KEY_NAME:
            keyName = parser.getString();
            break;
        case VALUE_NUMBER:
            if ("index-version".equals(keyName)) {
                version = parser.getInt();
            }
        case START_ARRAY:
            if ("files".equals(keyName)) {
                parseFiles(parser);
            }
            break;
        default:
            break;
        }
    }

    parser.close();

    if (version < 1) {
        throw new IllegalStateException("index version was not set");
    }
}
 
Example #30
Source File: CustomConfigSource.java    From boost with Eclipse Public License 1.0 5 votes vote down vote up
public Map<String, String> getProperties() {
    Map<String, String> m = new HashMap<String, String>();
    String jsonData = this.readFile(this.fileLocation);
    JsonParser parser = Json.createParser(new StringReader(jsonData));
    String key = null;
    while (parser.hasNext()) {
        final Event event = parser.next();
        switch (event) {
        case KEY_NAME:
            key = parser.getString();
            break;
        case VALUE_STRING:
            String string = parser.getString();
            m.put(key, string);
            break;
        case VALUE_NUMBER:
            BigDecimal number = parser.getBigDecimal();
            m.put(key, number.toString());
            break;
        case VALUE_TRUE:
            m.put(key, "true");
            break;
        case VALUE_FALSE:
            m.put(key, "false");
            break;
        default:
            break;
        }
    }
    parser.close();
    return m;
}