Example usage for com.google.gson JsonSyntaxException JsonSyntaxException

List of usage examples for com.google.gson JsonSyntaxException JsonSyntaxException

Introduction

In this page you can find the example usage for com.google.gson JsonSyntaxException JsonSyntaxException.

Prototype

public JsonSyntaxException(Throwable cause) 

Source Link

Document

Creates exception with the specified cause.

Usage

From source file:org.geotools.data.arcgisrest.GeoJSONParser.java

License:Open Source License

/**
 * Parses a GeoJSON feature properties. The values returned in a map is a
 * Boolean, a String, or a Double (for every numeric values)
 * /*from   w  w w .ja v a  2s .  com*/
 * @return A map with property names as keys, and property values as values
 * 
 * @throws IOException,
 *           JsonSyntaxException, IllegalStateException
 */
public Map<String, Object> parseProperties() throws JsonSyntaxException, IOException, IllegalStateException {

    Map<String, Object> props = new HashMap<String, Object>();
    String name;

    // If properties is null, returns a null point
    // If geometry is null, returns a null point
    try {
        if (this.reader.peek() == JsonToken.NULL) {
            this.reader.nextNull();
            throw (new MalformedJsonException("just here to avoid repeating the return statement"));
        }
    } catch (IllegalStateException | MalformedJsonException e) {
        return props;
    }

    this.reader.beginObject();

    try {
        while (this.reader.hasNext()) {
            name = this.reader.nextName();

            switch (this.reader.peek()) {

            case BOOLEAN:
                props.put(name, this.reader.nextBoolean());
                break;

            case NUMBER:
                props.put(name, this.reader.nextDouble());
                break;

            case STRING:
                props.put(name, this.reader.nextString());
                break;

            case NULL:
                this.reader.nextNull();
                props.put(name, null);
                break;

            default:
                throw (new JsonSyntaxException("Value expected"));
            }
        }
    } catch (IOException | IllegalStateException e) {
        throw (new NoSuchElementException(e.getMessage()));
    }

    this.reader.endObject();

    return props;
}

From source file:org.geotools.data.arcgisrest.GeoJSONParser.java

License:Open Source License

/**
 * Checks the next token is expProp, trows an exception if not
 * /*from w w  w .  j a v  a2  s.c o  m*/
 * @param expProp
 *          expected property name
 * @throws JsonSyntaxException
 *           ,IoException
 */
protected void checkPropertyName(String expProp) throws JsonSyntaxException, IOException {

    if (!expProp.equals(this.reader.nextName())) {
        throw (new JsonSyntaxException("'" + expProp + "' property expected"));
    }
}

From source file:org.geotools.data.arcgisrest.GeoJSONParser.java

License:Open Source License

/**
 * Checks the next strig value is expValue, trows an exception if not
 * /*from   w  w  w  .j  a  va2 s . com*/
 * @param expValue
 *          expected property value
 * @throws JsonSyntaxException
 *           ,IoException
 */
protected void checkPropertyValue(String expValue) throws JsonSyntaxException, IOException {

    if (!expValue.equals(this.reader.nextString())) {
        throw (new JsonSyntaxException("'" + expValue + "' value expected"));
    }
}

From source file:org.hibernate.search.backend.elasticsearch.gson.impl.AbstractExtraPropertiesJsonAdapter.java

License:LGPL

@Override
public T read(JsonReader in) throws IOException {
    if (in.peek() == JsonToken.NULL) {
        in.nextNull();/*  w w w.  jav  a  2  s.  co m*/
        return null;
    }

    T instance = createInstance();
    try {
        in.beginObject();
        while (in.hasNext()) {
            String name = in.nextName();
            FieldAdapter<? super T> fieldAdapter = fieldAdapters.get(name);
            if (fieldAdapter == null) {
                extraPropertyAdapter.readOne(in, name, instance);
            } else {
                fieldAdapter.read(in, instance);
            }
        }
        in.endObject();
    } catch (IllegalStateException e) {
        throw new JsonSyntaxException(e);
    }

    return instance;
}

