Example usage for org.json.simple JSONValue parseWithException

List of usage examples for org.json.simple JSONValue parseWithException

Introduction

In this page you can find the example usage for org.json.simple JSONValue parseWithException.

Prototype

public static Object parseWithException(String s) throws ParseException 

Source Link

Usage

From source file:org.o3project.odenos.remoteobject.rest.servlet.SubscriptionsServlet.java

@SuppressWarnings("unchecked")
private Map<String, Set<String>> deserialize(String reqBody) {
    JSONObject reqMap;//from   w ww .j  a va2s.com
    try {
        reqMap = (JSONObject) JSONValue.parseWithException(reqBody);
    } catch (Exception e) {
        return null;
    }

    if (reqMap == null) {
        return null;
    }

    Map<String, Set<String>> result = new HashMap<String, Set<String>>();
    for (Entry<String, ?> entry : (Set<Entry<String, ?>>) reqMap.entrySet()) {
        Object value = entry.getValue();
        if (!(value instanceof List<?>)) {
            return null;
        }

        Set<String> eventTypeSet = new HashSet<String>();
        List<?> reqList = (List<?>) value;
        for (Object eventType : reqList) {
            if (!(eventType instanceof String)) {
                return null;
            }
            eventTypeSet.add((String) eventType);
        }

        if (!eventTypeSet.isEmpty()) {
            result.put(entry.getKey(), eventTypeSet);
        }
    }

    return result;
}

From source file:org.ossmeter.repository.model.redmine.importer.RedmineImporter.java

private List<RedmineIssue> getIssue(String id, Platform platform) {
    ArrayList<RedmineIssue> result = new ArrayList<RedmineIssue>();
    int offset = 0;
    int total = 0;
    while (offset <= total) {
        String issuesUrlString = baseRepo + "issues.json?project_id=" + id + "&status_id=*&key=" + token
                + "&offset=" + offset;
        try {/*from   w  w  w .jav a2s . c  o m*/
            InputStream is2 = new URL(issuesUrlString).openStream();
            BufferedReader rd2 = new BufferedReader(new InputStreamReader(is2, Charset.forName("UTF-8")));
            String jsonText2 = readAll(rd2);
            //String jsonText2 = IOUtils.toString(new URL(issuesUrlString).openStream());
            JSONObject obj2 = (JSONObject) JSONValue.parseWithException(jsonText2);
            JSONArray issuesList = (JSONArray) obj2.get("issues");

            for (Object issue : issuesList) {
                //_-_-_-_-_-_-_-_-_-

                RedmineIssue ri = new RedmineIssue();
                ri.setDescription(((JSONObject) issue).get("description").toString());
                String status = ((JSONObject) ((JSONObject) issue).get("status")).get("name").toString();
                ri.setStatus(status);

                if (((JSONObject) issue).get("start_date") != null)
                    ri.setStart_date(((JSONObject) issue).get("start_date").toString());
                if (((JSONObject) issue).get("due_date") != null)
                    ri.setDue_date(((JSONObject) issue).get("due_date").toString());
                if (((JSONObject) issue).get("update_date") != null)
                    ri.setUpdate_date(((JSONObject) issue).get("update_date").toString());
                if (((JSONObject) issue).get("description") != null)
                    ri.setDescription(((JSONObject) issue).get("description").toString());
                String priority = ((JSONObject) issue).get("priority").toString();
                ri.setPriority(priority);

                JSONObject cat = (JSONObject) ((JSONObject) issue).get("category");

                if (cat != null) {
                    RedmineCategory g = new RedmineCategory();
                    g.setName(cat.get("name").toString());
                    ri.setCategory(g);
                }
                JSONObject author = (JSONObject) ((JSONObject) issue).get("author");
                Person p = platform.getProjectRepositoryManager().getProjectRepository().getPersons()
                        .findOneByName(author.get("name").toString());
                if (p != null && p instanceof RedmineUser)
                    ri.setAuthor((RedmineUser) p);
                JSONObject assigned = (JSONObject) ((JSONObject) issue).get("assigned_to");
                if (assigned != null) {
                    Person assignedPerson = platform.getProjectRepositoryManager().getProjectRepository()
                            .getPersons().findOneByName(assigned.get("name").toString());
                    if (assignedPerson != null && assignedPerson instanceof RedmineUser)
                        ri.setAssignedTo((RedmineUser) assignedPerson);
                }
                result.add(ri);

                //_-_-_-_-_-_-_-_-_-

            }
            total = Integer.parseInt(obj2.get("total_count").toString());
            offset += 25;
        } catch (MalformedURLException e) {
            logger.error("Error during import issue for redmine project: " + id);
            break;
        } catch (IOException e) {
            logger.error("Error during import issue for redmine project: " + id);
            break;
        } catch (ParseException e) {
            logger.error("Error during import issue for redmine project: " + id);
            break;
        }
    }
    return result;
}

