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:net.minecraftforge.common.crafting.CraftingHelper.java

License:Open Source License

private static void init() {
    conditions.clear();//  www.  j av a2s.c  om
    ingredients.clear();
    recipes.clear();

    registerC("forge:mod_loaded", (context, json) -> {
        String modid = JsonUtils.getString(json, "modid");
        return () -> Loader.isModLoaded(modid);
    });
    registerC("minecraft:item_exists", (context, json) -> {
        String itemName = context.appendModId(JsonUtils.getString(json, "item"));
        return () -> ForgeRegistries.ITEMS.containsKey(new ResourceLocation(itemName));
    });
    registerC("forge:not", (context, json) -> {
        BooleanSupplier child = CraftingHelper.getCondition(JsonUtils.getJsonObject(json, "value"), context);
        return () -> !child.getAsBoolean();
    });
    registerC("forge:or", (context, json) -> {
        JsonArray values = JsonUtils.getJsonArray(json, "values");
        List<BooleanSupplier> children = Lists.newArrayList();
        for (JsonElement j : values) {
            if (!j.isJsonObject())
                throw new JsonSyntaxException("Or condition values must be an array of JsonObjects");
            children.add(CraftingHelper.getCondition(j.getAsJsonObject(), context));
        }
        return () -> children.stream().anyMatch(BooleanSupplier::getAsBoolean);
    });
    registerC("forge:and", (context, json) -> {
        JsonArray values = JsonUtils.getJsonArray(json, "values");
        List<BooleanSupplier> children = Lists.newArrayList();
        for (JsonElement j : values) {
            if (!j.isJsonObject())
                throw new JsonSyntaxException("And condition values must be an array of JsonObjects");
            children.add(CraftingHelper.getCondition(j.getAsJsonObject(), context));
        }
        return () -> children.stream().allMatch(c -> c.getAsBoolean());
    });
    registerC("forge:false", (context, json) -> {
        return () -> false;
    });

    registerR("minecraft:crafting_shaped", (context, json) -> {
        String group = JsonUtils.getString(json, "group", "");
        //if (!group.isEmpty() && group.indexOf(':') == -1)
        //    group = context.getModId() + ":" + group;

        Map<Character, Ingredient> ingMap = Maps.newHashMap();
        for (Entry<String, JsonElement> entry : JsonUtils.getJsonObject(json, "key").entrySet()) {
            if (entry.getKey().length() != 1)
                throw new JsonSyntaxException("Invalid key entry: '" + entry.getKey()
                        + "' is an invalid symbol (must be 1 character only).");
            if (" ".equals(entry.getKey()))
                throw new JsonSyntaxException("Invalid key entry: ' ' is a reserved symbol.");

            ingMap.put(entry.getKey().toCharArray()[0],
                    CraftingHelper.getIngredient(entry.getValue(), context));
        }
        ingMap.put(' ', Ingredient.EMPTY);

        JsonArray patternJ = JsonUtils.getJsonArray(json, "pattern");

        if (patternJ.size() == 0)
            throw new JsonSyntaxException("Invalid pattern: empty pattern not allowed");
        if (patternJ.size() > 3)
            throw new JsonSyntaxException("Invalid pattern: too many rows, 3 is maximum");

        String[] pattern = new String[patternJ.size()];
        for (int x = 0; x < pattern.length; ++x) {
            String line = JsonUtils.getString(patternJ.get(x), "pattern[" + x + "]");
            if (line.length() > 3)
                throw new JsonSyntaxException("Invalid pattern: too many columns, 3 is maximum");
            if (x > 0 && pattern[0].length() != line.length())
                throw new JsonSyntaxException("Invalid pattern: each row must be the same width");
            pattern[x] = line;
        }

        NonNullList<Ingredient> input = NonNullList.withSize(pattern[0].length() * pattern.length,
                Ingredient.EMPTY);
        Set<Character> keys = Sets.newHashSet(ingMap.keySet());
        keys.remove(' ');

        int x = 0;
        for (String line : pattern) {
            for (char chr : line.toCharArray()) {
                Ingredient ing = ingMap.get(chr);
                if (ing == null)
                    throw new JsonSyntaxException(
                            "Pattern references symbol '" + chr + "' but it's not defined in the key");
                input.set(x++, ing);
                keys.remove(chr);
            }
        }

        if (!keys.isEmpty())
            throw new JsonSyntaxException("Key defines symbols that aren't used in pattern: " + keys);

        ItemStack result = CraftingHelper.getItemStack(JsonUtils.getJsonObject(json, "result"), context);
        return new ShapedRecipes(group, pattern[0].length(), pattern.length, input, result);
    });
    registerR("minecraft:crafting_shapeless", (context, json) -> {
        String group = JsonUtils.getString(json, "group", "");

        NonNullList<Ingredient> ings = NonNullList.create();
        for (JsonElement ele : JsonUtils.getJsonArray(json, "ingredients"))
            ings.add(CraftingHelper.getIngredient(ele, context));

        if (ings.isEmpty())
            throw new JsonParseException("No ingredients for shapeless recipe");
        if (ings.size() > 9)
            throw new JsonParseException("Too many ingredients for shapeless recipe");

        ItemStack itemstack = CraftingHelper.getItemStack(JsonUtils.getJsonObject(json, "result"), context);
        return new ShapelessRecipes(group, itemstack, ings);
    });
    registerR("forge:ore_shaped", ShapedOreRecipe::factory);
    registerR("forge:ore_shapeless", ShapelessOreRecipe::factory);

    registerI("minecraft:item",
            (context, json) -> Ingredient.fromStacks(CraftingHelper.getItemStackBasic(json, context)));
    registerI("minecraft:empty", (context, json) -> Ingredient.EMPTY);
    registerI("minecraft:item_nbt",
            (context, json) -> new IngredientNBT(CraftingHelper.getItemStack(json, context)));
    registerI("forge:ore_dict", (context, json) -> new OreIngredient(JsonUtils.getString(json, "ore")));
}