From source file:org.jackhuang.hellominecraft.launcher.core.download.MinecraftDownloadService.java

License:Open Source License

@Override
public Task downloadMinecraft(String id) {
    return new TaskInfo("Download Minecraft") {
        @Override/* w ww.j  a v  a  2s.co m*/
        public Collection<Task> getDependTasks() {
            return Arrays.asList(downloadMinecraftVersionJson(id));
        }

        @Override
        public void executeTask() throws Throwable {
            File vpath = new File(service.baseDirectory(), "versions/" + id);
            if (!areDependTasksSucceeded) {
                FileUtils.deleteDirectory(vpath);
                throw new RuntimeException("Cannot continue because of download failing.");
            }
            File mvj = new File(vpath, id + ".jar");
            if (mvj.exists() && !mvj.delete())
                HMCLog.warn("Failed to delete " + mvj);
            try {
                MinecraftVersion mv = C.GSON.fromJson(FileUtils.readQuietly(new File(vpath, id + ".json")),
                        MinecraftVersion.class);
                if (mv == null)
                    throw new JsonSyntaxException("incorrect version");

                afters.add(downloadMinecraftJar(mv, mvj));
            } catch (JsonSyntaxException ex) {
                HMCLog.err("Failed to parse minecraft version json.", ex);
                FileUtils.deleteDirectory(vpath);
            }
        }

        Collection<Task> afters = new HashSet<>();

        @Override
        public Collection<Task> getAfterTasks() {
            return afters;
        }
    };
}

From source file:org.jackhuang.hmcl.core.download.MinecraftDownloadService.java

License:Open Source License

@Override
public Task downloadMinecraft(String id) {
    return new TaskInfo("Download Minecraft") {
        @Override//from   w  w  w  .  j  a  v  a2 s .  c o  m
        public Collection<Task> getDependTasks() {
            return Arrays.asList(downloadMinecraftVersionJson(id));
        }

        @Override
        public void executeTask(boolean areDependTasksSucceeded) throws Exception {
            File vpath = new File(service.baseDirectory(), "versions/" + id);
            if (!areDependTasksSucceeded) {
                FileUtils.deleteDirectory(vpath);
                throw new RuntimeException("Cannot continue because of download failing.");
            }
            File mvj = new File(vpath, id + ".jar");
            if (mvj.exists() && !mvj.delete())
                HMCLog.warn("Failed to delete " + mvj);
            try {
                MinecraftVersion mv = C.GSON.fromJson(FileUtils.readQuietly(new File(vpath, id + ".json")),
                        MinecraftVersion.class);
                if (mv == null)
                    throw new JsonSyntaxException("incorrect version");

                afters.add(downloadMinecraftJar(mv, mvj));
            } catch (JsonSyntaxException ex) {
                HMCLog.err("Failed to parse minecraft version json.", ex);
                FileUtils.deleteDirectory(vpath);
            }
        }

        Collection<Task> afters = new HashSet<>();

        @Override
        public Collection<Task> getAfterTasks() {
            return afters;
        }
    };
}

From source file:org.jackhuang.hmcl.core.version.MinecraftVersionManager.java

License:Open Source License

