Example usage for com.fasterxml.jackson.core JsonParser getCurrentName

List of usage examples for com.fasterxml.jackson.core JsonParser getCurrentName

Introduction

In this page you can find the example usage for com.fasterxml.jackson.core JsonParser getCurrentName.

Prototype

public abstract String getCurrentName() throws IOException, JsonParseException;

Source Link

Document

Method that can be called to get the name associated with the current token: for JsonToken#FIELD_NAME s it will be the same as what #getText returns; for field values it will be preceding field name; and for others (array values, root-level values) null.

Usage

From source file:net.troja.eve.crest.CrestDataProcessor.java

private <T> String processData(final CrestApiProcessor<T> processor, final CrestContainer<T> container,
        final String data) {
    String next = null;//from   w w w. j a  va  2s .  c o m
    try {
        final JsonFactory parserFactory = new JsonFactory();
        final JsonParser jsonParser = parserFactory.createParser(data);
        jsonParser.nextToken();
        while (jsonParser.nextToken() != JsonToken.END_OBJECT) {
            final String fieldname = jsonParser.getCurrentName();
            jsonParser.nextToken();
            switch (fieldname) {
            case "totalCount":
                container.setTotalCount(jsonParser.getIntValue());
                break;
            case "pageCount":
                container.setPageCount(jsonParser.getIntValue());
                break;
            case "items":
                processItems(processor, container, jsonParser);
                break;
            case "next":
                next = processNext(jsonParser);
                break;
            default:
                break;
            }
        }
    } catch (final IOException e) {
        if (LOGGER.isWarnEnabled()) {
            LOGGER.warn("Problems while parsing json data: " + e.getMessage(), e);
        }
    }
    return next;
}

From source file:com.cedarsoft.serialization.test.performance.JacksonTest.java

@Test
public void testParse() throws Exception {
    JsonParser parser = jsonFactory.createJsonParser(JSON);

    assertEquals(JsonToken.START_OBJECT, parser.nextToken());

    assertEquals(JsonToken.FIELD_NAME, parser.nextToken());
    assertEquals("id", parser.getCurrentName());
    assertEquals(JsonToken.VALUE_STRING, parser.nextToken());
    assertEquals("Canon Raw", parser.getText());

    assertEquals(JsonToken.FIELD_NAME, parser.nextToken());
    assertEquals("dependent", parser.getCurrentName());
    assertEquals(JsonToken.VALUE_FALSE, parser.nextToken());
    assertFalse(parser.getBooleanValue());

    assertEquals(JsonToken.FIELD_NAME, parser.nextToken());
    assertEquals("extension", parser.getCurrentName());
    assertEquals(JsonToken.START_OBJECT, parser.nextToken());

    assertEquals(JsonToken.FIELD_NAME, parser.nextToken());
    assertEquals("extension", parser.getCurrentName());
    assertEquals(JsonToken.VALUE_STRING, parser.nextToken());
    assertEquals("cr2", parser.getText());

    assertEquals(JsonToken.FIELD_NAME, parser.nextToken());
    assertEquals("default", parser.getCurrentName());
    assertEquals(JsonToken.VALUE_TRUE, parser.nextToken());
    assertTrue(parser.getBooleanValue());

    assertEquals(JsonToken.FIELD_NAME, parser.nextToken());
    assertEquals("delimiter", parser.getCurrentName());
    assertEquals(JsonToken.VALUE_STRING, parser.nextToken());
    assertEquals(".", parser.getText());

    assertEquals(JsonToken.END_OBJECT, parser.nextToken());
    assertEquals(JsonToken.END_OBJECT, parser.nextToken());
    assertNull(parser.nextToken());//from  www .  j  a va  2 s  . c o  m
}

From source file:uk.ac.manchester.cs.owl.semspreadsheets.repository.bioportal.BioPortalRepositoryAccessor.java