From source file:org.PrimeSoft.MCPainter.Drawing.Statue.PlayerStatueDescription.java

public String getSkinFile(String playerName) {
    JSONObject responseUUID = HttpUtils.downloadJson(String.format(NAME_TO_UUID_URL, playerName));
    if (responseUUID == null || !responseUUID.containsKey("id")) {
        MCPainterMain.log("Unable to get session UUID for " + playerName);
        return null;
    }//w  ww.  j a v a2  s . c om

    JSONObject profile = HttpUtils.downloadJson(String.format(UUID_TO_PROFILE_URL, responseUUID.get("id")));
    if (profile == null || !profile.containsKey("properties")) {
        MCPainterMain.log("Unable to get player profile for " + playerName);
        return null;
    }

    JSONArray properties = (JSONArray) (profile.get("properties"));
    for (int i = 0; i < properties.size(); i++) {
        JSONObject prop = (JSONObject) properties.get(i);

        if (!prop.containsKey("name") || !prop.get("name").equals("textures") || !prop.containsKey("value")) {
            continue;
        }

        byte[] data = s_base64.decode((String) prop.get("value"));
        if (data == null || data.length <= 0) {
            continue;
        }

        JSONObject textureEntry = null;

        try {
            textureEntry = (JSONObject) JSONValue.parseWithException(new String(data));
        } catch (ParseException ex) {
            continue;
        }

        if (!textureEntry.containsKey("textures")) {
            continue;
        }

        textureEntry = (JSONObject) textureEntry.get("textures");

        if (textureEntry.containsKey("SKIN")) {
            textureEntry = (JSONObject) textureEntry.get("SKIN");
        }

        if (textureEntry.containsKey("url")) {
            return (String) textureEntry.get("url");
        }
    }

    MCPainterMain.log("Unable to detect the texture profile " + playerName);
    return null;
}

From source file:org.PrimeSoft.MCPainter.utils.HttpUtils.java

public static JSONObject downloadJson(String url) {
    String content = downloadPage(url);

    if (content == null || content.isEmpty()) {
        return null;
    }//  w w  w . j ava 2s .  com

    try {
        return (JSONObject) JSONValue.parseWithException(content);
    } catch (ParseException e) {
        MCPainterMain.log("Unable to parse JSON for " + url + " " + e.getMessage());
        return null;
    }
}

From source file:org.wisdom.maven.node.NPM.java

/**
 * Tries to find the main JS file.//from  www . j  a va  2  s . c o  m
 * This search is based on the `package.json` file and it's `bin` entry.
 * If there is an entry in the `bin` object matching `binary`, it uses this javascript file.
 * If the search failed, `null` is returned
 *
 * @return the JavaScript file to execute, null if not found
 */
public File findExecutable(String binary) throws IOException, ParseException {
    File npmDirectory = getNPMDirectory();
    File packageFile = new File(npmDirectory, PACKAGE_JSON);
    if (!packageFile.isFile()) {
        throw new IllegalStateException(
                "Invalid NPM " + npmName + " - " + packageFile.getAbsolutePath() + " does not" + " exist");
    }
    FileReader reader = null;
    try {
        reader = new FileReader(packageFile);
        JSONObject json = (JSONObject) JSONValue.parseWithException(reader);
        JSONObject bin = (JSONObject) json.get("bin");
        if (bin == null) {
            log.error("No `bin` object in " + packageFile.getAbsolutePath());
            return null;
        } else {
            String exec = (String) bin.get(binary);
            if (exec == null) {
                log.error(
                        "No `" + binary + "` object in the `bin` object from " + packageFile.getAbsolutePath());
                return null;
            }
            File file = new File(npmDirectory, exec);
            if (!file.isFile()) {
                log.error(
                        "To execute " + npmName + ", an entry was found for " + binary + " in 'package.json', "
                                + "but the specified file does not exist - " + file.getAbsolutePath());
                return null;
            }
            return file;
        }
    } finally {
        IOUtils.closeQuietly(reader);
    }
}

