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

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

Introduction

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

Prototype

public void beginObject() throws IOException 

Source Link

Document

Consumes the next token from the JSON stream and asserts that it is the beginning of a new object.

Usage

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  a2 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//ww w  .ja v a  2  s.  c o 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;//w  w  w . j  a v a 2s.c o m

    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);
}

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

License:Open Source License

private Map<String, String> readAspects(final JsonReader jr) throws IOException {
    final Map<String, String> result = new HashMap<>();

    jr.beginObject();
    while (jr.hasNext()) {
        switch (jr.nextName()) {
        case "map":
            jr.beginObject();/*from w w w.ja  v  a2s. co  m*/
            while (jr.hasNext()) {
                final String id = jr.nextName();
                String value = null;
                if (jr.peek() == JsonToken.STRING) {
                    value = jr.nextString();
                } else {
                    jr.skipValue();
                }
                result.put(id, value);
            }
            jr.endObject();
            break;
        }
    }
    jr.endObject();

    return result;
}

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

License:Open Source License

private Map<String, ArtifactInformation> readArtifacts(final JsonReader jr) throws IOException {
    jr.beginObject();

    final Map<String, ArtifactInformation> result = new HashMap<>();

    while (jr.hasNext()) {
        final String id = jr.nextName();
        jr.beginObject();/*  w w  w. j a v a 2 s .com*/

        String name = null;
        Long size = null;
        Instant creationTimestamp = null;
        String parentId = null;
        Set<String> childIds = Collections.emptySet();
        Set<String> facets = Collections.emptySet();
        String virtualizerAspectId = null;
        List<ValidationMessage> validationMessages = Collections.emptyList();
        Map<MetaKey, String> extractedMetaData = Collections.emptyMap();
        Map<MetaKey, String> providedMetaData = Collections.emptyMap();

        while (jr.hasNext()) {
            final String ele = jr.nextName();
            switch (ele) {
            case "name":
                name = jr.nextString();
                break;
            case "size":
                size = jr.nextLong();
                break;
            case "date":
                creationTimestamp = readTime(jr);
                break;
            case "parentId":
                parentId = jr.nextString();
                break;
            case "childIds":
                childIds = readSet(jr);
                break;
            case "facets":
                facets = readSet(jr);
                break;
            case "virtualizerAspectId":
                virtualizerAspectId = jr.nextString();
                break;
            case "extractedMetaData":
                extractedMetaData = readMetadata(jr);
                break;
            case "providedMetaData":
                providedMetaData = readMetadata(jr);
                break;
            case "validationMessages":
                validationMessages = readValidationMessages(jr);
                break;
            default:
                jr.skipValue();
                break;
            }
        }
        jr.endObject();

        if (id == null || name == null || size == null || creationTimestamp == null) {
            throw new IOException("Missing values for artifact");
        }

        this.numberOfBytes += size;

        result.put(id, new ArtifactInformation(id, parentId, childIds, name, size, creationTimestamp, facets,
                validationMessages, providedMetaData, extractedMetaData, virtualizerAspectId));
    }

    jr.endObject();

    return result;
}

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

License:Open Source License

private Map<MetaKey, String> readMetadata(final JsonReader jr) throws IOException {
    final Map<MetaKey, String> result = new HashMap<>();

    jr.beginObject();

    while (jr.hasNext()) {
        final String name = jr.nextName();
        if (jr.peek() == JsonToken.NULL) {
            jr.skipValue();/*  w ww . j  a  va  2  s.  c  o m*/
        } else {
            final String value = jr.nextString();
            result.put(MetaKey.fromString(name), value);
        }
    }

    jr.endObject();

    return result;
}

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

License:Open Source License

private ValidationMessage readValidationMessage(final JsonReader jr) throws IOException {
    String aspectId = null;//w w w  .j a v  a  2  s. co m
    Severity severity = null;
    String message = null;
    Set<String> artifactIds = Collections.emptySet();

    jr.beginObject();
    while (jr.hasNext()) {
        final String name = jr.nextName();
        switch (name) {
        case "aspectId":
            aspectId = jr.nextString();
            break;
        case "severity":
            severity = Severity.valueOf(jr.nextString());
            break;
        case "message":
            message = jr.nextString();
            break;
        case "artifactIds":
            artifactIds = readSet(jr);
            break;
        }
    }
    jr.endObject();

    if (aspectId == null || severity == null || message == null) {
        throw new IOException("Missing values in validation message");
    }

    return new ValidationMessage(aspectId, severity, message, artifactIds);
}

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

License:Open Source License

private Map<MetaKey, CacheEntryInformation> readCacheEntries(final JsonReader jr) throws IOException {
    final Map<MetaKey, CacheEntryInformation> result = new HashMap<>();

    jr.beginObject();
    while (jr.hasNext()) {
        final String entryName = jr.nextName();
        jr.beginObject();/*from w ww. ja va  2 s.  co m*/

        String name = null;
        Long size = null;
        String mimeType = null;
        Instant timestamp = null;

        while (jr.hasNext()) {
            final String ele = jr.nextName();
            switch (ele) {
            case "name":
                name = jr.nextString();
                break;
            case "size":
                size = jr.nextLong();
                break;
            case "mimeType":
                mimeType = jr.nextString();
                break;
            case "timestamp":
                timestamp = readTime(jr);
                break;
            default:
                jr.skipValue();
                break;
            }
        }

        if (name == null || size == null || mimeType == null || timestamp == null) {
            throw new IOException("Invalid format");
        }

        jr.endObject();

        final MetaKey key = MetaKey.fromString(entryName);

        result.put(key, new CacheEntryInformation(key, name, size, mimeType, timestamp));
    }
    jr.endObject();

    return result;
}

From source file:org.eclipse.packagedrone.repo.MetaKeys.java

License:Open Source License

public static Map<MetaKey, String> readJson(final Reader input) throws IOException {
    @SuppressWarnings("resource")
    final JsonReader reader = new JsonReader(input);

    final Map<MetaKey, String> result = new HashMap<>();

    reader.beginObject();

    while (reader.hasNext()) {
        final String name = reader.nextName();
        if (reader.peek() == JsonToken.NULL) {
            reader.nextNull();/*from w ww .j ava  2  s .c om*/
        } else {
            result.put(MetaKey.fromString(name), reader.nextString());
        }
    }

    reader.endObject();

    return result;
}

From source file:org.eclipse.recommenders.utils.gson.MultisetTypeAdapterFactory.java

License:Open Source License

private <E> TypeAdapter<Multiset<E>> newMultisetAdapter(final TypeAdapter<E> elementAdapter) {
    return new TypeAdapter<Multiset<E>>() {
        public void write(JsonWriter out, Multiset<E> multiset) throws IOException {
            if (multiset == null) {
                out.nullValue();/*from w w w .  ja v  a2s.  co  m*/
                return;
            }

            out.beginArray();
            for (Entry<E> entry : multiset.entrySet()) {
                out.beginObject();
                out.name("id");
                elementAdapter.write(out, entry.getElement());
                out.name("count");
                out.value(entry.getCount());
                out.endObject();
            }
            out.endArray();
        }

        public Multiset<E> read(JsonReader in) throws IOException {
            if (in.peek() == JsonToken.NULL) {
                in.nextNull();
                return null;
            }

            Multiset<E> result = LinkedHashMultiset.create();
            in.beginArray();
            while (in.hasNext()) {
                in.beginObject();
                in.nextName(); // "id"
                E element = elementAdapter.read(in);
                in.nextName(); // "count"
                int count = in.nextInt();
                result.add(element, count);
                in.endObject();
            }
            in.endArray();
            return result;
        }
    };
}