public String fetchOntologyFormat(String ontologyAcronym) {
    logger.debug("Fetching format for " + ontologyAcronym);
    BioPortalCache cache = BioPortalCache.getInstance();
    String format = cache.getFormat(ontologyAcronym);
    if (format != null) {
        if (logger.isDebugEnabled()) {
            logger.debug("The ontology format for " + ontologyAcronym + " was found in the cache as " + format);
        }//from  ww w.j av a2 s. c o m
    } else {
        logger.info("The format for " + ontologyAcronym + " not found in cache, fetching");
        try {
            URL url = new URL(BioPortalRepository.ONTOLOGY_LIST + "/" + ontologyAcronym + "/"
                    + BioPortalRepository.LATEST_SUBMISSION + "?format=json&apikey="
                    + BioPortalRepository.readAPIKey());
            logger.info("About to fetch more ontology information from " + url.toExternalForm());
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setConnectTimeout(CONNECT_TIMEOUT);
            connection.setReadTimeout(CONNECT_TIMEOUT);
            int responseCode = connection.getResponseCode();
            logger.info("BioPortal http response: " + responseCode);

            if (responseCode == 400 || responseCode == 403) {
                throw new BioPortalAccessDeniedException();
            }

            JsonParser parser = new JsonFactory().createParser(connection.getInputStream());
            while (format == null && parser.nextToken() != null) {
                String name = parser.getCurrentName();
                if ("hasOntologyLanguage".equals(name)) {
                    parser.nextToken();
                    format = parser.getText();
                }
            }
            if (format == null) {
                format = "unknown";
            }
            cache.storeFormat(ontologyAcronym, format);
        } catch (UnknownHostException e) {
            ErrorHandler.getErrorHandler().handleError(e);
        } catch (MalformedURLException e) {
            logger.error("Error with URL for BioPortal rest API", e);
        } catch (SocketTimeoutException e) {
            logger.error("Timeout connecting to BioPortal", e);
            ErrorHandler.getErrorHandler().handleError(e);
        } catch (IOException e) {
            logger.error("Error communiciating with BioPortal rest API", e);
        } catch (BioPortalAccessDeniedException e) {
            ErrorHandler.getErrorHandler().handleError(e);
        }
    }

    return format;
}

From source file:org.emfjson.jackson.databind.deser.EcoreReferenceDeserializer.java

@Override
public ReferenceEntry deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
    EObject parent = EMFContext.getParent(ctxt);
    EReference reference = EMFContext.getReference(ctxt);

    String id = null;//from w  w  w  . ja  va 2  s  . com
    String type = null;

    while (jp.nextToken() != JsonToken.END_OBJECT) {
        final String field = jp.getCurrentName();

        if (field.equalsIgnoreCase(info.getProperty())) {
            id = jp.nextTextValue();
        } else if (field.equalsIgnoreCase(info.getTypeProperty())) {
            type = jp.nextTextValue();
        }
    }

    return id != null ? new ReferenceEntry.Base(parent, reference, id, type) : null;
}

From source file:com.ntsync.shared.RawContact.java

/**
 * Creates and returns an instance of the RawContact from encrypted data
 * //from  w w  w.  ja  va2s .c  o  m
 * */
