Java Code Examples for org.codehaus.jackson.JsonToken#START_OBJECT

The following examples show how to use org.codehaus.jackson.JsonToken#START_OBJECT . 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: HiveJsonStructReader.java    From incubator-hivemall with Apache License 2.0 6 votes vote down vote up
private static void skipValue(JsonParser parser) throws JsonParseException, IOException {
    int array = 0;
    int object = 0;
    do {
        JsonToken currentToken = parser.getCurrentToken();
        if (currentToken == JsonToken.START_ARRAY) {
            array++;
        }
        if (currentToken == JsonToken.END_ARRAY) {
            array--;
        }
        if (currentToken == JsonToken.START_OBJECT) {
            object++;
        }
        if (currentToken == JsonToken.END_OBJECT) {
            object--;
        }

        parser.nextToken();

    } while (array > 0 || object > 0);
}
 
Example 2
Source File: BarFileUtils.java    From io with Apache License 2.0 6 votes vote down vote up
/**
 * barファイルエントリからJSONファイルを読み込む.
 * @param <T> JSONMappedObject
 * @param inStream barファイルエントリのInputStream
 * @param entryName entryName
 * @param clazz clazz
 * @return JSONファイルから読み込んだオブジェクト
 * @throws IOException JSONファイル読み込みエラー
 */
public static <T> T readJsonEntry(
        InputStream inStream, String entryName, Class<T> clazz) throws IOException {
    JsonParser jp = null;
    ObjectMapper mapper = new ObjectMapper();
    JsonFactory f = new JsonFactory();
    jp = f.createJsonParser(inStream);
    JsonToken token = jp.nextToken(); // JSONルート要素("{")
    Pattern formatPattern = Pattern.compile(".*/+(.*)");
    Matcher formatMatcher = formatPattern.matcher(entryName);
    String jsonName = formatMatcher.replaceAll("$1");
    T json = null;
    if (token == JsonToken.START_OBJECT) {
        try {
            json = mapper.readValue(jp, clazz);
        } catch (UnrecognizedPropertyException ex) {
            throw DcCoreException.BarInstall.JSON_FILE_FORMAT_ERROR.params(jsonName);
        }
    } else {
        throw DcCoreException.BarInstall.JSON_FILE_FORMAT_ERROR.params(jsonName);
    }
    return json;
}
 
Example 3
Source File: EventResource.java    From io with Apache License 2.0 6 votes vote down vote up
/**
 * リクエストボディを解析してEventオブジェクトを取得する.
 * @param reader Http入力ストリーム
 * @return 解析したEventオブジェクト
 */
protected JSONEvent getRequestBody(final Reader reader) {
    JSONEvent event = null;
    JsonParser jp = null;
    ObjectMapper mapper = new ObjectMapper();
    JsonFactory f = new JsonFactory();
    try {
        jp = f.createJsonParser(reader);
        JsonToken token = jp.nextToken(); // JSONルート要素("{")
        if (token == JsonToken.START_OBJECT) {
            event = mapper.readValue(jp, JSONEvent.class);
        } else {
            throw DcCoreException.Event.JSON_PARSE_ERROR;
        }
    } catch (IOException e) {
        throw DcCoreException.Event.JSON_PARSE_ERROR;
    }
    return event;
}
 
Example 4
Source File: AbstractSiteToSiteReportingTask.java    From nifi with Apache License 2.0 6 votes vote down vote up
public JsonRecordReader(final InputStream in, RecordSchema recordSchema) throws IOException, MalformedRecordException {
    this.recordSchema = recordSchema;
    try {
        jsonParser = new JsonFactory().createJsonParser(in);
        jsonParser.setCodec(new ObjectMapper());
        JsonToken token = jsonParser.nextToken();
        if (token == JsonToken.START_ARRAY) {
            array = true;
            token = jsonParser.nextToken();
        } else {
            array = false;
        }
        if (token == JsonToken.START_OBJECT) {
            firstJsonNode = jsonParser.readValueAsTree();
        } else {
            firstJsonNode = null;
        }
    } catch (final JsonParseException e) {
        throw new MalformedRecordException("Could not parse data as JSON", e);
    }
}
 
Example 5
Source File: JsonSerdeUtils.java    From incubator-hivemall with Apache License 2.0 5 votes vote down vote up
private static void skipValue(@Nonnull final JsonParser p)
        throws JsonParseException, IOException {
    JsonToken valueToken = p.nextToken();
    if ((valueToken == JsonToken.START_ARRAY) || (valueToken == JsonToken.START_OBJECT)) {
        // if the currently read token is a beginning of an array or object, move stream forward
        // skipping any child tokens till we're at the corresponding END_ARRAY or END_OBJECT token
        p.skipChildren();
    }
}
 
