Example usage for com.google.gson.stream JsonReader nextName

List of usage examples for com.google.gson.stream JsonReader nextName

Introduction

In this page you can find the example usage for com.google.gson.stream JsonReader nextName.

Prototype

public String nextName() throws IOException 

Source Link

Document

Returns the next token, a com.google.gson.stream.JsonToken#NAME property name , and consumes it.

Usage

From source file:org.bimserver.emf.SharedJsonDeserializer.java

License:Open Source License

@SuppressWarnings({ "rawtypes", "unchecked" })
private IdEObject processObject(IfcModelInterface model, WaitingList<Long> waitingList, JsonReader jsonReader,
        EClass eClass) throws IOException, DeserializeException, IfcModelInterfaceException {
    IdEObjectImpl object = null;/*from  ww w  .j a  v a 2s  . c o  m*/
    jsonReader.beginObject();
    if (jsonReader.nextName().equals("_i")) {
        long oid = jsonReader.nextLong();
        if (jsonReader.nextName().equals("_t")) {
            String type = jsonReader.nextString();
            if (eClass == null) {
                eClass = model.getPackageMetaData().getEClassIncludingDependencies(type);
            }
            if (eClass == null) {
                throw new DeserializeException("No class found with name " + type);
            }
            if (model.containsNoFetch(oid)) {
                object = (IdEObjectImpl) model.getNoFetch(oid);
            } else {
                if (eClass == StorePackage.eINSTANCE.getIfcHeader()) {
                    object = (IdEObjectImpl) StoreFactory.eINSTANCE.createIfcHeader();
                } else {
                    object = (IdEObjectImpl) model.create(eClass, oid);
                }
            }

            if (jsonReader.nextName().equals("_s")) {
                int state = jsonReader.nextInt();
                if (state == 1) {
                    object.setLoadingState(State.LOADED);
                    while (jsonReader.hasNext()) {
                        String featureName = jsonReader.nextName();
                        boolean embedded = false;
                        if (featureName.startsWith("_r")) {
                            featureName = featureName.substring(2);
                        } else if (featureName.startsWith("_e")) {
                            embedded = true;
                            featureName = featureName.substring(2);
                        }
                        EStructuralFeature eStructuralFeature = eClass.getEStructuralFeature(featureName);
                        if (eStructuralFeature == null) {
                            throw new DeserializeException(
                                    "Unknown field (" + featureName + ") on class " + eClass.getName());
                        }
                        if (eStructuralFeature.isMany()) {
                            jsonReader.beginArray();
                            if (eStructuralFeature instanceof EAttribute) {
                                List list = (List) object.eGet(eStructuralFeature);
                                List<String> stringList = null;

                                if (eStructuralFeature.getEType() == EcorePackage.eINSTANCE.getEDoubleObject()
                                        || eStructuralFeature.getEType() == EcorePackage.eINSTANCE
                                                .getEDouble()) {
                                    EStructuralFeature asStringFeature = eClass
                                            .getEStructuralFeature(eStructuralFeature.getName() + "AsString");
                                    stringList = (List<String>) object.eGet(asStringFeature);
                                }

                                while (jsonReader.hasNext()) {
                                    Object e = readPrimitive(jsonReader, eStructuralFeature);
                                    list.add(e);
                                    if (eStructuralFeature.getEType() == EcorePackage.eINSTANCE.getEDouble()) {
                                        double val = (Double) e;
                                        stringList.add("" + val); // TODO
                                        // this
                                        // is
                                        // losing
                                        // precision,
                                        // maybe
                                        // also
                                        // send
                                        // the
                                        // string
                                        // value?
                                    }
                                }
                            } else if (eStructuralFeature instanceof EReference) {
                                int index = 0;
                                AbstractEList list = (AbstractEList) object.eGet(eStructuralFeature);
                                while (jsonReader.hasNext()) {
                                    if (embedded) {
                                        JsonToken peek = jsonReader.peek();
                                        if (peek == JsonToken.NUMBER) {
                                            long refOid = jsonReader.nextLong();
                                            processRef(model, waitingList, object, eStructuralFeature, index,
                                                    list, refOid);
                                        } else {
                                            jsonReader.beginObject();
                                            String nextName = jsonReader.nextName();
                                            if (nextName.equals("_t")) {
                                                String t = jsonReader.nextString();
                                                IdEObject wrappedObject = (IdEObject) model
                                                        .create(model.getPackageMetaData().getEClass(t), -1);
                                                if (jsonReader.nextName().equals("_v")) {
                                                    EStructuralFeature wv = wrappedObject.eClass()
                                                            .getEStructuralFeature("wrappedValue");
                                                    wrappedObject.eSet(wv, readPrimitive(jsonReader, wv));
                                                    list.add(wrappedObject);
                                                } else {
                                                    // error
                                                }
                                            } else if (nextName.equals("_i")) {
                                                // Not all are embedded...
                                                long refOid = jsonReader.nextLong();
                                                processRef(model, waitingList, object, eStructuralFeature,
                                                        index, list, refOid);
                                            }
                                            jsonReader.endObject();
                                        }
                                    } else {
                                        long refOid = jsonReader.nextLong();
                                        processRef(model, waitingList, object, eStructuralFeature, index, list,
                                                refOid);
                                    }
                                    index++;
                                }
                            }
                            jsonReader.endArray();
                        } else {
                            if (eStructuralFeature instanceof EAttribute) {
                                Object x = readPrimitive(jsonReader, eStructuralFeature);
                                if (eStructuralFeature.getEType() == EcorePackage.eINSTANCE.getEDouble()) {
                                    EStructuralFeature asStringFeature = object.eClass()
                                            .getEStructuralFeature(eStructuralFeature.getName() + "AsString");
                                    if (asStringFeature != null) {
                                        object.eSet(asStringFeature, "" + x); // TODO
                                    }
                                    // this
                                    // is
                                    // losing
                                    // precision,
                                    // maybe
                                    // also
                                    // send
                                    // the
                                    // string
                                    // value?
                                }
                                object.eSet(eStructuralFeature, x);
                            } else if (eStructuralFeature instanceof EReference) {
                                if (eStructuralFeature.getName().equals("GlobalId")) {
                                    IfcGloballyUniqueId globallyUniqueId = Ifc2x3tc1Factory.eINSTANCE
                                            .createIfcGloballyUniqueId();
                                    globallyUniqueId.setWrappedValue(jsonReader.nextString());
                                    object.eSet(eStructuralFeature, globallyUniqueId);
                                } else if (embedded) {
                                    jsonReader.beginObject();
                                    if (jsonReader.nextName().equals("_t")) {
                                        String t = jsonReader.nextString();
                                        IdEObject wrappedObject = (IdEObject) model.create(
                                                model.getPackageMetaData().getEClassIncludingDependencies(t),
                                                -1);
                                        if (eStructuralFeature.getEAnnotation("dbembed") != null) {
                                            for (EStructuralFeature eStructuralFeature2 : wrappedObject.eClass()
                                                    .getEAllStructuralFeatures()) {
                                                String fn = jsonReader.nextName();
                                                if (fn.equals(eStructuralFeature2.getName())) {
                                                    wrappedObject.eSet(eStructuralFeature2,
                                                            readPrimitive(jsonReader, eStructuralFeature2));
                                                } else {
                                                    throw new DeserializeException(
                                                            fn + " / " + eStructuralFeature2.getName());
                                                }
                                            }
                                            object.eSet(eStructuralFeature, wrappedObject);
                                        } else {
                                            if (jsonReader.nextName().equals("_v")) {
                                                EStructuralFeature wv = wrappedObject.eClass()
                                                        .getEStructuralFeature("wrappedValue");
                                                wrappedObject.eSet(wv, readPrimitive(jsonReader, wv));
                                                object.eSet(eStructuralFeature, wrappedObject);
                                            }
                                        }
                                    }
                                    jsonReader.endObject();
                                } else {
                                    long refOid = jsonReader.nextLong();
                                    boolean isInverse = false;
                                    EntityDefinition entityBN = model.getPackageMetaData().getSchemaDefinition()
                                            .getEntityBN(object.eClass().getName());
                                    if (entityBN != null) {
                                        // Some entities like GeometryInfo/Data are not in IFC schema, but valid
                                        Attribute attributeBN = entityBN
                                                .getAttributeBNWithSuper(eStructuralFeature.getName());
                                        if (attributeBN != null) {
                                            if (attributeBN instanceof InverseAttribute) {
                                                isInverse = true;
                                            }
                                        }
                                    }
                                    if (!isInverse) {
                                        if (model.contains(refOid)) {
                                            object.eSet(eStructuralFeature, model.get(refOid));
                                        } else {
                                            waitingList.add(refOid, new SingleWaitingObject(-1, object,
                                                    (EReference) eStructuralFeature));
                                        }
                                    }
                                }
                            }
                        }
                    }
                } else {
                    // state not_loaded
                }
                if (waitingList.containsKey(oid)) {
                    waitingList.updateNode(oid, eClass, object);
                }
                model.add(object.getOid(), object);
            } else {
                LOGGER.info("_s expected");
            }
        } else {
            LOGGER.info("_t expected");
        }
    } else {
        LOGGER.info("_i expected");
    }
    jsonReader.endObject();
    return object;
}