public static RawContact valueOf(String rowId, Map<Byte, ByteBuffer> values, Key privateKey)
        throws InvalidKeyException {
    try {
        String serverContactId = null;
        long rawContactId = -1;
        if (values.containsKey(ContactConstants.SERVERROW_ID)) {
            serverContactId = readRawString(values.get(ContactConstants.SERVERROW_ID));
        }
        String lastModStr = readRawString(values.get(ContactConstants.MODIFIED));
        Date lastModified = null;
        if (lastModStr != null) {
            lastModified = new Date(Long.parseLong(lastModStr));
        }

        if (serverContactId == null || !serverContactId.equals(rowId)) {
            // If ServerContactId is different, then rowId is the clientId
            rawContactId = Long.parseLong(rowId);
        }

        if (serverContactId == null && rawContactId < 0) {
            throw new IllegalArgumentException("Missing RowId in data");
        }

        AEADBlockCipher cipher = CryptoHelper.getCipher();
        final boolean deleted = values.containsKey(ContactConstants.DELETED);

        final String textData = CryptoHelper.decodeStringValue(ContactConstants.TEXTDATA, values, cipher,
                privateKey);

        if (textData == null && !deleted) {
            LOG.error("No textdata found for row with Id:" + rowId);
            return null;
        }

        String fullName = null;
        String firstName = null;
        String lastName = null;
        String middleName = null;
        String prefixName = null;
        String suffixName = null;
        String phonecticFirst = null;
        String phonecticMiddle = null;
        String phonecticLast = null;
        List<String> groupSourceIds = null;
        String note = null;
        List<ListRawData<PhoneType>> phones = null;
        List<ListRawData<EmailType>> emails = null;
        List<ListRawData<WebsiteType>> websites = null;
        List<ListRawData<EventType>> events = null;
        List<ListRawData<RelationType>> relations = null;
        List<ListRawData<SipAddressType>> sipaddresses = null;
        List<ListRawData<NicknameType>> nicknames = null;
        List<RawAddressData> addresses = null;
        List<RawImData> imAddresses = null;
        RawOrganizationData organization = null;
        boolean photoSuperPrimary = false;
        boolean starred = false;
        String customRingtone = null;
        boolean sendToVoiceMail = false;

        if (!SyncDataHelper.isEmpty(textData)) {
            JsonFactory fac = new JsonFactory();
            JsonParser jp = fac.createParser(textData);
            jp.nextToken();
            while (jp.nextToken() != JsonToken.END_OBJECT) {
                String fieldname = jp.getCurrentName();
                // move to value, or START_OBJECT/START_ARRAY
                jp.nextToken();
                if (ContactConstants.STRUCTUREDNAME.equals(fieldname)) {
                    while (jp.nextToken() != JsonToken.END_OBJECT) {
                        String namefield = jp.getCurrentName();
                        // move to value
                        if (jp.nextToken() == null) {
                            throw new JsonParseException("Invalid JSON-Structure. End of Object missing.",
                                    jp.getCurrentLocation());
                        }
                        if (ContactConstants.DISPLAY_NAME.equals(namefield)) {
                            fullName = jp.getValueAsString();
                        } else if (ContactConstants.FAMILY_NAME.equals(namefield)) {
                            lastName = jp.getValueAsString();
                        } else if (ContactConstants.GIVEN_NAME.equals(namefield)) {
                            firstName = jp.getValueAsString();
                        } else if (ContactConstants.MIDDLE_NAME.equals(namefield)) {
                            middleName = jp.getValueAsString();
                        } else if (ContactConstants.SUFFIX_NAME.equals(namefield)) {
                            suffixName = jp.getValueAsString();
                        } else if (ContactConstants.PREFIX_NAME.equals(namefield)) {
                            prefixName = jp.getValueAsString();
                        } else if (ContactConstants.PHONETIC_FAMILY.equals(namefield)) {
                            phonecticLast = jp.getValueAsString();
                        } else if (ContactConstants.PHONETIC_GIVEN.equals(namefield)) {
                            phonecticFirst = jp.getValueAsString();
                        } else if (ContactConstants.PHONETIC_MIDDLE.equals(namefield)) {
                            phonecticMiddle = jp.getValueAsString();
                        } else {
                            LOG.error("Unrecognized structurednamefield for row with Id:" + rowId
                                    + " Fieldname:" + fieldname);
                            break;
                        }
                    }
                } else if (ContactConstants.STRUCTUREDPOSTAL.equals(fieldname)) {
                    addresses = readAddressList(rowId, addresses, jp);
                } else if (ContactConstants.PHONE.equals(fieldname)) {
                    phones = readJsonList(rowId, phones, jp, fieldname, PhoneType.TYPE_OTHER, PhoneType.class);
                } else if (ContactConstants.EMAIL.equals(fieldname)) {
                    emails = readJsonList(rowId, emails, jp, fieldname, EmailType.TYPE_OTHER, EmailType.class);
                } else if (ContactConstants.WEBSITE.equals(fieldname)) {
                    websites = readJsonList(rowId, websites, jp, fieldname, WebsiteType.TYPE_OTHER,
                            WebsiteType.class);
                } else if (ContactConstants.EVENT.equals(fieldname)) {
                    events = readJsonList(rowId, events, jp, fieldname, EventType.TYPE_OTHER, EventType.class);
                } else if (ContactConstants.RELATION.equals(fieldname)) {
                    relations = readJsonList(rowId, relations, jp, fieldname, RelationType.TYPE_CUSTOM,
                            RelationType.class);
                } else if (ContactConstants.SIPADDRESS.equals(fieldname)) {
                    sipaddresses = readJsonList(rowId, sipaddresses, jp, fieldname, SipAddressType.TYPE_OTHER,
                            SipAddressType.class);
                } else if (ContactConstants.NICKNAME.equals(fieldname)) {
                    nicknames = readJsonList(rowId, nicknames, jp, fieldname, NicknameType.TYPE_DEFAULT,
                            NicknameType.class);
                } else if (ContactConstants.IM.equals(fieldname)) {
                    imAddresses = readImList(rowId, imAddresses, jp);
                } else if (ContactConstants.NOTE.equals(fieldname)) {
                    note = jp.getValueAsString();
                } else if (ContactConstants.GROUPMEMBERSHIP.equals(fieldname)) {
                    while (jp.nextToken() != JsonToken.END_ARRAY) {
                        String groupSourceId = jp.getValueAsString();
                        if (groupSourceIds == null) {
                            groupSourceIds = new ArrayList<String>();
                        }
                        groupSourceIds.add(groupSourceId);
                    }
                } else if (ContactConstants.ORGANIZATION.equals(fieldname)) {
                    organization = readOrg(rowId, jp);
                } else if (ContactConstants.PHOTO_SUPERPRIMARY.equals(fieldname)) {
                    photoSuperPrimary = jp.getValueAsBoolean();
                } else if (ContactConstants.STARRED.equals(fieldname)) {
                    starred = jp.getValueAsBoolean();
                } else if (ContactConstants.SEND_TO_VOICE_MAIL.equals(fieldname)) {
                    sendToVoiceMail = jp.getValueAsBoolean();
                } else if (ContactConstants.DROID_CUSTOM_RINGTONE.equals(fieldname)) {
                    customRingtone = jp.getValueAsString();
                } else {
                    LOG.error("Unrecognized field for row with Id:" + rowId + " Fieldname:" + fieldname);
                }
            }
            jp.close();
        }

        final byte[] photo = CryptoHelper.decodeValue(ContactConstants.PHOTO, values, cipher, privateKey);

        return new RawContact(fullName, firstName, lastName, middleName, prefixName, suffixName, phonecticFirst,
                phonecticMiddle, phonecticLast, phones, emails, websites, addresses, events, relations,
                sipaddresses, nicknames, imAddresses, note, organization, photo, photoSuperPrimary,
                groupSourceIds, null, starred, customRingtone, sendToVoiceMail, lastModified, deleted,
                serverContactId, rawContactId, false, -1);
    } catch (InvalidCipherTextException ex) {
        throw new InvalidKeyException("Invalid key detected.", ex);
    } catch (final IOException ex) {
        LOG.info("Error parsing contact data. Reason:" + ex.toString(), ex);
    } catch (IllegalArgumentException ex) {
        LOG.warn("Error parsing contact data. Reason:" + ex.toString(), ex);
    }

    return null;
}