@Override
public synchronized void refreshVersions() {
    HMCLApi.EVENT_BUS.fireChannel(new RefreshingVersionsEvent(this));

    try {/*from w ww .j a  v  a2s .c o m*/
        MCUtils.tryWriteProfile(baseDirectory());
    } catch (IOException ex) {
        HMCLog.warn("Failed to create launcher_profiles.json, Forge/LiteLoader installer will not work.", ex);
    }

    versions.clear();
    File oldDir = new File(baseDirectory(), "bin");
    if (oldDir.exists()) {
        MinecraftClassicVersion v = new MinecraftClassicVersion();
        versions.put(v.id, v);
    }

    File version = new File(baseDirectory(), "versions");
    File[] files = version.listFiles();
    if (files != null && files.length > 0)
        for (File dir : files) {
            String id = dir.getName();
            File jsonFile = new File(dir, id + ".json");

            if (!dir.isDirectory())
                continue;
            boolean ask = false;
            File[] jsons = null;
            if (!jsonFile.exists()) {
                jsons = FileUtils.searchSuffix(dir, "json");
                if (jsons.length == 1)
                    ask = true;
            }
            if (ask) {
                HMCLog.warn("Found not matched filenames version: " + id + ", json: " + jsons[0].getName());
                if (MessageBox.show(
                        String.format(C.i18n("launcher.versions_json_not_matched"), id, jsons[0].getName()),
                        MessageBox.YES_NO_OPTION) == MessageBox.YES_OPTION)
                    if (!jsons[0].renameTo(jsonFile))
                        HMCLog.warn("Failed to rename version json " + jsons[0]);
            }
            if (!jsonFile.exists()) {
                if (MessageBox.show(C.i18n("launcher.versions_json_not_matched_cannot_auto_completion", id),
                        MessageBox.YES_NO_OPTION) == MessageBox.YES_OPTION)
                    FileUtils.deleteDirectoryQuietly(dir);
                continue;
            }
            MinecraftVersion mcVersion;
            try {
                mcVersion = readJson(jsonFile);
                if (mcVersion == null)
                    throw new JsonSyntaxException("Wrong json format, got null.");
            } catch (JsonSyntaxException | IOException e) {
                HMCLog.warn("Found wrong format json, try to fix it.", e);
                if (MessageBox.show(C.i18n("launcher.versions_json_not_formatted", id),
                        MessageBox.YES_NO_OPTION) == MessageBox.YES_OPTION) {
                    TaskWindow.factory().execute(service.download().downloadMinecraftVersionJson(id));
                    try {
                        mcVersion = readJson(jsonFile);
                        if (mcVersion == null)
                            throw new JsonSyntaxException("Wrong json format, got null.");
                    } catch (IOException | JsonSyntaxException ex) {
                        HMCLog.warn("Ignoring: " + dir + ", the json of this Minecraft is malformed.", ex);
                        continue;
                    }
                } else
                    continue;
            }
            try {
                if (!id.equals(mcVersion.id)) {
                    HMCLog.warn("Found: " + dir + ", it contains id: " + mcVersion.id + ", expected: " + id
                            + ", this app will fix this problem.");
                    mcVersion.id = id;
                    FileUtils.writeQuietly(jsonFile, C.GSON.toJson(mcVersion));
                }

                versions.put(id, mcVersion);
                HMCLApi.EVENT_BUS.fireChannel(new LoadedOneVersionEvent(this, id));
            } catch (Exception e) {
                HMCLog.warn("Ignoring: " + dir + ", the json of this Minecraft is malformed.", e);
            }
        }
    HMCLApi.EVENT_BUS.fireChannel(new RefreshedVersionsEvent(this));
}

From source file:org.kairosdb.core.http.rest.json.DataPointsParser.java

License:Apache License

private NewMetric parseMetric(JsonReader reader) {
    NewMetric metric;/*from w  ww .  ja  v a  2s  .c om*/
    try {
        metric = gson.fromJson(reader, NewMetric.class);
    } catch (IllegalArgumentException e) {
        // Happens when parsing data points where one of the pair is missing (timestamp or value)
        throw new JsonSyntaxException("Invalid JSON");
    }
    return metric;
}

From source file:org.onos.yangtools.yang.data.codec.gson.JsonParserStream.java

License:Open Source License

