Java Code Examples for org.codehaus.jackson.JsonParser#getCurrentName()

The following examples show how to use org.codehaus.jackson.JsonParser#getCurrentName() . 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 Project: hraven   File: ClientObjectMapper.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public CounterMap deserialize(JsonParser jsonParser,
                              DeserializationContext deserializationContext)
                              throws IOException {
  CounterMap counterMap = new CounterMap();

  JsonToken token;
  while ((token = jsonParser.nextToken()) != JsonToken.END_OBJECT) {
    assertToken(token, JsonToken.FIELD_NAME);
    String group = jsonParser.getCurrentName();

    assertToken(jsonParser.nextToken(), JsonToken.START_OBJECT);
    while ((token = jsonParser.nextToken()) != JsonToken.END_OBJECT) {
      if (token != JsonToken.VALUE_NUMBER_INT) {
        continue; // all deserialized values are ints
      }

      Counter counter =
          new Counter(group, jsonParser.getCurrentName(), jsonParser.getLongValue());
      counterMap.add(counter);
    }
  }
  return counterMap;
}
 
Example 2
public static boolean isValidJSON(String json) {
    boolean valid = false;
    try {
        final JsonParser parser = new ObjectMapper().getJsonFactory()
                .createJsonParser(json);
        while (parser.nextToken() != null) {
            String fieldname = parser.getCurrentName();
            System.out.println("fieldname: " + fieldname);
        }
        valid = true;
    } catch (JsonParseException jpe) {
        jpe.printStackTrace();
    } catch (IOException ioe) {
        ioe.printStackTrace();
    }

    return valid;
}
 
Example 3
public static boolean isEmptySON(String json) {
    boolean isEmpty = true;
    try {
        final JsonParser parser = new ObjectMapper().getJsonFactory()
                .createJsonParser(json);
        while (parser.nextToken() != null) {
            String fieldname = parser.getCurrentName();
            if(fieldname != null){
                isEmpty = false;
                break;
            }

        }

    } catch (JsonParseException jpe) {
        System.out.println("isEmptySON: " + jpe.getMessage());
        jpe.printStackTrace();
    } catch (IOException ioe) {
        System.out.println("isEmptySON: " + ioe.getMessage());
        ioe.printStackTrace();
    }

    return isEmpty;
}
 
Example 4
Source Project: io   File: BarFileReadRunner.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * フィールド名がファイルの形式に一致しているかの確認.
 * @param jp
 * @param jsonName
 * @throws IOException
 * @throws JsonParseException
 */
private void checkMatchFieldName(JsonParser jp, String jsonName) throws IOException {
    String fieldName = jp.getCurrentName();
    if (!(fieldName.equals("Relations") && jsonName.equals(RELATION_JSON))
            && !(fieldName.equals("Roles") && jsonName.equals(ROLE_JSON))
            && !(fieldName.equals("ExtRoles") && jsonName.equals(EXTROLE_JSON))
            && !(fieldName.equals("Links") && jsonName.equals(LINKS_JSON))
            && !(fieldName.equals("Links") && jsonName.equals(USERDATA_LINKS_JSON))) {
        throw DcCoreException.BarInstall.JSON_FILE_FORMAT_ERROR.params(jsonName);
    }
}
 