From source file:org.wisdom.maven.node.NPM.java

/**
 * Utility method to extract the version from a NPM by reading its 'package.json' file.
 *
 * @param npmDirectory the directory in which the NPM is installed
 * @param log          the logger object
 * @return the read version, "0.0.0" if there are not 'package.json' file, {@code null} if this file cannot be
 * read or does not contain the "version" metadata
 *///from www. j a v  a  2 s .  c om
public static String getVersionFromNPM(File npmDirectory, Log log) {
    File packageFile = new File(npmDirectory, PACKAGE_JSON);
    if (!packageFile.isFile()) {
        return "0.0.0";
    }

    FileReader reader = null;
    try {
        reader = new FileReader(packageFile); //NOSONAR
        JSONObject json = (JSONObject) JSONValue.parseWithException(reader);
        return (String) json.get("version");
    } catch (IOException | ParseException e) {
        log.error("Cannot extract version from " + packageFile.getAbsolutePath(), e);
    } finally {
        IOUtils.closeQuietly(reader);
    }

    return null;
}

From source file:project.cs.netinfservice.netinf.node.search.UrlSearchService.java

/**
 * Reads the search results from a HttpResponse.
 * //from  www.  j av a  2 s  .  c om
 * @param response
 *      The HttpResponse
 * @return
 *      A set of the identifiers in the search result
 * @throws Exception
 *      In case extracting the search result failed
 */
private Set<Identifier> handleResponse(HttpResponse response) throws Exception {
    // Make a new set of identifiers for handling the results
    Set<Identifier> resultSet = new HashSet<Identifier>();

    // Get status code from HTTP response
    int statusCode = response.getStatusLine().getStatusCode();

    // If the status code is '200' or HTTP OK
    if (statusCode == HttpStatus.SC_OK) {
        // Get the JSON returned (200 always returns a JSON)
        String jsonString = EntityUtils.toString(response.getEntity());

        // Parse String to JSON Object
        JSONObject json = (JSONObject) JSONValue.parseWithException(jsonString);

        // Go inside the results
        JSONArray results = (JSONArray) json.get("results");

        // Iterate through the results from the NRS search 
        for (Object result : results) {
            JSONObject jsonResult = (JSONObject) result;

            // Get the 'ni' field and the metadata from Results
            String niField = (String) jsonResult.get("ni");
            JSONObject metaField = (JSONObject) jsonResult.get("meta");

            // Extract HASH, HASH ALGORITHM and METADATA from the search results
            String hash = getHashFromResults(niField);
            String hashAlg = getHashAlgFromResults(niField);
            String meta = getMetadataFromResults(metaField);

            // Create a new Identifier with the information extracted 
            Identifier identifier = new IdentifierBuilder(mDatamodelFactory).setHash(hash).setHashAlg(hashAlg)
                    .setMetadata(meta).build();

            // Add result to the set
            resultSet.add(identifier);
        }
    }

    // Return set with all results retrieved from the NRS
    return resultSet;
}

From source file:report.mainReport.java