From source file:org.helm.notation2.wsadapter.MonomerWSSaver.java

/**
 * Adds or updates a single monomer to the monomer store using the URL configured in {@code MonomerStoreConfiguration}
 * ./*from  w  w w  .  ja v  a 2  s .c o  m*/
 * 
 * @param monomer to save
 */
public String saveMonomerToStore(Monomer monomer) {
    String res = "";
    CloseableHttpResponse response = null;

    try {
        response = WSAdapterUtils.putResource(monomer.toJSON(),
                MonomerStoreConfiguration.getInstance().getWebserviceNucleotidesPutFullURL());
        LOG.debug(response.getStatusLine().toString());

        JsonFactory jsonf = new JsonFactory();
        InputStream instream = response.getEntity().getContent();

        JsonParser jsonParser = jsonf.createParser(instream);

        while (!jsonParser.isClosed()) {
            JsonToken jsonToken = jsonParser.nextToken();
            if (JsonToken.FIELD_NAME.equals(jsonToken)) {
                String fieldName = jsonParser.getCurrentName();
                LOG.debug("Field name: " + fieldName);
                jsonParser.nextToken();
                if (fieldName.equals("monomerShortName")) {
                    res = jsonParser.getValueAsString();
                    break;
                }
            }
        }

        EntityUtils.consume(response.getEntity());

    } catch (Exception e) {
        LOG.error("Saving monomer failed!", e);
        return "";
    } finally {
        try {
            if (response != null) {
                response.close();
            }
        } catch (IOException e) {
            LOG.debug("Closing resources failed.", e);
            return res;
        }
    }

    return res;
}