Example 5
Source Project: workcraft   File: PNetGenerationCommand.java    License: 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 6
Source Project: stratio-cassandra   File: SSTableImport.java    License: Apache License 2.0 4 votes vote down vote up
private int importSorted(String jsonFile, ColumnFamily columnFamily, String ssTablePath,
        IPartitioner partitioner) throws IOException
{
    int importedKeys = 0; // already imported keys count
    long start = System.nanoTime();

    JsonParser parser = getParser(jsonFile);

    if (keyCountToImport == null)
    {
        keyCountToImport = 0;
        System.out.println("Counting keys to import, please wait... (NOTE: to skip this use -n <num_keys>)");

        parser.nextToken(); // START_ARRAY
        while (parser.nextToken() != null)
        {
            parser.skipChildren();
            if (parser.getCurrentToken() == JsonToken.END_ARRAY)
                break;

            keyCountToImport++;
        }
    }

    System.out.printf("Importing %s keys...%n", keyCountToImport);

    parser = getParser(jsonFile); // renewing parser
    SSTableWriter writer = new SSTableWriter(ssTablePath, keyCountToImport, ActiveRepairService.UNREPAIRED_SSTABLE);

    int lineNumber = 1;
    DecoratedKey prevStoredKey = null;

    parser.nextToken(); // START_ARRAY
    while (parser.nextToken() != null)
    {
        String key = parser.getCurrentName();
        Map<?, ?> row = parser.readValueAs(new TypeReference<Map<?, ?>>(){});
        DecoratedKey currentKey = partitioner.decorateKey(getKeyValidator(columnFamily).fromString((String) row.get("key")));

        if (row.containsKey("metadata"))
            parseMeta((Map<?, ?>) row.get("metadata"), columnFamily, null);

        addColumnsToCF((List<?>) row.get("cells"), columnFamily);

        if (prevStoredKey != null && prevStoredKey.compareTo(currentKey) != -1)
        {
            System.err
                    .printf("Line %d: Key %s is greater than previous, collection is not sorted properly. Aborting import. You might need to delete SSTables manually.%n",
                            lineNumber, key);
            return -1;
        }

        // saving decorated key
        writer.append(currentKey, columnFamily);
        columnFamily.clear();

        prevStoredKey = currentKey;
        importedKeys++;
        lineNumber++;

        long current = System.nanoTime();

        if (TimeUnit.NANOSECONDS.toSeconds(current - start) >= 5) // 5 secs.
        {
            System.out.printf("Currently imported %d keys.%n", importedKeys);
            start = current;
        }

        if (keyCountToImport == importedKeys)
            break;

    }

    writer.closeAndOpenReader();

    return importedKeys;
}
 
Example 7
Source Project: ReactiveLab   File: BackendResponse.java    License: 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 8
Source Project: usergrid   File: ImportAdmins.java    License: Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
private void importMetadata(String fileName, int writeThreads) throws Exception {

    EntityManager em = emf.getEntityManager( CpNamingUtils.MANAGEMENT_APPLICATION_ID);

    File metadataFile = new File(importDir, fileName);

    logger.info("----- Loading metadata file: " + metadataFile.getAbsolutePath());

    JsonParser jp = getJsonParserForFile(metadataFile);

    JsonToken jsonToken = null; // jp.nextToken();// START_OBJECT this is the outer hashmap

    int depth = 1;

    BlockingQueue<ImportMetadataTask> workQueue = new LinkedBlockingQueue<ImportMetadataTask>();
    startMetadataWorkers(workQueue, writeThreads);

    while (depth > 0) {

        jsonToken = jp.nextToken();

        if (jsonToken == null) {
            logger.info("token is null, breaking");
            break;
        }

        if (jsonToken.equals(JsonToken.START_OBJECT)) {
            depth++;
        } else if (jsonToken.equals(JsonToken.END_OBJECT)) {
            depth--;
        }

        if (jsonToken.equals(JsonToken.FIELD_NAME) && depth == 2) {

            jp.nextToken();
            String entityOwnerId = jp.getCurrentName();

            try {
                EntityRef entityRef = new SimpleEntityRef( "user", UUID.fromString( entityOwnerId ) );
                Map<String, Object> metadata = (Map<String, Object>) jp.readValueAs( Map.class );

                workQueue.put( new ImportMetadataTask( entityRef, metadata ) );
                logger.debug( "Put user {} in metadata queue", entityRef.getUuid() );

            } catch ( Exception e ) {
                logger.debug( "Error with user {}, not putting in metadata queue", entityOwnerId );
            }
        }
    }

    waitForQueueAndMeasure(workQueue, metadataEmptyCount, metadataWorkerThreadMap, "Metadata Load");

    logger.info("----- End of metadata -----");
    jp.close();
}
 
Example 9
Source Project: WSPerfLab   File: BackendResponse.java    License: 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();
    }
}