@SuppressWarnings("deprecation")
private static String sendGet(String url, String type) {
    String genreJson;//ww w  .  ja v a2  s. co m
    String distance = "0";

    //rep = new String[2];
    JSONParser parser = new JSONParser();
    ArrayList polyline = new ArrayList();
    try {
        JSONArray genreArray = null;
        if (type.equalsIgnoreCase("match")) {
            //url = osrm+"loc="+lat1+","+lon1+"&t="+tms1+"loc="+lat2+","+lon2+"&t="+tms2+"&compression=true";
            genreJson = IOUtils.toString(new URL(url));
            JSONObject genreJsonObject = (JSONObject) JSONValue.parseWithException(genreJson);

            genreArray = (JSONArray) genreJsonObject.get("matchings");
            //System.out.println(genreArray);
            if (genreArray == null) {
                System.out.println("JMapData not found in JSON response");
                distance = "0";
            } else {
                // get the first genre
                JSONObject firstGenre = (JSONObject) genreArray.get(0);
                JSONObject routesummary = (JSONObject) firstGenre.get("route_summary");
                distance = routesummary.get("total_distance").toString();
            }
            //rep[0] = distance;
        } else {
            //url = osrm+"loc="+lat1+","+lon1+"&loc="+lat2+","+lon2+"&instructions=false&alt=false";
            genreJson = IOUtils.toString(new URL(url));
            JSONObject genreJsonObject = (JSONObject) JSONValue.parseWithException(genreJson);

            JSONObject firstGenre = (JSONObject) genreJsonObject.get("route_summary");
            //System.out.println(firstGenre.get("total_distance").toString());
            distance = firstGenre.get("total_distance").toString();
        }

    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return distance;
}

From source file:report.mainReport.java

@SuppressWarnings("deprecation")
private static ArrayList<Location> sendGetLoc(String url, String type) {
    String genreJson;/*from   w  w  w .  ja  v a 2s .c o  m*/
    String distance = "0";
    ArrayList rep;

    //rep = new String[2];
    JSONParser parser = new JSONParser();
    ArrayList polyline = new ArrayList();
    try {
        JSONArray genreArray = null;
        if (type.equalsIgnoreCase("match")) {
            //url = "http://192.168.0.12:5000/match?loc="+lat1+","+lon1+"&t="+tms1+"loc="+lat2+","+lon2+"&t="+tms2+"&compression=true";
            genreJson = IOUtils.toString(new URL(url));
            JSONObject genreJsonObject = (JSONObject) JSONValue.parseWithException(genreJson);

            genreArray = (JSONArray) genreJsonObject.get("matchings");
            //System.out.println(genreArray);
            if (genreArray == null) {
                System.out.println("JMapData not found in JSON response");
                distance = "0";
            } else {
                // get the first genre
                JSONObject firstGenre = (JSONObject) genreArray.get(0);
                JSONObject routesummary = (JSONObject) firstGenre.get("route_summary");
                distance = routesummary.get("total_distance").toString();
            }
            //rep[0] = distance;
        } else {
            //url = "http://192.168.0.1:5000/viaroute?loc="+lat1+","+lon1+"&loc="+lat2+","+lon2+"&instructions=false&alt=false";
            genreJson = IOUtils.toString(new URL(url));
            JSONObject genreJsonObject = (JSONObject) JSONValue.parseWithException(genreJson);

            JSONObject firstGenre = (JSONObject) genreJsonObject.get("route_summary");
            //System.out.println(firstGenre.get("total_distance").toString());
            distance = firstGenre.get("total_distance").toString();
            Object obj = parser.parse(genreJson);

            JSONObject jsonObject = (JSONObject) obj;
            String route_geometry = (String) jsonObject.get("route_geometry");
            polyline = decodePoly(route_geometry, distance);
            // Get size and display.
            //int count = polyline.size();
            //System.out.println("Count: " + count);
            //rep[0] = distance;
            //rep[1] = polyline.toString();
        }

    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    if ((Integer.parseInt(distance) / 1000) < DISTANCE_MINI_ENTRE_POINT)
        return null;
    else
        return polyline;
}

From source file:semblance.json.JSONParser.java

public JSONParser(String pathToJson) {
    this.json = null;
    IReader reader = ReaderFactory.getReader(pathToJson);
    String source = reader.load();
    if (!source.isEmpty()) {
        try {//  w w w .  j  av  a2  s .  c  om
            json = (Map<String, Object>) JSONValue.parseWithException(source);
        } catch (ParseException ex) {
            Logger.getLogger(getClass().getName()).log(Level.SEVERE, "Exception loading JSON config", ex);
        }
    } else {
        Logger.getLogger(getClass().getName())
                .severe(String.format("Unable to load JSON config %s", pathToJson));
    }
}