Example 6
Source File: HiveJsonStructReader.java    From incubator-hivemall with Apache License 2.0 5 votes vote down vote up
private Object parseMap(JsonParser parser, MapObjectInspector oi)
        throws IOException, SerDeException {
    if (parser.getCurrentToken() == JsonToken.VALUE_NULL) {
        parser.nextToken();
        return null;
    }

    Map<Object, Object> ret = new LinkedHashMap<>();

    if (parser.getCurrentToken() != JsonToken.START_OBJECT) {
        throw new SerDeException("struct expected");
    }

    if (!(oi.getMapKeyObjectInspector() instanceof PrimitiveObjectInspector)) {
        throw new SerDeException("map key must be a primitive");
    }
    PrimitiveObjectInspector keyOI = (PrimitiveObjectInspector) oi.getMapKeyObjectInspector();
    ObjectInspector valOI = oi.getMapValueObjectInspector();

    JsonToken currentToken = parser.nextToken();
    while (currentToken != null && currentToken != JsonToken.END_OBJECT) {

        if (currentToken != JsonToken.FIELD_NAME) {
            throw new SerDeException("unexpected token: " + currentToken);
        }

        Object key = parseMapKey(parser, keyOI);
        Object val = parseDispatcher(parser, valOI);
        ret.put(key, val);

        currentToken = parser.getCurrentToken();
    }
    if (currentToken != null) {
        parser.nextToken();
    }
    return ret;
}
 
Example 7
Source File: BarFileReadRunner.java    From io with Apache License 2.0 5 votes vote down vote up
/**
 * 10_relations.json, 20_roles.json, 30_extroles.json, 70_$links.json, 10_odatarelations.jsonのバリデートチェック.
 * @param jp Jsonパース
 * @param mapper ObjectMapper
 * @param jsonName ファイル名
 * @throws IOException IOException
 */
protected void registJsonEntityData(JsonParser jp, ObjectMapper mapper, String jsonName) throws IOException {
    JsonToken token;
    token = jp.nextToken();

    // Relations,Roles,ExtRoles,$linksのチェック
    checkMatchFieldName(jp, jsonName);

    token = jp.nextToken();
    // 配列でなければエラー
    if (token != JsonToken.START_ARRAY) {
        throw DcCoreException.BarInstall.JSON_FILE_FORMAT_ERROR.params(jsonName);
    }
    token = jp.nextToken();

    while (jp.hasCurrentToken()) {
        if (token == JsonToken.END_ARRAY) {
            break;
        } else if (token != JsonToken.START_OBJECT) {
            throw DcCoreException.BarInstall.JSON_FILE_FORMAT_ERROR.params(jsonName);
        }

        // 1件登録処理
        JSONMappedObject mappedObject = barFileJsonValidate(jp, mapper, jsonName);
        if (jsonName.equals(RELATION_JSON)) {
            createRelation(mappedObject.getJson());
        } else if (jsonName.equals(ROLE_JSON)) {
            createRole(mappedObject.getJson());
        } else if (jsonName.equals(EXTROLE_JSON)) {
            createExtRole(mappedObject.getJson());
        } else if (jsonName.equals(LINKS_JSON)) {
            createLinks(mappedObject, odataProducer);
        }

        token = jp.nextToken();
    }
}
 
Example 8
Source File: AbstractJsonRowRecordReader.java    From nifi with Apache License 2.0 5 votes vote down vote up
public AbstractJsonRowRecordReader(final InputStream in, final ComponentLog logger, final String dateFormat, final String timeFormat, final String timestampFormat)
        throws IOException, MalformedRecordException {

    this.logger = logger;

    final DateFormat df = dateFormat == null ? null : DataTypeUtils.getDateFormat(dateFormat);
    final DateFormat tf = timeFormat == null ? null : DataTypeUtils.getDateFormat(timeFormat);
    final DateFormat tsf = timestampFormat == null ? null : DataTypeUtils.getDateFormat(timestampFormat);

    LAZY_DATE_FORMAT = () -> df;
    LAZY_TIME_FORMAT = () -> tf;
    LAZY_TIMESTAMP_FORMAT = () -> tsf;

    try {
        jsonParser = jsonFactory.createJsonParser(in);
        jsonParser.setCodec(codec);

        JsonToken token = jsonParser.nextToken();
        if (token == JsonToken.START_ARRAY) {
            token = jsonParser.nextToken(); // advance to START_OBJECT token
        }

        if (token == JsonToken.START_OBJECT) { // could be END_ARRAY also
            firstJsonNode = jsonParser.readValueAsTree();
        } else {
            firstJsonNode = null;
        }
    } catch (final JsonParseException e) {
        throw new MalformedRecordException("Could not parse data as JSON", e);
    }
}
 