From source file:org.cyanogenmod.changelog.ChangelogParser.java

License:Open Source License

/**
 * Read ChangeInfo JSON entity//  w w  w. ja  v a  2 s. c o m
 * See http://review.cyanogenmod.org/Documentation/rest-api.html
 * @param reader the JsonReader to use
 * @return the parsed Change.
 * @throws IOException
 */
private Change parseChangeInfo(JsonReader reader) throws IOException {
    Change change = new Change();
    reader.beginObject();
    while (reader.hasNext()) {
        switch (reader.nextName()) {
        case "_number":
            change.setChangeId(reader.nextString());
            break;
        case "project":
            change.setProject(reader.nextString());
            break;
        case "subject":
            change.setSubject(reader.nextString());
            break;
        case "updated":
            change.setLastUpdate(parseTimestamp(reader.nextString()));
            break;
        case "insertions":
            change.setInsertions(reader.nextInt());
            break;
        case "deletions":
            change.setDeletions(reader.nextInt());
            break;
        default:
            reader.skipValue();
        }
    }
    reader.endObject();
    return change;
}

From source file:org.eclipse.agail.genconfgen.CheckAll.java

License:Open Source License

private static ArrayList<UserRequirementDefinition> parseUserRequirementsDefinition() {
    ArrayList<UserRequirementDefinition> userRequirements = new ArrayList<UserRequirementDefinition>();

    try {//w  w w. j a  v a2s .  co m
        JsonReader reader = new JsonReader(new FileReader(userRequirementsDefinitionPath));
        reader.beginObject();
        reader.nextName();
        UserRequirementDefinition[] userRequirementsArray = (new Gson()).fromJson(reader,
                UserRequirementDefinition[].class);
        reader.close();

        for (int i = 0; i < userRequirementsArray.length; i++) {
            userRequirements.add(userRequirementsArray[i]);
        }
    } catch (FileNotFoundException e) {
        System.err.println("Could not read from file " + userRequirementsDefinitionPath);
        e.printStackTrace();
        return new ArrayList<UserRequirementDefinition>();
    } catch (IOException e) {
        System.err.println("Could not close file " + userRequirementsDefinitionPath);
        e.printStackTrace();
    }

    return userRequirements;
}

