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

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

Introduction

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

Prototype

public abstract JsonLocation getCurrentLocation();

Source Link

Document

Method that returns location of the last processed character; usually for error reporting purposes.

Usage

From source file:com.reprezen.swagedit.model.NodeDeserializer.java

protected ValueNode deserializeValueNode(JsonParser p, DeserializationContext context,
        JsonLocation startLocation) throws IOException {
    final Model model = (Model) context.getAttribute(ATTRIBUTE_MODEL);
    final AbstractNode parent = (AbstractNode) context.getAttribute(ATTRIBUTE_PARENT);
    final JsonPointer ptr = (JsonPointer) context.getAttribute(ATTRIBUTE_POINTER);

    Object v = context.readValue(p, Object.class);

    ValueNode node = model.valueNode(parent, ptr, v);
    node.setStartLocation(createLocation(startLocation));
    node.setEndLocation(createLocation(p.getCurrentLocation()));

    return node;/*from   w ww . j  a  va  2 s. c om*/
}

From source file:com.netflix.discovery.converters.jackson.serializer.ApplicationXmlDeserializer.java

@Override
public Application deserialize(JsonParser jp, DeserializationContext ctxt)
        throws IOException, JsonProcessingException {
    String name = null;/*from w  w w. j  a va  2 s  .  c  o m*/
    List<InstanceInfo> instances = new ArrayList<>();
    while (jp.nextToken() == JsonToken.FIELD_NAME) {
        String fieldName = jp.getCurrentName();
        jp.nextToken(); // to point to value
        if ("name".equals(fieldName)) {
            name = jp.getValueAsString();
        } else if ("instance".equals(fieldName)) {
            instances.add(jp.readValueAs(InstanceInfo.class));
        } else {
            throw new JsonMappingException("Unexpected field " + fieldName, jp.getCurrentLocation());
        }
    }
    return new Application(name, instances);
}

From source file:com.netflix.discovery.converters.jackson.serializer.PortWrapperXmlDeserializer.java

@Override
public InstanceInfo.PortWrapper deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
    boolean enabled = false;
    int port = 0;
    while (jp.nextToken() == JsonToken.FIELD_NAME) {
        String fieldName = jp.getCurrentName();
        jp.nextToken(); // to point to value
        if ("enabled".equals(fieldName)) {
            enabled = Boolean.valueOf(jp.getValueAsString());
        } else if (fieldName == null || "".equals(fieldName)) {
            String value = jp.getValueAsString();
            port = value == null ? 0 : Integer.parseInt(value);
        } else {//from w  ww.j  ava 2 s  .  co  m
            throw new JsonMappingException("Unexpected field " + fieldName, jp.getCurrentLocation());
        }
    }
    return new InstanceInfo.PortWrapper(enabled, port);
}

From source file:com.msopentech.odatajclient.engine.data.json.JSONEntryDeserializer.java

/**
 * {@inheritDoc }/*from ww  w  .j  a va 2 s.  c om*/
 */