From source file:net.minecraftforge.common.crafting.CraftingHelper.java

License:Open Source License

private static <T> T getClassInstance(String clsName, Class<T> expected) {
    try {//  ww  w .  j a v  a 2 s. com
        Class<?> cls = Class.forName(clsName);
        if (!expected.isAssignableFrom(cls))
            throw new JsonSyntaxException("Class '" + clsName + "' is not an " + expected.getSimpleName());
        return (T) cls.newInstance();
    } catch (ClassNotFoundException e) {
        throw new JsonSyntaxException("Could not find " + expected.getSimpleName() + ": " + clsName, e);
    } catch (InstantiationException | IllegalAccessException e) {
        throw new JsonSyntaxException("Could not instantiate " + expected.getSimpleName() + ": " + clsName, e);
    }
}

From source file:net.minecraftforge.common.crafting.JsonContext.java

License:Open Source License

void loadConstants(JsonObject[] jsons) {
    for (JsonObject json : jsons) {
        if (json.has("conditions")
                && !CraftingHelper.processConditions(json.getAsJsonArray("conditions"), this))
            continue;
        if (!json.has("ingredient"))
            throw new JsonSyntaxException("Constant entry must contain 'ingredient' value");
        constants.put(JsonUtils.getString(json, "name"),
                CraftingHelper.getIngredient(json.get("ingredient"), this));
    }/*  w ww. j a v a 2 s  .co  m*/

}

From source file:net.minecraftforge.oredict.ShapedOreRecipe.java

License:Open Source License