From source file:org.eclipse.lsp4j.adapters.HoverTypeAdapter.java

License:Open Source License

public Hover read(final JsonReader in) throws IOException {
    JsonToken nextToken = in.peek();/*w w w . ja  va2s .c o  m*/
    if (nextToken == JsonToken.NULL) {
        return null;
    }

    Hover result = new Hover();
    in.beginObject();
    while (in.hasNext()) {
        String name = in.nextName();
        switch (name) {
        case "contents":
            result.setContents(readContents(in));
            break;
        case "range":
            result.setRange(readRange(in));
            break;
        default:
            in.skipValue();
        }
    }
    in.endObject();
    return result;
}

From source file:org.eclipse.lsp4j.adapters.InitializeParamsTypeAdapter.java

License:Open Source License

public InitializeParams read(final JsonReader in) throws IOException {
    JsonToken nextToken = in.peek();//from  w  w  w. ja va2 s. co m
    if (nextToken == JsonToken.NULL) {
        return null;
    }

    InitializeParams result = new InitializeParams();
    in.beginObject();
    while (in.hasNext()) {
        String name = in.nextName();
        switch (name) {
        case "processId":
            result.setProcessId(readProcessId(in));
            break;
        case "rootPath":
            result.setRootPath(readRootPath(in));
            break;
        case "rootUri":
            result.setRootUri(readRootUri(in));
            break;
        case "initializationOptions":
            result.setInitializationOptions(readInitializationOptions(in));
            break;
        case "capabilities":
            result.setCapabilities(readCapabilities(in));
            break;
        case "clientName":
            result.setClientName(readClientName(in));
            break;
        case "trace":
            result.setTrace(readTrace(in));
            break;
        case "workspaceFolders":
            result.setWorkspaceFolders(readWorkspaceFolders(in));
            break;
        default:
            in.skipValue();
        }
    }
    in.endObject();
    return result;
}

From source file:org.eclipse.lsp4j.adapters.VersionedTextDocumentIdentifierTypeAdapter.java

License:Open Source License