@Override
public JSONEntry deserialize(final JsonParser parser, final DeserializationContext ctxt)
        throws IOException, JsonProcessingException {

    final ObjectNode tree = (ObjectNode) parser.getCodec().readTree(parser);

    if (tree.has(ODataConstants.JSON_VALUE) && tree.get(ODataConstants.JSON_VALUE).isArray()) {
        throw new JsonParseException("Expected OData Entity, found EntitySet", parser.getCurrentLocation());
    }

    final boolean isMediaEntry = tree.hasNonNull(ODataConstants.JSON_MEDIAREAD_LINK)
            && tree.hasNonNull(ODataConstants.JSON_MEDIA_CONTENT_TYPE);

    final JSONEntry entry = new JSONEntry();

    if (tree.hasNonNull(ODataConstants.JSON_METADATA)) {
        entry.setMetadata(URI.create(tree.get(ODataConstants.JSON_METADATA).textValue()));
        tree.remove(ODataConstants.JSON_METADATA);
    }

    if (tree.hasNonNull(ODataConstants.JSON_MEDIA_ETAG)) {
        entry.setMediaETag(tree.get(ODataConstants.JSON_MEDIA_ETAG).textValue());
        tree.remove(ODataConstants.JSON_MEDIA_ETAG);
    }

    if (tree.hasNonNull(ODataConstants.JSON_ETAG)) {
        entry.setETag(tree.get(ODataConstants.JSON_ETAG).textValue());
        tree.remove(ODataConstants.JSON_ETAG);
    }

    if (tree.hasNonNull(ODataConstants.JSON_TYPE)) {
        entry.setType(tree.get(ODataConstants.JSON_TYPE).textValue());
        tree.remove(ODataConstants.JSON_TYPE);
    }

    if (tree.hasNonNull(ODataConstants.JSON_ID)) {
        entry.setId(tree.get(ODataConstants.JSON_ID).textValue());
        tree.remove(ODataConstants.JSON_ID);
    }

    if (tree.hasNonNull(ODataConstants.JSON_READ_LINK)) {
        final JSONLink link = new JSONLink();
        link.setRel(ODataConstants.SELF_LINK_REL);
        link.setHref(tree.get(ODataConstants.JSON_READ_LINK).textValue());
        entry.setSelfLink(link);

        tree.remove(ODataConstants.JSON_READ_LINK);
    }

    if (tree.hasNonNull(ODataConstants.JSON_EDIT_LINK)) {
        final JSONLink link = new JSONLink();
        link.setRel(ODataConstants.EDIT_LINK_REL);
        link.setHref(tree.get(ODataConstants.JSON_EDIT_LINK).textValue());
        entry.setEditLink(link);

        tree.remove(ODataConstants.JSON_EDIT_LINK);
    }

    if (tree.hasNonNull(ODataConstants.JSON_MEDIAREAD_LINK)) {
        entry.setMediaContentSource(tree.get(ODataConstants.JSON_MEDIAREAD_LINK).textValue());
        tree.remove(ODataConstants.JSON_MEDIAREAD_LINK);
    }
    if (tree.hasNonNull(ODataConstants.JSON_MEDIAEDIT_LINK)) {
        final JSONLink link = new JSONLink();
        link.setHref(tree.get(ODataConstants.JSON_MEDIAEDIT_LINK).textValue());
        entry.addMediaEditLink(link);

        tree.remove(ODataConstants.JSON_MEDIAEDIT_LINK);
    }
    if (tree.hasNonNull(ODataConstants.JSON_MEDIA_CONTENT_TYPE)) {
        entry.setMediaContentType(tree.get(ODataConstants.JSON_MEDIA_CONTENT_TYPE).textValue());
        tree.remove(ODataConstants.JSON_MEDIA_CONTENT_TYPE);
    }

    final Set<String> toRemove = new HashSet<String>();
    final Iterator<Map.Entry<String, JsonNode>> itor = tree.fields();
    while (itor.hasNext()) {
        final Map.Entry<String, JsonNode> field = itor.next();

        if (field.getKey().endsWith(ODataConstants.JSON_NAVIGATION_LINK_SUFFIX)
                || field.getKey().endsWith(ODataConstants.JSON_NAVIGATION_LINK_ODATA_4_SUFFIX)) {
            final JSONLink link = new JSONLink();
            link.setTitle(getTitle(field));
            link.setRel(ODataConstants.NAVIGATION_LINK_REL + getTitle(field));
            if (field.getValue().isValueNode()) {
                link.setHref(field.getValue().textValue());
                link.setType(ODataLinkType.ENTITY_NAVIGATION.toString());
            }
            // NOTE: this should be expected to happen, but it isn't - at least up to OData 4.0
            /* if (field.getValue().isArray()) {
             * link.setHref(field.getValue().asText());
             * link.setType(ODataLinkType.ENTITY_SET_NAVIGATION.toString());
             * } */
            entry.addNavigationLink(link);

            toRemove.add(field.getKey());
            toRemove.add(setInline(field.getKey(),
                    field.getKey().endsWith(ODataConstants.JSON_NAVIGATION_LINK_SUFFIX)
                            ? ODataConstants.JSON_NAVIGATION_LINK_SUFFIX
                            : ODataConstants.JSON_NAVIGATION_LINK_ODATA_4_SUFFIX,
                    tree, parser.getCodec(), link));
        } else if (field.getKey().endsWith(ODataConstants.JSON_ASSOCIATION_LINK_SUFFIX)) {
            final JSONLink link = new JSONLink();
            link.setTitle(getTitle(field));
            link.setRel(ODataConstants.ASSOCIATION_LINK_REL + getTitle(field));
            link.setHref(field.getValue().textValue());
            link.setType(ODataLinkType.ASSOCIATION.toString());
            entry.addAssociationLink(link);

            toRemove.add(field.getKey());
        } else if (field.getKey().endsWith(ODataConstants.JSON_MEDIAEDIT_LINK_SUFFIX)) {
            final JSONLink link = new JSONLink();
            link.setTitle(getTitle(field));
            link.setRel(ODataConstants.MEDIA_EDIT_LINK_REL + getTitle(field));
            link.setHref(field.getValue().textValue());
            link.setType(ODataLinkType.MEDIA_EDIT.toString());
            entry.addMediaEditLink(link);

            toRemove.add(field.getKey());
            toRemove.add(setInline(field.getKey(), ODataConstants.JSON_MEDIAEDIT_LINK_SUFFIX, tree,
                    parser.getCodec(), link));
        } else if (field.getKey().charAt(0) == '#') {
            final ODataOperation operation = new ODataOperation();
            operation.setMetadataAnchor(field.getKey());

            final ObjectNode opNode = (ObjectNode) tree.get(field.getKey());
            operation.setTitle(opNode.get(ODataConstants.ATTR_TITLE).asText());
            operation.setTarget(URI.create(opNode.get(ODataConstants.ATTR_TARGET).asText()));

            entry.addOperation(operation);

            toRemove.add(field.getKey());
        }
    }
    tree.remove(toRemove);

    try {
        final DocumentBuilder builder = ODataConstants.DOC_BUILDER_FACTORY.newDocumentBuilder();
        final Document document = builder.newDocument();

        final Element properties = document.createElementNS(ODataConstants.NS_METADATA,
                ODataConstants.ELEM_PROPERTIES);

        DOMTreeUtils.buildSubtree(properties, tree);

        if (isMediaEntry) {
            entry.setMediaEntryProperties(properties);
        } else {
            entry.setContent(properties);
        }
    } catch (ParserConfigurationException e) {
        throw new JsonParseException("Cannot build entry content", parser.getCurrentLocation(), e);
    }

    return entry;
}

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