public static ShapedOreRecipe factory(JsonContext context, JsonObject json) {
    String group = JsonUtils.getString(json, "group", "");
    //if (!group.isEmpty() && group.indexOf(':') == -1)
    //    group = context.getModId() + ":" + group;

    Map<Character, Ingredient> ingMap = Maps.newHashMap();
    for (Entry<String, JsonElement> entry : JsonUtils.getJsonObject(json, "key").entrySet()) {
        if (entry.getKey().length() != 1)
            throw new JsonSyntaxException("Invalid key entry: '" + entry.getKey()
                    + "' is an invalid symbol (must be 1 character only).");
        if (" ".equals(entry.getKey()))
            throw new JsonSyntaxException("Invalid key entry: ' ' is a reserved symbol.");

        ingMap.put(entry.getKey().toCharArray()[0], CraftingHelper.getIngredient(entry.getValue(), context));
    }//from  ww  w.j av  a2 s  .  c  om

    ingMap.put(' ', Ingredient.EMPTY);

    JsonArray patternJ = JsonUtils.getJsonArray(json, "pattern");

    if (patternJ.size() == 0)
        throw new JsonSyntaxException("Invalid pattern: empty pattern not allowed");

    String[] pattern = new String[patternJ.size()];
    for (int x = 0; x < pattern.length; ++x) {
        String line = JsonUtils.getString(patternJ.get(x), "pattern[" + x + "]");
        if (x > 0 && pattern[0].length() != line.length())
            throw new JsonSyntaxException("Invalid pattern: each row must  be the same width");
        pattern[x] = line;
    }

    ShapedPrimer primer = new ShapedPrimer();
    primer.width = pattern[0].length();
    primer.height = pattern.length;
    primer.mirrored = JsonUtils.getBoolean(json, "mirrored", true);
    primer.input = NonNullList.withSize(primer.width * primer.height, Ingredient.EMPTY);

    Set<Character> keys = Sets.newHashSet(ingMap.keySet());
    keys.remove(' ');

    int x = 0;
    for (String line : pattern) {
        for (char chr : line.toCharArray()) {
            Ingredient ing = ingMap.get(chr);
            if (ing == null)
                throw new JsonSyntaxException(
                        "Pattern references symbol '" + chr + "' but it's not defined in the key");
            primer.input.set(x++, ing);
            keys.remove(chr);
        }
    }

    if (!keys.isEmpty())
        throw new JsonSyntaxException("Key defines symbols that aren't used in pattern: " + keys);

    ItemStack result = CraftingHelper.getItemStack(JsonUtils.getJsonObject(json, "result"), context);
    return new ShapedOreRecipe(group.isEmpty() ? null : new ResourceLocation(group), result, primer);
}

From source file:org.ckan.Connection.java

License:Open Source License

/**
 * Makes a POST request/*w ww . jav a2 s .co m*/
 *
 * Submits a POST HTTP request to the CKAN instance configured within the
 * constructor, returning the entire contents of the response.
 *
 * @param path The URL path to make the POST request to
 * @param data The data to be posted to the URL
 * @returns The String contents of the response
 * @throws A CKANException if the request fails
 */