Example 9
Source File: JsonRecordSource.java    From nifi with Apache License 2.0 5 votes vote down vote up
@Override
public JsonNode next() throws IOException {
    while (true) {
        final JsonToken token = jsonParser.nextToken();
        if (token == null) {
            return null;
        }

        if (token == JsonToken.START_OBJECT) {
            return jsonParser.readValueAsTree();
        }
    }
}
 
Example 10
Source File: WebStorageImpl.java    From openemm with GNU Affero General Public License v3.0 4 votes vote down vote up
private void collectDataMap(Map<String, WebStorageEntry> dataMapToCollectIn, String dataAsJson) throws IOException {
    Map<String, Class<? extends WebStorageEntry>> typeMap = new HashMap<>();
    ObjectMapper mapper = new ObjectMapper();

    mapper.disable(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES);

    for (WebStorageBundle<? extends WebStorageEntry> bundle : WebStorageBundle.definitions()) {
        typeMap.put(bundle.getName(), bundle.getType());
    }

    JsonFactory factory = new JsonFactory();

    try (JsonParser parser = factory.createJsonParser(dataAsJson)) {
        parser.setCodec(mapper);

        if (JsonToken.START_OBJECT != parser.nextToken()) {
            throw new IOException("Missing expected `{` token");
        }

        for ( ; ; ) {
            JsonToken token = parser.nextToken();

            if (token == JsonToken.FIELD_NAME) {
                String name = parser.getCurrentName();
                Class<? extends WebStorageEntry> type = typeMap.get(name);

                parser.nextToken();

                if (type == null) {
                    parser.skipChildren();
                    logger.warn("Missing expected definition for `" + name + "` bundle");
                } else {
                    try {
                        dataMapToCollectIn.put(name, mapper.readValue(parser.readValueAsTree(), type));
                    } catch (JsonMappingException e) {
                        logger.warn("Failed to deserialize `" + name + "` bundle", e);
                    }
                }
            } else if (token == JsonToken.END_OBJECT) {
                return;
            } else {
                throw new IOException("Unexpected token (field name or `}` were expected)");
            }
        }
    }
}
 
Example 11
Source File: PNetGenerationCommand.java    From workcraft with MIT License 4 votes vote down vote up
public static void initParse(String args) throws IOException {
    JsonFactory f = new MappingJsonFactory();
    JsonParser jp = f.createJsonParser(new File(args));

    JsonToken current;

    current = jp.nextToken();
    if (current != JsonToken.START_OBJECT) {
        LogUtils.logError("Root should be object: quiting.");
        return;
    }

    while (jp.nextToken() != JsonToken.END_OBJECT) {
        String fieldName = jp.getCurrentName();
        // move from field name to field value
        current = jp.nextToken();

        if ("NETWORK".equals(fieldName)) {
            if (current == JsonToken.START_ARRAY) {
                // For each of the records in the array
                System.out.println("Generate CPNs");
                while (jp.nextToken() != JsonToken.END_ARRAY) {
                    JsonNode node = jp.readValueAsTree();
                    String idName = node.get("id").toString();
                    String idName1 = "";
                    String idName2 = "";
                    String idNamep = "";
                    String idNamep1 = "";
                    String idNamep2 = "";
                    String typeName = node.get("type").toString();
                    //System.out.println("id: " + idName + "type: " + typeName);
                    lst2.add(new Ids(idName, typeName));
                    JsonNode y = node.get("outs");
                    if (y != null) {
                        for (int i = 0; y.has(i); i++) {
                            if (y.get(i).has("id")) {
                                if (i == 0) {
                                    idName1 = y.get(i).get("id").toString();
                                    idNamep1 = y.get(i).get("in_port").toString();
                                    if ("xfork".equals(typeName)) {
                                        lst.add(new Info(idName1, idName, "b", idNamep1));
                                    } else if ("xswitch".equals(typeName)) {
                                        lst.add(new Info(idName1, idName, "a", idNamep1));
                                    } else {
                                        lst.add(new Info(idName1, idName, "", idNamep1));
                                    }
                                    if (idName1.contains("Sync")) {
                                        //System.out.println("id: " + idName + "sync: " + idName1);
                                        slsti.add(new Info(idName, idName1, "", idNamep1));   //swapped order slsti slsto
                                    }
                                    //add o based on order of i or reverse?
                                    if (idName.contains("Sync")) {
                                        slsto2.add(new Info(idName1, idName, "", idNamep1));
                                    }
                                } else if (i == 1) {
                                    idName2 = y.get(i).get("id").toString();
                                    idNamep2 = y.get(i).get("in_port").toString();
                                    if ("xfork".equals(typeName)) {
                                        lst.add(new Info(idName2, idName, "a", idNamep2));
                                    } else if ("xswitch".equals(typeName)) {
                                        lst.add(new Info(idName2, idName, "b", idNamep2));
                                    } else {
                                        lst.add(new Info(idName2, idName, "", idNamep2));
                                    }
                                    if (idName2.contains("Sync")) slsti.add(new Info(idName, idName2, "", idNamep2));
                                    if (idName.contains("Sync")) {
                                        slsto2.add(new Info(idName2, idName, "", idNamep2));
                                    }
                                } else {
                                    idName1 = y.get(i).get("id").toString();
                                    idNamep = y.get(i).get("in_port").toString();
                                    if (idName.contains("Sync")) {
                                        slsto2.add(new Info(idName, idName1, "", idNamep));
                                    }
                                }
                            }
                        }
                    }
                }
            } else {
                LogUtils.logError("Records should be an array: skipping.");
                jp.skipChildren();
            }
        } else {
            //System.out.println("Unprocessed property: " + fieldName);
            jp.skipChildren();
        }
    }
}
 