@SuppressWarnings({ "unchecked", "rawtypes" })
private static <T extends ListType> List<ListRawData<T>> readJsonList(String rowId,
        List<ListRawData<T>> listData, JsonParser jp, String fieldname, ListType defaultType,
        Class<T> typeClass) throws IOException {
    List<ListRawData<T>> newListData = listData;
    while (jp.nextToken() != JsonToken.END_ARRAY) {
        String number = null;//  ww  w . j ava2s  .  c om
        ListType type = defaultType;
        String label = null;
        boolean isSuperPrimary = false;
        boolean isPrimary = false;
        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 Array missing.",
                        jp.getCurrentLocation());
            }
            if (ContactConstants.DATA.equals(namefield)) {
                number = jp.getValueAsString();
            } else if (ContactConstants.TYPE.equals(namefield)) {
                type = ContactConstants.fromVal(typeClass, jp.getValueAsInt());
                if (type == null) {
                    type = defaultType;
                }
            } else if (ContactConstants.SUPERPRIMARY.equals(namefield)) {
                isSuperPrimary = jp.getValueAsBoolean();
            } else if (ContactConstants.PRIMARY.equals(namefield)) {
                isPrimary = jp.getValueAsBoolean();
            } else if (ContactConstants.LABEL.equals(namefield)) {
                label = jp.getValueAsString();
            } else {
                LOG.error(JSON_FIELDNOTRECOGNIZED + rowId + " Fieldname:" + fieldname + " Unrecognized: "
                        + namefield);
                break;
            }
        }
        if (number != null) {
            if (newListData == null) {
                newListData = new ArrayList();
            }
            newListData.add(new ListRawData(number, type, label, isPrimary, isSuperPrimary));
        }
    }
    return newListData;
}

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