protected String post(String path, String data) throws CKANException {
    URL url = null;

    try {
        String urlString = this.m_host + ":" + this.m_port + path;
        logger.debug("posting url: " + urlString);
        logger.debug("posting data: " + data);
        url = new URL(urlString);
    } catch (MalformedURLException mue) {
        System.err.println(mue);
        return null;
    }

    String body = "";

    BasicClientConnectionManager bccm = null;
    //ClientConnectionManager cm = null;
    try {
        /**
         * ********************************************************************
         */
        SSLContext sslContext = SSLContext.getInstance("SSL");
        // set up a TrustManager that trusts everything
        sslContext.init(null, new TrustManager[] { new X509TrustManager() {
            public X509Certificate[] getAcceptedIssuers() {
                System.out.println("getAcceptedIssuers =============");
                return null;
            }

            public void checkClientTrusted(X509Certificate[] certs, String authType) {
                System.out.println("checkClientTrusted =============");
            }

            public void checkServerTrusted(X509Certificate[] certs, String authType) {
                System.out.println("checkServerTrusted =============");
            }
        } }, new SecureRandom());
        SSLSocketFactory sf = new SSLSocketFactory(sslContext);
        Scheme httpsScheme = new Scheme("https", 443, sf);
        SchemeRegistry schemeRegistry = new SchemeRegistry();
        schemeRegistry.register(httpsScheme);
        bccm = new BasicClientConnectionManager(schemeRegistry);
        // apache HttpClient version >4.2 should use BasicClientConnectionManager
        // cm = new SingleClientConnManager(schemeRegistry);
        /**
         * ********************************************************************
         */
    } catch (KeyManagementException kme) {
        logger.error("Con ex: " + kme.getMessage());
    } catch (NoSuchAlgorithmException nsae) {
        logger.error("Con ex: " + nsae.getMessage());
    }

    //HttpClient httpclient = new DefaultHttpClient(bccm);
    HttpClient httpclient = HttpClientBuilder.create().build();
    try {
        HttpPost postRequest = new HttpPost(url.toString());
        postRequest.setHeader("X-CKAN-API-Key", this._apikey);
        StringEntity input = new StringEntity(data);
        input.setContentType("application/json");
        postRequest.setEntity(input);
        HttpResponse response = httpclient.execute(postRequest);
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode == 301) { // quick hack just for dati.trentino                                
            logger.debug(
                    "Got a 301 Moved Permanently for a POST with a json as data, see https://github.com/opendatatrentino/TrCkanClient/issues/2");
            logger.debug(
                    "As quick hack retrying using a GET. GET parameters will be taken from POST data, supposing it is a JSON");
            try {

                JsonElement jelement = new JsonParser().parse(data);
                if (!jelement.isJsonObject()) {
                    throw new JsonSyntaxException("POST body is not a json object");
                }

                JsonObject jobj = jelement.getAsJsonObject();
                StringBuilder urlParams = new StringBuilder();
                boolean first = true;
                for (Map.Entry<String, JsonElement> entry : jobj.entrySet()) {

                    String param = entry.getValue().toString();
                    String strippedParam = param;
                    if (param.length() > 1 && param.charAt(0) == '\"'
                            && param.charAt(param.length() - 1) == '\"') {
                        strippedParam = param.substring(1, param.length() - 1);
                    }

                    urlParams.append(first ? "?" : "&").append(URLEncoder.encode(entry.getKey(), "UTF-8"))
                            .append("=").append(URLEncoder.encode(strippedParam, "UTF-8"));
                    first = false;
                }
                ;
                String getUrl = url.toString() + urlParams.toString();
                logger.debug("GET url = " + getUrl);
                HttpGet getRequest = new HttpGet(getUrl);

                getRequest.setHeader("X-CKAN-API-Key", this._apikey);
                response = httpclient.execute(getRequest);
                statusCode = response.getStatusLine().getStatusCode();
            } catch (JsonSyntaxException ex) {
                throw new RuntimeException(
                        "Got a 301 Moved Permanently after a POST. Retried with a GET and failed. See https://github.com/opendatatrentino/TrCkanClient/issues/2",
                        ex);
            }

        }

        BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));

        String line = "";
        while ((line = br.readLine()) != null) {
            body += line;
        }
        logger.debug("post status: " + statusCode + " post result: " + body);
    } catch (IOException ioe) {
        System.out.println(ioe);
    } finally {
        httpclient.getConnectionManager().shutdown();
    }

    return body;
}

From source file:org.couchbase.mock.subdoc.Executor.java

License:Apache License

private static <T> T parseStrictJson(String text, Class<T> klass) {
    try {/*from  w  w  w .j a  v  a2  s.c o m*/
        JSONValue.parseWithException(text);
    } catch (ParseException ex) {
        throw new JsonSyntaxException(ex);
    } catch (NumberFormatException ex2) {
        // Ignore number formats. GSON uses BigInteger if it's too big anyway. It's perfectly valid JSON
    }
    JsonReader reader = new JsonReader(new StringReader(text));
    reader.setLenient(false);
    return gs.fromJson(reader, klass);
}

From source file:org.eclipse.smarthome.storage.json.PropertiesTypeAdapter.java

License:Open Source License