From source file:net.openhft.chronicle.wire.benchmarks.Data.java

public void readFrom(JsonParser parser) throws IOException {
    parser.nextToken();/*from   w  w  w . j a  va 2 s  . c  o m*/
    while (parser.nextToken() != JsonToken.END_OBJECT) {
        String fieldname = parser.getCurrentName();
        parser.nextToken();
        switch (fieldname) {
        case "price":
            setPrice(parser.getDoubleValue());
            break;
        case "flag":
            flag = parser.getBooleanValue();
            break;
        case "text":
            setText(parser.getValueAsString());
            break;
        case "side":
            side = Side.valueOf(parser.getValueAsString());
            break;
        case "smallInt":
            smallInt = parser.getIntValue();
            break;
        case "longInt":
            longInt = parser.getLongValue();
            break;
        }
    }
}

From source file:com.basho.riak.client.raw.http.NamedJSFunctionDeserializer.java

@Override
public NamedJSFunction deserialize(JsonParser jp, DeserializationContext ctxt)
        throws IOException, JsonProcessingException {

    JsonToken token = jp.getCurrentToken();

    if (JsonToken.START_OBJECT.equals(token)) {

        String name = null;//from  w  ww  .j a v  a2 s  .c  o m

        while (!JsonToken.END_OBJECT.equals(token)) {
            String field = jp.getCurrentName();

            if (Constants.FL_SCHEMA_FUN_NAME.equals(field)) {
                jp.nextToken();
                name = jp.getText();
            }
            token = jp.nextToken();
        }
        if (name != null) {
            return new NamedJSFunction(name);
        } else {
            return null;
        }
    }
    throw ctxt.mappingException(NamedJSFunction.class);
}

From source file:com.msopentech.odatajclient.engine.metadata.edm.v4.annotation.DynExprConstructDeserializer.java