private static List<RawImData> readImList(String rowId, List<RawImData> imAddresses, JsonParser jp)
        throws IOException {
    List<RawImData> newImAddresses = imAddresses;
    while (jp.nextToken() != JsonToken.END_ARRAY) {
        ImType type = null;/*from   ww w .jav a2 s .  c  o  m*/
        ImProtocolType proType = null;
        String customProctocolName = null;
        String imAddress = null;
        String imTypeLabel = null;
        boolean isSuperPrimary = false;
        boolean isPrimary = false;
        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.DATA.equals(namefield)) {
                imAddress = jp.getValueAsString();
            } else if (ContactConstants.TYPE.equals(namefield)) {
                type = ImType.fromVal(jp.getValueAsInt());
            } else if (ContactConstants.SUPERPRIMARY.equals(namefield)) {
                isSuperPrimary = jp.getValueAsBoolean();
            } else if (ContactConstants.PRIMARY.equals(namefield)) {
                isPrimary = jp.getValueAsBoolean();
            } else if (ContactConstants.LABEL.equals(namefield)) {
                imTypeLabel = jp.getValueAsString();
            } else if (ContactConstants.PROTOCOL_TYPE.equals(namefield)) {
                proType = ImProtocolType.fromVal(jp.getValueAsInt());
            } else if (ContactConstants.PROTOCOL_CUSTOM_PROT.equals(namefield)) {
                customProctocolName = jp.getValueAsString();
            } else {
                LOG.error(JSON_FIELDNOTRECOGNIZED + rowId + " Fieldname:" + namefield);
            }
        }
        if (newImAddresses == null) {
            newImAddresses = new ArrayList<RawImData>();
        }
        if (type == null) {
            type = ImType.TYPE_OTHER;
        }

        newImAddresses.add(new RawImData(imAddress, type, imTypeLabel, isPrimary, isSuperPrimary, proType,
                customProctocolName));
    }
    return newImAddresses;
}

From source file:com.unboundid.scim2.common.utils.Parser.java

/**
 * Read a filter from the reader.//w  w w  .  j a  v  a  2 s. c  o  m
 *
 * @param reader The reader to read the filter from.
 * @param isValueFilter Whether to read the filter as a value filter.
 * @return The parsed filter.
 * @throws BadRequestException If the filter string could not be parsed.
 */