@Override
public Map<String, Object> read(JsonReader in) throws IOException {
    // gson implementation code is modified when deserializing numbers
    JsonToken peek = in.peek();/*from w  ww  .  j  av a2s .  c  o  m*/
    if (peek == JsonToken.NULL) {
        in.nextNull();
        return null;
    }

    Map<String, Object> map = constructor.get(TOKEN).construct();

    if (peek == JsonToken.BEGIN_ARRAY) {
        in.beginArray();
        while (in.hasNext()) {
            in.beginArray(); // entry array
            String key = keyAdapter.read(in);

            // modification
            Object value = getValue(in);

            Object replaced = map.put(key, value);
            if (replaced != null) {
                throw new JsonSyntaxException("duplicate key: " + key);
            }
            in.endArray();
        }
        in.endArray();
    } else {
        in.beginObject();
        while (in.hasNext()) {
            JsonReaderInternalAccess.INSTANCE.promoteNameToValue(in);
            String key = keyAdapter.read(in);

            // modification
            Object value = getValue(in);

            Object replaced = map.put(key, value);
            if (replaced != null) {
                throw new JsonSyntaxException("duplicate key: " + key);
            }
        }
        in.endObject();
    }
    return map;
}

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

License:Open Source License

public ArcGISRestDataStore(String namespaceIn, String apiEndpoint, boolean opendataFlagIn, String user,
        String password) throws MalformedURLException, JsonSyntaxException, IOException {

    super();/* w w  w  .  jav a 2  s .co  m*/

    try {
        this.namespace = new URL(namespaceIn);
    } catch (MalformedURLException e) {
        LOGGER.log(Level.SEVERE, "Namespace \"" + namespaceIn + "\" is not properly formatted", e);
        throw (e);
    }
    try {
        this.apiUrl = new URL(apiEndpoint);
    } catch (MalformedURLException e) {
        LOGGER.log(Level.SEVERE, "URL \"" + apiEndpoint + "\" is not properly formatted", e);
        throw (e);
    }
    this.user = user;
    this.password = password;
    this.opendataFlag = opendataFlagIn;

    // Retrieves the catalog JSON document
    String response = null;
    Error_ err;
    try {
        response = ArcGISRestDataStore.InputStreamToString(this.retrieveJSON("GET", apiUrl, DEFAULT_PARAMS));
    } catch (IOException e) {
        LOGGER.log(Level.SEVERE, "Error during retrieval of service '" + apiUrl + "' " + e.getMessage(), e);
        throw (e);
    }

    // Gets the catalog of web services in either the Open Data catalog, or
    // the ArcGIS Server list of services

    // If this is the Open Data catalog, it loads it
    if (this.opendataFlag == true) {
        this.catalog = (new Gson()).fromJson(response, Catalog.class);
        if (this.catalog == null) {
            throw (new JsonSyntaxException("Malformed JSON"));
        }

        // It it is an ArcGIS Server, cycles through the services list to
        // retrieve the web services URL of the FeautreServers
    } else {
        this.catalog = new Catalog();

        Featureserver featureServer = null;

        try {
            featureServer = (new Gson()).fromJson(response, Featureserver.class);
            if (featureServer == null) {
                throw (new JsonSyntaxException("Malformed JSON"));
            }
        } catch (JsonSyntaxException e) {
            // Checks whether we have an ArcGIS error message
            Error_ errWS = (new Gson()).fromJson(response, Error_.class);
            LOGGER.log(Level.SEVERE,
                    "Error during retrieval of feature server " + errWS.getCode() + " " + errWS.getMessage(),
                    e);
            return;
        }

        // Checks API version and output format of the endpoint
        if (featureServer.getCurrentVersion() < MINIMUM_API_VERSION || featureServer.getSupportedQueryFormats()
                .toString().toLowerCase().contains(FORMAT_JSON.toLowerCase()) == false) {
            UnsupportedImplementationException e = new UnsupportedImplementationException("FeatureServer "
                    + apiEndpoint
                    + " does not support either the minimum API version required, or the GeoJSON format");
            LOGGER.log(Level.SEVERE, e.getMessage());
            throw (e);
        }

        try {
            String featureServerURLString = apiUrl.toString();
            featureServer.getLayers().forEach(layer -> {
                Dataset ds = new Dataset();
                ds.setWebService(featureServerURLString + "/" + layer.getId());
                this.catalog.getDataset().add(ds);
            });
        } catch (JsonSyntaxException e) {
            // Checks whether we have an AercGIS error message
            err = (new Gson()).fromJson(response, Error_.class);
            LOGGER.log(Level.SEVERE, "JSON syntax error " + err.getCode() + " " + err.getMessage(), e);
            throw (e);
        }
    }
}

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