public VersionedTextDocumentIdentifier read(final JsonReader in) throws IOException {
    JsonToken nextToken = in.peek();//from ww w .  j  ava 2 s. c o m
    if (nextToken == JsonToken.NULL) {
        return null;
    }

    VersionedTextDocumentIdentifier result = new VersionedTextDocumentIdentifier();
    in.beginObject();
    while (in.hasNext()) {
        String name = in.nextName();
        switch (name) {
        case "version":
            result.setVersion(readVersion(in));
            break;
        case "uri":
            result.setUri(readUri(in));
            break;
        default:
            in.skipValue();
        }
    }
    in.endObject();
    return result;
}

From source file:org.eclipse.lsp4j.jsonrpc.debug.adapters.DebugMessageTypeAdapter.java

License:Open Source License

@Override
public Message read(JsonReader in) throws IOException {
    if (in.peek() == JsonToken.NULL) {
        in.nextNull();//from www  .  j  a  va 2s. c o  m
        return null;
    }

    in.beginObject();
    String messageType = null, method = null, message = null;
    int seq = 0, request_seq = 0;
    Boolean rawSuccess = null;
    Object rawParams = null;
    Object rawBody = null;

    try {

        while (in.hasNext()) {
            String name = in.nextName();
            switch (name) {
            case "seq": {
                seq = in.nextInt();
                break;
            }
            case "request_seq": {
                // on responses we treat the request_seq as the id
                request_seq = in.nextInt();
                break;
            }
            case "type": {
                messageType = in.nextString();
                break;
            }
            case "success": {
                rawSuccess = in.nextBoolean();
                break;
            }
            case "command": {
                method = in.nextString();
                break;
            }
            case "event": {
                method = in.nextString();
                break;
            }
            case "message": {
                if (in.peek() == JsonToken.NULL) {
                    in.nextNull();
                } else {
                    message = in.nextString();
                }
                break;
            }
            case "arguments": {
                rawParams = parseParams(in, method);
                break;
            }
            case "body": {
                rawBody = parseBody(in, messageType, request_seq, method, rawSuccess);
                break;
            }
            default:
                in.skipValue();
            }
        }
        boolean success = rawSuccess != null ? rawSuccess : false;
        Object params = parseParams(rawParams, method);
        Object body = parseBody(rawBody, messageType, request_seq, method, success);

        in.endObject();
        return createMessage(messageType, seq, request_seq, method, success, message, params, body);

    } catch (JsonSyntaxException | MalformedJsonException | EOFException exception) {
        if ("request".equals(messageType) || "event".equals(messageType) || "response".equals(messageType)) {
            // Create a message and bundle it to an exception with an issue that wraps the original exception
            boolean success = rawSuccess != null ? rawSuccess : false;
            Message resultMessage = createMessage(messageType, seq, request_seq, method, success, message,
                    rawParams, rawBody);
            MessageIssue issue = new MessageIssue("Message could not be parsed.",
                    ResponseErrorCode.ParseError.getValue(), exception);
            throw new MessageIssueException(resultMessage, issue);
        } else {
            throw exception;
        }
    }
}

From source file:org.eclipse.lsp4j.jsonrpc.json.adapters.MessageTypeAdapter.java

License:Open Source License

@Override
public Message read(JsonReader in) throws IOException, JsonIOException, JsonSyntaxException {
    if (in.peek() == JsonToken.NULL) {
        in.nextNull();/*from  w w w  .j  av  a  2  s.co  m*/
        return null;
    }

    in.beginObject();
    String jsonrpc = null, method = null;
    Either<String, Number> id = null;
    Object rawParams = null;
    Object rawResult = null;
    ResponseError responseError = null;
    try {

        while (in.hasNext()) {
            String name = in.nextName();
            switch (name) {
            case "jsonrpc": {
                jsonrpc = in.nextString();
                break;
            }
            case "id": {
                if (in.peek() == JsonToken.NUMBER)
                    id = Either.forRight(in.nextInt());
                else
                    id = Either.forLeft(in.nextString());
                break;
            }
            case "method": {
                method = in.nextString();
                break;
            }
            case "params": {
                rawParams = parseParams(in, method);
                break;
            }
            case "result": {
                rawResult = parseResult(in, id != null ? id.get().toString() : null);
                break;
            }
            case "error": {
                responseError = gson.fromJson(in, ResponseError.class);
                break;
            }
            default:
                in.skipValue();
            }
        }
        Object params = parseParams(rawParams, method);
        Object result = parseResult(rawResult, id != null ? id.get().toString() : null);

        in.endObject();
        return createMessage(jsonrpc, id, method, params, result, responseError);

    } catch (JsonSyntaxException | MalformedJsonException | EOFException exception) {
        if (id != null || method != null) {
            // Create a message and bundle it to an exception with an issue that wraps the original exception
            Message message = createMessage(jsonrpc, id, method, rawParams, rawResult, responseError);
            MessageIssue issue = new MessageIssue("Message could not be parsed.",
                    ResponseErrorCode.ParseError.getValue(), exception);
            throw new MessageIssueException(message, issue);
        } else {
            throw exception;
        }
    }
}