private static Filter readFilter(final StringReader reader, final boolean isValueFilter)
        throws BadRequestException {
    final Stack<Filter> outputStack = new Stack<Filter>();
    final Stack<String> precedenceStack = new Stack<String>();

    String token;
    String previousToken = null;

    while ((token = readFilterToken(reader, isValueFilter)) != null) {
        if (token.equals("(") && expectsNewFilter(previousToken)) {
            precedenceStack.push(token);
        } else if (token.equalsIgnoreCase(FilterType.NOT.getStringValue()) && expectsNewFilter(previousToken)) {
            // "not" should be followed by an (
            String nextToken = readFilterToken(reader, isValueFilter);
            if (nextToken == null) {
                throw BadRequestException.invalidFilter("Unexpected end of filter string");
            }
            if (!nextToken.equals("(")) {
                final String msg = String.format("Expected '(' at position %d", reader.mark);
                throw BadRequestException.invalidFilter(msg);
            }
            precedenceStack.push(token);
        } else if (token.equals(")") && !expectsNewFilter(previousToken)) {
            String operator = closeGrouping(precedenceStack, outputStack, false);
            if (operator == null) {
                final String msg = String.format(
                        "No opening parenthesis matching closing " + "parenthesis at position %d", reader.mark);
                throw BadRequestException.invalidFilter(msg);
            }
            if (operator.equalsIgnoreCase(FilterType.NOT.getStringValue())) {
                // Treat "not" the same as "(" except wrap everything in a not filter.
                outputStack.push(Filter.not(outputStack.pop()));
            }
        } else if (token.equalsIgnoreCase(FilterType.AND.getStringValue())
                && !expectsNewFilter(previousToken)) {
            // and has higher precedence than or.
            precedenceStack.push(token);
        } else if (token.equalsIgnoreCase(FilterType.OR.getStringValue()) && !expectsNewFilter(previousToken)) {
            // pop all the pending ands first before pushing or.
            LinkedList<Filter> andComponents = new LinkedList<Filter>();
            while (!precedenceStack.isEmpty()) {
                if (precedenceStack.peek().equalsIgnoreCase(FilterType.AND.getStringValue())) {
                    precedenceStack.pop();
                    andComponents.addFirst(outputStack.pop());
                } else {
                    break;
                }
                if (!andComponents.isEmpty()) {
                    andComponents.addFirst(outputStack.pop());
                    outputStack.push(Filter.and(andComponents));
                }
            }

            precedenceStack.push(token);
        } else if (token.endsWith("[") && expectsNewFilter(previousToken)) {
            // This is a complex value filter.
            final Path filterAttribute;
            try {
                filterAttribute = parsePath(token.substring(0, token.length() - 1));
            } catch (final BadRequestException e) {
                Debug.debugException(e);
                final String msg = String.format("Invalid attribute path at position %d: %s", reader.mark,
                        e.getMessage());
                throw BadRequestException.invalidFilter(msg);
            }

            if (filterAttribute.isRoot()) {
                final String msg = String.format("Attribute path expected at position %d", reader.mark);
                throw BadRequestException.invalidFilter(msg);
            }

            outputStack.push(Filter.hasComplexValue(filterAttribute, readFilter(reader, true)));
        } else if (isValueFilter && token.equals("]") && !expectsNewFilter(previousToken)) {
            break;
        } else if (expectsNewFilter(previousToken)) {
            // This must be an attribute path followed by operator and maybe value.
            final Path filterAttribute;
            try {
                filterAttribute = parsePath(token);
            } catch (final BadRequestException e) {
                Debug.debugException(e);
                final String msg = String.format("Invalid attribute path at position %d: %s", reader.mark,
                        e.getMessage());
                throw BadRequestException.invalidFilter(msg);
            }

            if (filterAttribute.isRoot()) {
                final String msg = String.format("Attribute path expected at position %d", reader.mark);
                throw BadRequestException.invalidFilter(msg);
            }

            String op = readFilterToken(reader, isValueFilter);

            if (op == null) {
                throw BadRequestException.invalidFilter("Unexpected end of filter string");
            }

            if (op.equalsIgnoreCase(FilterType.PRESENT.getStringValue())) {
                outputStack.push(Filter.pr(filterAttribute));
            } else {
                ValueNode valueNode;
                try {
                    // Mark the beginning of the JSON value so we can later reset back
                    // to this position and skip the actual chars that were consumed
                    // by Jackson. The Jackson parser is buffered and reads everything
                    // until the end of string.
                    reader.mark(0);
                    ScimJsonFactory scimJsonFactory = (ScimJsonFactory) JsonUtils.getObjectReader()
                            .getFactory();
                    JsonParser parser = scimJsonFactory.createScimFilterParser(reader);
                    // The object mapper will return a Java null for JSON null.
                    // Have to distinguish between reading a JSON null and encountering
                    // the end of string.
                    if (parser.getCurrentToken() == null && parser.nextToken() == null) {
                        // End of string.
                        valueNode = null;
                    } else {
                        valueNode = parser.readValueAsTree();

                        // This is actually a JSON null. Use NullNode.
                        if (valueNode == null) {
                            valueNode = JsonUtils.getJsonNodeFactory().nullNode();
                        }
                    }
                    // Reset back to the beginning of the JSON value.
                    reader.reset();
                    // Skip the number of chars consumed by JSON parser.
                    reader.skip(parser.getCurrentLocation().getCharOffset());
                } catch (IOException e) {
                    final String msg = String.format("Invalid comparison value at position %d: %s", reader.mark,
                            e.getMessage());
                    throw BadRequestException.invalidFilter(msg);
                }

                if (valueNode == null) {
                    throw BadRequestException.invalidFilter("Unexpected end of filter string");
                }

                if (op.equalsIgnoreCase(FilterType.EQUAL.getStringValue())) {
                    outputStack.push(Filter.eq(filterAttribute, valueNode));
                } else if (op.equalsIgnoreCase(FilterType.NOT_EQUAL.getStringValue())) {
                    outputStack.push(Filter.ne(filterAttribute, valueNode));
                } else if (op.equalsIgnoreCase(FilterType.CONTAINS.getStringValue())) {
                    outputStack.push(Filter.co(filterAttribute, valueNode));
                } else if (op.equalsIgnoreCase(FilterType.STARTS_WITH.getStringValue())) {
                    outputStack.push(Filter.sw(filterAttribute, valueNode));
                } else if (op.equalsIgnoreCase(FilterType.ENDS_WITH.getStringValue())) {
                    outputStack.push(Filter.ew(filterAttribute, valueNode));
                } else if (op.equalsIgnoreCase(FilterType.GREATER_THAN.getStringValue())) {
                    outputStack.push(Filter.gt(filterAttribute, valueNode));
                } else if (op.equalsIgnoreCase(FilterType.GREATER_OR_EQUAL.getStringValue())) {
                    outputStack.push(Filter.ge(filterAttribute, valueNode));
                } else if (op.equalsIgnoreCase(FilterType.LESS_THAN.getStringValue())) {
                    outputStack.push(Filter.lt(filterAttribute, valueNode));
                } else if (op.equalsIgnoreCase(FilterType.LESS_OR_EQUAL.getStringValue())) {
                    outputStack.push(Filter.le(filterAttribute, valueNode));
                } else {
                    final String msg = String.format("Unrecognized attribute operator '%s' at position %d. "
                            + "Expected: eq,ne,co,sw,ew,pr,gt,ge,lt,le", op, reader.mark);
                    throw BadRequestException.invalidFilter(msg);
                }
            }
        } else {
            final String msg = String.format("Unexpected character '%s' at position %d", token, reader.mark);
            throw BadRequestException.invalidFilter(msg);
        }
        previousToken = token;
    }

    closeGrouping(precedenceStack, outputStack, true);

    if (outputStack.isEmpty()) {
        throw BadRequestException.invalidFilter("Unexpected end of filter string");
    }
    return outputStack.pop();
}