Example 12
Source File: BackendResponse.java    From ReactiveLab with Apache License 2.0 4 votes vote down vote up
private static BackendResponse parseBackendResponse(JsonParser parser) throws IOException {
    try {
        // Sanity check: verify that we got "Json Object":
        if (parser.nextToken() != JsonToken.START_OBJECT) {
            throw new IOException("Expected data to start with an Object");
        }
        long responseKey = 0;
        int delay = 0;
        int numItems = 0;
        int itemSize = 0;
        String[] items = null;
        JsonToken current;

        while (parser.nextToken() != JsonToken.END_OBJECT) {
            String fieldName = parser.getCurrentName();
            // advance
            current = parser.nextToken();
            if (fieldName.equals("responseKey")) {
                responseKey = parser.getLongValue();
            } else if (fieldName.equals("delay")) {
                delay = parser.getIntValue();
            } else if (fieldName.equals("itemSize")) {
                itemSize = parser.getIntValue();
            } else if (fieldName.equals("numItems")) {
                numItems = parser.getIntValue();
            } else if (fieldName.equals("items")) {
                // expect numItems to be populated before hitting this
                if (numItems == 0) {
                    throw new IllegalStateException("Expected numItems > 0");
                }
                items = new String[numItems];
                if (current == JsonToken.START_ARRAY) {
                    int j = 0;
                    // For each of the records in the array
                    while (parser.nextToken() != JsonToken.END_ARRAY) {
                        items[j++] = parser.getText();
                    }
                } else {
                    //                            System.out.println("Error: items should be an array: skipping.");
                    parser.skipChildren();
                }

            }
        }
        return new BackendResponse(responseKey, delay, numItems, itemSize, items);
    } finally {
        parser.close();
    }
}
 
Example 13
Source File: BackendResponse.java    From WSPerfLab with Apache License 2.0 4 votes vote down vote up
public static BackendResponse parseBackendResponse(JsonParser parser) throws IOException {
    try {
        // Sanity check: verify that we got "Json Object":
        if (parser.nextToken() != JsonToken.START_OBJECT) {
            throw new IOException("Expected data to start with an Object");
        }
        long responseKey = 0;
        int delay = 0;
        int numItems = 0;
        int itemSize = 0;
        String[] items = null;
        JsonToken current;

        while (parser.nextToken() != JsonToken.END_OBJECT) {
            String fieldName = parser.getCurrentName();
            // advance
            current = parser.nextToken();
            if (fieldName.equals("responseKey")) {
                responseKey = parser.getLongValue();
            } else if (fieldName.equals("delay")) {
                delay = parser.getIntValue();
            } else if (fieldName.equals("itemSize")) {
                itemSize = parser.getIntValue();
            } else if (fieldName.equals("numItems")) {
                numItems = parser.getIntValue();
            } else if (fieldName.equals("items")) {
                // expect numItems to be populated before hitting this
                if (numItems == 0) {
                    throw new IllegalStateException("Expected numItems > 0");
                }
                items = new String[numItems];
                if (current == JsonToken.START_ARRAY) {
                    int j = 0;
                    // For each of the records in the array
                    while (parser.nextToken() != JsonToken.END_ARRAY) {
                        items[j++] = parser.getText();
                    }
                } else {
                    //                            System.out.println("Error: items should be an array: skipping.");
                    parser.skipChildren();
                }

            }
        }
        
        return new BackendResponse(responseKey, delay, numItems, itemSize, items);
    } finally {
        parser.close();
    }
}