public JsonParserStream parse(final JsonReader reader) throws JsonIOException, JsonSyntaxException {
    // code copied from gson's JsonParser and Stream classes

    final boolean lenient = reader.isLenient();
    reader.setLenient(true);//from ww  w. jav a2  s  .c  om
    boolean isEmpty = true;
    try {
        reader.peek();
        isEmpty = false;
        final CompositeNodeDataWithSchema compositeNodeDataWithSchema = new CompositeNodeDataWithSchema(
                parentNode);
        read(reader, compositeNodeDataWithSchema);
        compositeNodeDataWithSchema.write(writer);

        return this;
        // return read(reader);
    } catch (final EOFException e) {
        if (isEmpty) {
            return this;
            // return JsonNull.INSTANCE;
        }
        // The stream ended prematurely so it is likely a syntax error.
        throw new JsonSyntaxException(e);
    } catch (final MalformedJsonException e) {
        throw new JsonSyntaxException(e);
    } catch (final IOException e) {
        throw new JsonIOException(e);
    } catch (final NumberFormatException e) {
        throw new JsonSyntaxException(e);
    } catch (StackOverflowError | OutOfMemoryError e) {
        throw new JsonParseException("Failed parsing JSON source: " + reader + " to Json", e);
    } finally {
        reader.setLenient(lenient);
    }
}

From source file:org.onos.yangtools.yang.data.codec.gson.JsonParserStream.java

License:Open Source License

public void read(final JsonReader in, AbstractNodeDataWithSchema parent) throws IOException {
    switch (in.peek()) {
    case STRING://from ww w .  ja v  a  2s .  c o  m
    case NUMBER:
        setValue(parent, in.nextString());
        break;
    case BOOLEAN:
        setValue(parent, Boolean.toString(in.nextBoolean()));
        break;
    case NULL:
        in.nextNull();
        setValue(parent, null);
        break;
    case BEGIN_ARRAY:
        in.beginArray();
        while (in.hasNext()) {
            if (parent instanceof LeafNodeDataWithSchema) {
                read(in, parent);
            } else {
                final AbstractNodeDataWithSchema newChild = newArrayEntry(parent);
                read(in, newChild);
            }
        }
        in.endArray();
        return;
    case BEGIN_OBJECT:
        final Set<String> namesakes = new HashSet<>();
        in.beginObject();
        /*
         * This allows parsing of incorrectly /as showcased/
         * in testconf nesting of list items - eg.
         * lists with one value are sometimes serialized
         * without wrapping array.
         *
         */
        if (isArray(parent)) {
            parent = newArrayEntry(parent);
        }
        while (in.hasNext()) {
            final String jsonElementName = in.nextName();
            final NamespaceAndName namespaceAndName = resolveNamespace(jsonElementName, parent.getSchema());
            final String localName = namespaceAndName.getName();
            addNamespace(namespaceAndName.getUri());
            if (namesakes.contains(jsonElementName)) {
                throw new JsonSyntaxException("Duplicate name " + jsonElementName + " in JSON input.");
            }
            namesakes.add(jsonElementName);
            final Deque<DataSchemaNode> childDataSchemaNodes = findSchemaNodeByNameAndNamespace(
                    parent.getSchema(), localName, getCurrentNamespace());
            if (childDataSchemaNodes.isEmpty()) {
                throw new IllegalStateException("Schema for node with name " + localName + " and namespace "
                        + getCurrentNamespace() + " doesn't exist.");
            }

            final AbstractNodeDataWithSchema newChild = ((CompositeNodeDataWithSchema) parent)
                    .addChild(childDataSchemaNodes);
            /*
             * FIXME:anyxml data shouldn't be skipped but should be loaded somehow.
             * will be able to load anyxml which conforms to YANG data using these
             * parser, for other anyxml will be harder.
             */
            if (newChild instanceof AnyXmlNodeDataWithSchema) {
                in.skipValue();
            } else {
                read(in, newChild);
            }
            removeNamespace();
        }
        in.endObject();
        return;
    case END_DOCUMENT:
    case NAME:
    case END_OBJECT:
    case END_ARRAY:
        break;
    }
}