From source file:org.seedstack.seed.core.internal.data.DataManagerImpl.java

@Override
public void importData(InputStream inputStream, String acceptGroup, String acceptName, boolean clear) {
    Set<DataImporter<Object>> usedDataImporters = new HashSet<>();

    try {//from   w  w  w  .j a v a  2s .co  m
        ParsingState state = ParsingState.START;
        String group = null;
        String name = null;
        JsonParser jsonParser = this.jsonFactory
                .createParser(new InputStreamReader(inputStream, Charset.forName(UTF_8)));
        JsonToken jsonToken = jsonParser.nextToken();

        while (jsonToken != null) {
            switch (state) {
            case START:
                if (jsonToken == JsonToken.START_ARRAY) {
                    state = ParsingState.DEFINITION_START;
                } else {
                    throwParsingError(jsonParser.getCurrentLocation(), "start array expected");
                }

                break;
            case DEFINITION_START:
                if (jsonToken == JsonToken.START_OBJECT) {
                    state = ParsingState.DEFINITION_GROUP;
                } else {
                    throwParsingError(jsonParser.getCurrentLocation(), "start object expected");
                }

                break;
            case DEFINITION_GROUP:
                if (jsonToken == JsonToken.FIELD_NAME && GROUP.equals(jsonParser.getCurrentName())) {
                    group = jsonParser.nextTextValue();
                    state = ParsingState.DEFINITION_NAME;
                } else {
                    throwParsingError(jsonParser.getCurrentLocation(), "group field expected");
                }

                break;
            case DEFINITION_NAME:
                if (jsonToken == JsonToken.FIELD_NAME && NAME.equals(jsonParser.getCurrentName())) {
                    name = jsonParser.nextTextValue();
                    state = ParsingState.DEFINITION_ITEMS;
                } else {
                    throwParsingError(jsonParser.getCurrentLocation(), "name field expected");
                }

                break;
            case DEFINITION_ITEMS:
                if (jsonToken == JsonToken.FIELD_NAME && ITEMS.equals(jsonParser.getCurrentName())) {
                    usedDataImporters.add(consumeItems(jsonParser, group, name, acceptGroup, acceptName));
                    state = ParsingState.DEFINITION_END;
                } else {
                    throwParsingError(jsonParser.getCurrentLocation(), "items field expected");
                }

                break;
            case DEFINITION_END:
                if (jsonToken == JsonToken.END_OBJECT) {
                    group = null;
                    name = null;
                    state = ParsingState.END;
                } else {
                    throwParsingError(jsonParser.getCurrentLocation(), "end object expected");
                }

                break;
            case END:
                if (jsonToken == JsonToken.START_OBJECT) {
                    state = ParsingState.DEFINITION_GROUP;
                } else if (jsonToken == JsonToken.END_ARRAY) {
                    state = ParsingState.START;
                } else {
                    throwParsingError(jsonParser.getCurrentLocation(), "start object or end array expected");
                }

                break;
            default:
                throwParsingError(jsonParser.getCurrentLocation(), "unexpected parser state");
            }

            jsonToken = jsonParser.nextToken();
        }
    } catch (Exception e1) {
        for (DataImporter<Object> usedDataImporter : usedDataImporters) {
            try {
                usedDataImporter.rollback();
            } catch (Exception e2) {
                e2.initCause(e1);
                throw SeedException.wrap(e2, DataErrorCode.FAILED_TO_ROLLBACK_IMPORT).put(IMPORTER_CLASS,
                        usedDataImporter.getClass().getName());
            }
        }

        throw SeedException.wrap(e1, DataErrorCode.IMPORT_FAILED);
    }

    for (DataImporter<Object> usedDataImporter : usedDataImporters) {
        try {
            usedDataImporter.commit(clear);
        } catch (Exception e) {
            throw SeedException.wrap(e, DataErrorCode.FAILED_TO_COMMIT_IMPORT).put(IMPORTER_CLASS,
                    usedDataImporter.getClass().getName());
        }
    }
}

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