License:Open Source License

@Override
protected List<Name> createTypeNames() {

    if (this.entries.isEmpty() == false) {
        return new ArrayList<Name>(this.entries.keySet());
    }//from   w ww  .ja v  a  2 s.c  o m

    final List<Dataset> datasetList = this.getCatalog().getDataset();
    List<Name> typeNames = new ArrayList<Name>();

    // Starts an executor with a fixed numbe rof threads
    ExecutorService executor = Executors.newFixedThreadPool(REQUEST_THREADS);

    /**
     * Since there could be many datasets in the FeatureServer, it makes sense
     * to parallelize the requests to cut down processing time
     */
    final class WsCallResult {
        public Dataset dataset;
        public Webservice webservice;

        public WsCallResult(Dataset ds, Webservice ws) {
            this.dataset = ds;
            this.webservice = ws;
        };
    }

    final class WsCall implements Callable<WsCallResult> {
        public final Dataset dataset;

        public WsCall(Dataset dsIn) {
            this.dataset = dsIn;
        }

        public WsCallResult call() throws Exception {

            Webservice ws = null;
            InputStream responseWs = null;
            String responseWSString = null;

            try {
                responseWSString = ArcGISRestDataStore.InputStreamToString(retrieveJSON("GET",
                        new URL(this.dataset.getWebService().toString()), ArcGISRestDataStore.DEFAULT_PARAMS));
            } catch (IOException e) {
                LOGGER.log(Level.SEVERE, "Error during retrieval of dataset '" + this.dataset.getWebService()
                        + "' " + e.getMessage(), e);
                return null;
            }

            try {
                ws = (new Gson()).fromJson(responseWSString, Webservice.class);
                if (ws == null || ws.getCurrentVersion() == null) {
                    throw (new JsonSyntaxException("Malformed JSON"));
                }
            } catch (JsonSyntaxException e) {
                // Checks whether we have an ArcGIS error message
                Error_ errWS = (new Gson()).fromJson(responseWSString, Error_.class);
                LOGGER.log(Level.SEVERE, "Error during retrieval of dataset " + this.dataset.getWebService()
                        + " " + errWS.getCode() + " " + errWS.getMessage(), e);
                return null;
            }

            // Checks whether the web-service API version is supported and
            // supports GeoJSON
            if (ws.getCurrentVersion() < MINIMUM_API_VERSION || ws.getSupportedQueryFormats().toString()
                    .toLowerCase().contains(FORMAT_JSON.toLowerCase()) == false) {
                LOGGER.log(Level.SEVERE, "Dataset " + this.dataset.getWebService()
                        + " does not support either the API version supported ,or the GeoJSON format");
                return null;
            }

            return new WsCallResult(this.dataset, ws);
        }
    }

    // Builds a list of calls to be made to retrieve FeatureServer web services
    // metadata that support the ReST API (if there are not distribution
    // elements, it
    // is supposed NOT to support it)
    try {
        Collection<WsCall> calls = new ArrayList<WsCall>();
        datasetList.stream().forEach((ds) -> {
            if (ds.getWebService().toString().contains(FEATURESERVER_SERVICE)) {
                calls.add(new WsCall(ds));
            }
        });

        List<Future<WsCallResult>> futures = executor.invokeAll(calls,
                (REQUEST_TIMEOUT * calls.size()) / REQUEST_THREADS, TimeUnit.SECONDS);

        for (Future<WsCallResult> future : futures) {

            WsCallResult result = future.get();

            // Checks whether the lasyer supports query and JSON
            // TODO: I am not quite sure this catches cases in which ESRI JSON is
            // supporte, but NOT GeoJSON
            if (result != null
                    && result.webservice.getSupportedQueryFormats().toLowerCase()
                            .contains(FORMAT_JSON.toLowerCase())
                    && result.webservice.getCapabilities().toLowerCase()
                            .contains(CAPABILITIES_QUERY.toLowerCase())) {
                Name dsName = new NameImpl(namespace.toExternalForm(), result.webservice.getName());
                ContentEntry entry = new ContentEntry(this, dsName);
                this.datasets.put(dsName, result.dataset);
                this.entries.put(dsName, entry);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    // Shutdowsn the executor thread pool
    executor.shutdown();

    // Returns the list of datastore entries
    return new ArrayList<Name>(this.entries.keySet());
}

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

License:Open Source License

/**
 * Parses a Geometry in GeoJSON format//from  w  w  w .  j  a  v a  2s . c om
 * 
 * @return list of arrays with ring coordinates
 * @throws IOException,
 *           JsonSyntaxException, IllegalStateException
 */
public Geometry parseGeometry() throws JsonSyntaxException, IOException, IllegalStateException {

    double[] coords;
    GeometryBuilder builder = new GeometryBuilder();
    GeometryFactory geomFactory = new GeometryFactory();

    // 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 builder.point();
    }

    this.reader.beginObject();

    // Check the presence of feature type
    if (!reader.nextName().equals(FEATURE_TYPE)) {
        throw (new JsonSyntaxException("Geometry type expected"));
    }

    switch (reader.nextString()) {

    case GEOMETRY_POINT:
        this.checkPropertyName(FEATURE_GEOMETRY_COORDINATES);
        coords = this.parsePointCoordinates();
        this.reader.endObject();
        return (Geometry) builder.point(coords[0], coords[1]);

    case GEOMETRY_MULTIPOINT:
        this.checkPropertyName(FEATURE_GEOMETRY_COORDINATES);
        List<double[]> pointCoords = this.parseMultiPointCoordinates();
        ;
        Point[] points = new Point[pointCoords.size()];
        for (int i = 0; i < pointCoords.size(); i++) {
            points[i] = (Point) builder.point(pointCoords.get(i)[0], pointCoords.get(i)[1]);
        }
        this.reader.endObject();
        return (Geometry) new MultiPoint(points, geomFactory);

    case GEOMETRY_LINE:
        this.checkPropertyName(FEATURE_GEOMETRY_COORDINATES);
        coords = this.parseLineStringCoordinates();
        this.reader.endObject();
        return (Geometry) builder.lineString(coords);

    case GEOMETRY_MULTILINE:
        this.checkPropertyName(FEATURE_GEOMETRY_COORDINATES);
        List<double[]> lineArrays = this.parseMultiLineStringCoordinates();
        LineString[] lines = new LineString[lineArrays.size()];
        int i = 0;
        for (double[] array : lineArrays) {
            lines[i++] = builder.lineString(array);
        }
        this.reader.endObject();
        return (Geometry) builder.multiLineString(lines);

    case GEOMETRY_POLYGON:
        this.checkPropertyName(FEATURE_GEOMETRY_COORDINATES);
        List<double[]> rings = this.parsePolygonCoordinates();
        this.reader.endObject();
        return (Geometry) builder.polygon(rings.get(0)); // FIXME: what about
                                                         // holes?

    case GEOMETRY_MULTIPOLYGON:
        this.checkPropertyName(FEATURE_GEOMETRY_COORDINATES);
        List<List<double[]>> polyArrays = this.parseMultiPolygonCoordinates();
        Polygon[] polys = new Polygon[polyArrays.size()];
        int j = 0;
        for (List<double[]> array : polyArrays) {
            polys[j++] = builder.polygon(array.get(0)); // FIXME: what about holes?
        }
        this.reader.endObject();
        return (Geometry) builder.multiPolygon(polys);

    default:
        throw (new JsonSyntaxException("Unrecognized geometry type"));
    }

}