From source file:org.eclipse.lsp4j.jsonrpc.json.adapters.ThrowableTypeAdapter.java

License:Open Source License

@SuppressWarnings("unchecked")
@Override/*from  www .ja va  2  s.co m*/
public Throwable read(JsonReader in) throws IOException {
    if (in.peek() == JsonToken.NULL) {
        in.nextNull();
        return null;
    }

    in.beginObject();
    String message = null;
    Throwable cause = null;
    while (in.hasNext()) {
        String name = in.nextName();
        switch (name) {
        case "message": {
            message = in.nextString();
            break;
        }
        case "cause": {
            cause = read(in);
            break;
        }
        default:
            in.skipValue();
        }
    }
    in.endObject();

    try {
        Constructor<Throwable> constructor;
        if (message == null && cause == null) {
            constructor = (Constructor<Throwable>) typeToken.getRawType().getDeclaredConstructor();
            return constructor.newInstance();
        } else if (message == null) {
            constructor = (Constructor<Throwable>) typeToken.getRawType()
                    .getDeclaredConstructor(Throwable.class);
            return constructor.newInstance(cause);
        } else if (cause == null) {
            constructor = (Constructor<Throwable>) typeToken.getRawType().getDeclaredConstructor(String.class);
            return constructor.newInstance(message);
        } else {
            constructor = (Constructor<Throwable>) typeToken.getRawType().getDeclaredConstructor(String.class,
                    Throwable.class);
            return constructor.newInstance(message, cause);
        }
    } catch (NoSuchMethodException e) {
        if (message == null && cause == null)
            return new RuntimeException();
        else if (message == null)
            return new RuntimeException(cause);
        else if (cause == null)
            return new RuntimeException(message);
        else
            return new RuntimeException(message, cause);
    } catch (Exception e) {
        throw new JsonParseException(e);
    }
}

From source file:org.eclipse.packagedrone.repo.channel.apm.ChannelReader.java

License:Open Source License

public ModifyContextImpl read() throws IOException {
    this.numberOfBytes = 0;

    final Reader reader = new InputStreamReader(this.stream, StandardCharsets.UTF_8);

    final ChannelState.Builder state = new ChannelState.Builder();

    Boolean locked = null;/*from  w  w w.ja  v a2  s .  c  om*/

    Map<MetaKey, CacheEntryInformation> cacheEntries = Collections.emptyMap();
    Map<String, ArtifactInformation> artifacts = Collections.emptyMap();
    Map<MetaKey, String> extractedMetaData = Collections.emptyMap();
    Map<MetaKey, String> providedMetaData = Collections.emptyMap();
    Map<String, String> aspects = new HashMap<>();

    final JsonReader jr = new JsonReader(reader);

    jr.beginObject();
    while (jr.hasNext()) {
        final String name = jr.nextName();
        switch (name) {
        case "locked":
            state.setLocked(locked = jr.nextBoolean());
            break;
        case "creationTimestamp":
            state.setCreationTimestamp(readTime(jr));
            break;
        case "modificationTimestamp":
            state.setModificationTimestamp(readTime(jr));
            break;
        case "cacheEntries":
            cacheEntries = readCacheEntries(jr);
            break;
        case "artifacts":
            artifacts = readArtifacts(jr);
            break;
        case "extractedMetaData":
            extractedMetaData = readMetadata(jr);
            break;
        case "providedMetaData":
            providedMetaData = readMetadata(jr);
            break;
        case "validationMessages":
            state.setValidationMessages(readValidationMessages(jr));
            break;
        case "aspects":
            aspects = readAspects(jr);
            break;
        default:
            jr.skipValue();
            break;
        }
    }
    jr.endObject();

    if (locked == null) {
        throw new IOException("Missing values for channel");
    }

    // transient information

    state.setNumberOfArtifacts(artifacts.size());
    state.setNumberOfBytes(this.numberOfBytes);

    // create result

    return new ModifyContextImpl(this.channelId, this.store, this.cacheStore, state.build(), aspects, artifacts,
            cacheEntries, extractedMetaData, providedMetaData);
}