private static List<RawAddressData> readAddressList(String rowId, List<RawAddressData> addresses, JsonParser jp)
        throws IOException {
    List<RawAddressData> newAddresses = addresses;
    while (jp.nextToken() != JsonToken.END_ARRAY) {
        AddressType type = null;//from w w w  . j ava 2s .  co m
        String label = null;
        String street = null;
        String city = null;
        String postcode = null;
        String country = null;
        String region = null;
        String pobox = null;
        String neighborhood = null;
        boolean isSuperPrimary = false;
        boolean isPrimary = false;
        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 Array missing.",
                        jp.getCurrentLocation());
            }
            if (ContactConstants.NEIGHBORHOOD.equals(namefield)) {
                neighborhood = jp.getValueAsString();
            } else if (ContactConstants.TYPE.equals(namefield)) {
                type = AddressType.fromVal(jp.getValueAsInt());
            } else if (ContactConstants.SUPERPRIMARY.equals(namefield)) {
                isSuperPrimary = jp.getValueAsBoolean();
            } else if (ContactConstants.PRIMARY.equals(namefield)) {
                isPrimary = jp.getValueAsBoolean();
            } else if (ContactConstants.LABEL.equals(namefield)) {
                label = jp.getValueAsString();
            } else if (ContactConstants.STREET.equals(namefield)) {
                street = jp.getValueAsString();
            } else if (ContactConstants.REGION.equals(namefield)) {
                region = jp.getValueAsString();
            } else if (ContactConstants.CITY.equals(namefield)) {
                city = jp.getValueAsString();
            } else if (ContactConstants.POSTCODE.equals(namefield)) {
                postcode = jp.getValueAsString();
            } else if (ContactConstants.COUNTRY.equals(namefield)) {
                country = jp.getValueAsString();
            } else if (ContactConstants.REGION.equals(namefield)) {
                region = jp.getValueAsString();
            } else if (ContactConstants.POBOX.equals(namefield)) {
                pobox = jp.getValueAsString();
            } else {
                LOG.error(JSON_FIELDNOTRECOGNIZED + rowId + " Fieldname:" + namefield);
            }
        }
        if (newAddresses == null) {
            newAddresses = new ArrayList<RawAddressData>();
        }
        if (type == null) {
            type = AddressType.TYPE_OTHER;
        }

        newAddresses.add(new RawAddressData(type, label, isPrimary, isSuperPrimary, street, pobox, neighborhood,
                city, region, postcode, country));
    }
    return newAddresses;
}

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

/**
 * Creates and returns an instance of the RawContact from encrypted data
 * /*from   w  w  w .ja v a  2s  .  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;
}