@Override
protected DynExprConstruct doDeserialize(final JsonParser jp, final DeserializationContext ctxt)
        throws IOException, JsonProcessingException {

    DynExprConstruct construct = null;/*  w w  w . ja v  a 2s.c o m*/

    if (DynExprSingleParamOp.Type.fromString(jp.getCurrentName()) != null) {
        final DynExprSingleParamOp dynExprSingleParamOp = new DynExprSingleParamOp();
        dynExprSingleParamOp.setType(DynExprSingleParamOp.Type.fromString(jp.getCurrentName()));

        jp.nextToken();
        jp.nextToken();
        dynExprSingleParamOp.setExpression(jp.getCodec().readValue(jp, DynExprConstruct.class));

        construct = dynExprSingleParamOp;
    } else if (DynExprDoubleParamOp.Type.fromString(jp.getCurrentName()) != null) {
        final DynExprDoubleParamOp dynExprDoubleParamOp = new DynExprDoubleParamOp();
        dynExprDoubleParamOp.setType(DynExprDoubleParamOp.Type.fromString(jp.getCurrentName()));

        jp.nextToken();
        jp.nextToken();
        dynExprDoubleParamOp.setLeft(jp.getCodec().readValue(jp, DynExprConstruct.class));
        dynExprDoubleParamOp.setRight(jp.getCodec().readValue(jp, DynExprConstruct.class));

        construct = dynExprDoubleParamOp;
    } else if (ArrayUtils.contains(EL_OR_ATTR, jp.getCurrentName())) {
        final AbstractElOrAttrConstruct elOrAttr = getElOrAttrInstance(jp.getCurrentName());
        elOrAttr.setValue(jp.nextTextValue());

        construct = elOrAttr;
    } else if (APPLY.equals(jp.getCurrentName())) {
        jp.nextToken();
        construct = jp.getCodec().readValue(jp, Apply.class);
    } else if (CAST.equals(jp.getCurrentName())) {
        jp.nextToken();
        construct = jp.getCodec().readValue(jp, Cast.class);
    } else if (COLLECTION.equals(jp.getCurrentName())) {
        jp.nextToken();
        construct = jp.getCodec().readValue(jp, Collection.class);
    } else if (IF.equals(jp.getCurrentName())) {
        jp.nextToken();
        jp.nextToken();

        final If _if = new If();
        _if.setGuard(parseConstOrEnumExprConstruct(jp));
        _if.setThen(parseConstOrEnumExprConstruct(jp));
        _if.setElse(parseConstOrEnumExprConstruct(jp));

        construct = _if;
    } else if (IS_OF.equals(jp.getCurrentName())) {
        jp.nextToken();
        construct = jp.getCodec().readValue(jp, IsOf.class);
    } else if (LABELED_ELEMENT.equals(jp.getCurrentName())) {
        jp.nextToken();
        construct = jp.getCodec().readValue(jp, LabeledElement.class);
    } else if (NULL.equals(jp.getCurrentName())) {
        jp.nextToken();
        construct = jp.getCodec().readValue(jp, Null.class);
    } else if (RECORD.equals(jp.getCurrentName())) {
        jp.nextToken();
        construct = jp.getCodec().readValue(jp, Record.class);
    } else if (URL_REF.equals(jp.getCurrentName())) {
        jp.nextToken();
        construct = jp.getCodec().readValue(jp, UrlRef.class);
    }

    return construct;
}

From source file:org.example.testcases.BasicTypesDeSerializer.java

private BasicTypes readObject(JsonParser jp) throws IOException {
    BasicTypes basicTypes = new BasicTypes();
    for (JsonToken jsonToken; (jsonToken = jp.nextToken()) != null && (jsonToken != END_OBJECT);) {
        if (FIELD_NAME != jsonToken)
            continue;
        final String fieldName = jp.getCurrentName();
        switch (fieldName) {
        case "aString":
            jsonToken = jp.nextToken(); // read value
            basicTypes.aString = jp.getText();
            break;
        case "aBoolean":
            jsonToken = jp.nextToken(); // read value
            basicTypes.aBoolean = jp.getBooleanValue();
            break;
        case "aFloat":
            jsonToken = jp.nextToken(); // read value
            basicTypes.aFloat = jp.getFloatValue();
            break;
        case "aDouble":
            jsonToken = jp.nextToken(); // read value
            basicTypes.aDouble = jp.getDoubleValue();
            break;
        case "aInt":
            jsonToken = jp.nextToken(); // read value
            basicTypes.aInt = jp.getIntValue();
            break;
        case "aShort":
            jsonToken = jp.nextToken(); // read value
            basicTypes.aShort = jp.getShortValue();
            break;
        case "aByte":
            jsonToken = jp.nextToken(); // read value
            basicTypes.aByte = jp.getByteValue();
            break;
        default:/*from  w ww.  j a  va  2  s .c o  m*/
            // decide what to do;
        }
    }
    return basicTypes;
}