Example usage for org.json.simple.parser JSONParser parse

List of usage examples for org.json.simple.parser JSONParser parse

Introduction

In this page you can find the example usage for org.json.simple.parser JSONParser parse.

Prototype

public Object parse(Reader in) throws IOException, ParseException 

Source Link

Usage

From source file:models.ACLRole.java

/**
 * @return never null// w w  w . ja v  a 2  s.  co  m
 */
public List<String> getPrivilegesList() {
    if (privileges == null) {
        return new ArrayList<String>(1);
    }
    if (privileges.trim().equals("")) {
        return new ArrayList<String>(1);
    }
    JSONParser jp = new JSONParser();
    try {
        JSONArray ja = (JSONArray) jp.parse(privileges);
        if (ja.size() == 0) {
            return new ArrayList<String>(1);
        }

        ArrayList<String> result = new ArrayList<String>();
        for (Object o : ja) {
            result.add((String) o);
        }

        return result;
    } catch (Exception e) {
        Log2.log.error("Can't extract privileges from DB", e, new Log2Dump("raw privileges", privileges));
        return new ArrayList<String>(1);
    }

}

From source file:models.ACLRole.java

/**
 * @return never null// w w w .jav a2s .co  m
 */
public List<String> getFunctionalitiesList() {
    if (functionalities == null) {
        return new ArrayList<String>(1);
    }
    if (functionalities.trim().equals("")) {
        return new ArrayList<String>(1);
    }
    JSONParser jp = new JSONParser();
    try {
        JSONArray ja = (JSONArray) jp.parse(functionalities);
        if (ja.size() == 0) {
            return new ArrayList<String>(1);
        }

        ArrayList<String> result = new ArrayList<String>();
        for (Object o : ja) {
            result.add((String) o);
        }

        return result;
    } catch (Exception e) {
        Log2.log.error("Can't extract functionalities from DB", e,
                new Log2Dump("raw functionalities", functionalities));
        return new ArrayList<String>(1);
    }
}

From source file:com.Jax.GenericResource.java

@POST
@Consumes(MediaType.APPLICATION_JSON)//from   ww w . j  a v  a2s.c  o m
@Produces(MediaType.APPLICATION_JSON)
@Path("/post")
public void createProduct(String content) throws ParseException, SQLException {
    JSONParser parser = new JSONParser();
    JSONObject json = (JSONObject) parser.parse(content);

    Object id = json.get("id");
    String newProductID = id.toString();
    int productID = Integer.parseInt(newProductID);

    Object newName = json.get("newName");
    String name = newName.toString();

    Object newDescription = json.get("newDescription");
    String description = newDescription.toString();

    Object qty = json.get("qty");
    String newQty = qty.toString();
    int quantity = Integer.parseInt(newQty);

    Statement stmt = con.createStatement();
    String query = "INSERT INTO products VALUES('" + productID + "','" + newName + "','" + newDescription
            + "','" + quantity + "')";
    stmt.executeUpdate(query);
}

From source file:com.Jax.GenericResource.java

@DELETE
@Consumes(MediaType.APPLICATION_JSON)/*  w  w  w.  j a  v a2s  .  c  om*/
@Produces(MediaType.APPLICATION_JSON)
@Path("/delete")
public void deleteProduct(String content) throws ParseException, SQLException {

    JSONParser parser = new JSONParser();
    JSONObject json = (JSONObject) parser.parse(content);

    Object id = json.get("id");
    String newProductID = id.toString();
    int productID = Integer.parseInt(newProductID);

    Object newName = json.get("newName");
    String name = newName.toString();

    Object newDescription = json.get("newDescription");
    String description = newDescription.toString();

    Object qty = json.get("qty");
    String newQty = qty.toString();
    int quantity = Integer.parseInt(newQty);

    Statement stmt = con.createStatement();
    String query = "DELETE FROM products WHERE productID =" + productID;
    stmt.executeUpdate(query);
}

From source file:edu.usc.polar.NLTKNERRecogniser.java

/**
 * recognises names of entities in the text
 * @param text text which possibly contains names
 * @return map of entity type -> set of names
 *///w  w  w .  j  a  v  a 2s .  c  o m
public Map<String, Set<String>> recognise(String text) {
    Map<String, Set<String>> entities = new HashMap<>();
    try {
        String url = restHostUrlStr;
        if (!url.equals(""))
            url = url + "/nltk";
        else
            url = "http://localhost:8881/";
        System.out.print(url);
        Response response = WebClient.create(url).accept(MediaType.TEXT_HTML).post(text);
        int responseCode = response.getStatus();
        System.out.print(url + "--" + responseCode);
        if (responseCode == 200) {

            String result = response.readEntity(String.class);
            System.out.println("Printing response Snehal" + result);
            ;

            JSONParser parser = new JSONParser();
            JSONObject j = (JSONObject) parser.parse(result);
            Set s = entities.put("NAMES", new HashSet((Collection) j.get("names")));
        }
    } catch (Exception e) {
        LOG.debug(e.getMessage(), e);
    }
    ENTITY_TYPES.clear();
    ENTITY_TYPES.addAll(entities.keySet());
    return entities;
}

From source file:alexaactions.SmartThingsAgent.java

SmartThingsAgent() {
    client = "8ecfcc6e-b07b-487d-815f-9494b1789ac5";
    access_token = "10ddc55b-d266-47f5-9dc7-6f9b71e73094";
    endpoints_url = "https://graph.api.smartthings.com/api/smartapps/endpoints/" + client + "?access_token="
            + access_token;/* w  ww .j av a 2  s.co m*/
    smartthings = new RESTCaller();
    String endp = getEndpoints();

    Object obj = null;
    JSONParser parser = new JSONParser();

    try {
        obj = parser.parse(endp);
    } catch (ParseException ex) {
        Logger.getLogger(SmartThingsAgent.class.getName()).log(Level.SEVERE, null, ex);
    }

    endpoints = (JSONArray) obj;
    System.out.println(endpoints);
}

From source file:hoot.services.nativeInterfaces.ProcessStreamInterfaceTest.java

@Test
@Category(UnitTest.class)
public void testcreateScriptCmd() throws Exception {
    //private String createScriptCmd(JSONObject cmd)
    hoot.services.controllers.wps.ETLProcessletTest etlTest = new hoot.services.controllers.wps.ETLProcessletTest();
    String sParam = etlTest.generateJobParam();
    JSONParser parser = new JSONParser();
    JSONObject command = (JSONObject) parser.parse(sParam);

    ProcessStreamInterface ps = new ProcessStreamInterface();

    Class[] cArg = new Class[1];
    cArg[0] = JSONObject.class;
    Method method = ProcessStreamInterface.class.getDeclaredMethod("createScriptCmdArray", cArg);
    method.setAccessible(true);/*  www .  j av  a 2s  .  c  o m*/
    command.put("jobId", "123-456-789");
    String[] ret = (String[]) method.invoke(ps, command);
    String commandStr = ArrayUtils.toString(ret);

    String expected = "";

    try {
        String coreScriptPath = HootProperties.getProperty("coreScriptPath");

        String coreOutputPath = HootProperties.getProperty("coreScriptOutputPath");

        String ETLMakefile = HootProperties.getInstance().getProperty("ETLMakefile",
                HootProperties.getDefault("ETLMakefile"));
        String makePath = coreScriptPath + "/" + ETLMakefile;

        //[make, -f, /project/hoot/scripts/makeetl, translation=/test/file/test.js, INPUT_TYPE=OSM, INPUT=/test/file/INPUT.osm,  jobid=123-456-789]
        expected = "{make,-f," + makePath
                + ",translation=/test/file/test.js,INPUT_TYPE=OSM,INPUT=/test/file/INPUT.osm";
        expected += ",jobid=123-456-789";

        String dbname = HootProperties.getProperty("dbName");
        String userid = HootProperties.getProperty("dbUserId");
        String pwd = HootProperties.getProperty("dbPassword");
        String host = HootProperties.getProperty("dbHost");
        String dbUrl = "postgresql://" + userid + ":" + pwd + "@" + host + "/" + dbname;
        expected += ",DB_URL=" + dbUrl + "}";

    } catch (IOException e) {

    }

    Assert.assertEquals(expected, commandStr);

}

From source file:com.respam.comniq.models.OMDBParser.java

public void requestOMDB(String movie, String year) {
    String imageURL;//ww  w  .  ja va 2 s  .com

    // Location for downloading and storing thumbnails
    String path = System.getProperty("user.home") + File.separator + "comniq" + File.separator + "output"
            + File.separator + "thumbnails";
    File userOutDir = new File(path);

    // Create Thumbnails directory if not present
    if (userOutDir.mkdirs()) {
        System.out.println(userOutDir + " was created");
    }

    // Connect to OMDB API and fetch details
    try {
        // Proxy details
        HttpHost proxy = new HttpHost("web-proxy.in.hpecorp.net", 8080, "http");

        //            HttpClient client = HttpClientBuilder.create().build();

        // Start of proxy client
        DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy);
        CloseableHttpClient client = HttpClients.custom().setRoutePlanner(routePlanner).build();
        // End of proxy client

        String uri = "http://www.omdbapi.com/?t=" + URLEncoder.encode(movie) + "&y=" + year;
        uri = uri.replace(" ", "%20");
        HttpGet request = new HttpGet(uri);
        HttpResponse response = client.execute(request);
        String json = EntityUtils.toString(response.getEntity());
        JSONParser parser = new JSONParser();
        JSONObject jsonObject = (JSONObject) parser.parse(json);

        // Excluding Non Movies
        if (null != jsonObject.get("Title")) {
            movieInfo.add(jsonObject);

            // Download the thumbnails if Poster URL present
            if (null != jsonObject.get("Poster")) {
                imageURL = ((String) jsonObject.get("Poster"));
                System.out.println(imageURL);
                URL thumbnail = new URL(imageURL);
                ReadableByteChannel rbc = Channels.newChannel(thumbnail.openStream());
                FileOutputStream fos = new FileOutputStream(
                        path + File.separator + jsonObject.get("Title") + ".jpg");
                fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
            }
        }

    } catch (ParseException | IOException | UnsupportedOperationException e) {
        e.printStackTrace();
    }
}

From source file:hoot.services.controllers.job.ProcessJobRunnable.java

private void processCommand() throws Exception {
    logger.debug("Processing job: {}", jobId);

    jobStatusManager.addJob(jobId);/*w ww.ja  v a 2s.c o m*/

    JSONObject command = null;
    try {
        JSONParser parser = new JSONParser();
        command = (JSONObject) parser.parse(params);

        //log.debug(JsonUtils.objectToJson(command));
        JSONObject result = processJob(jobId, command);
        //log.debug(JsonUtils.objectToJson(result));

        String warnings = null;
        Object oWarn = result.get("warnings");
        if (oWarn != null) {
            warnings = oWarn.toString();
        }

        String statusDetail = "";
        if (warnings != null) {
            statusDetail += "WARNINGS: " + warnings;
        }

        Map<String, String> params = paramsToMap(command);
        if (params.containsKey("writeStdOutToStatusDetail")
                && Boolean.parseBoolean(params.get("writeStdOutToStatusDetail"))) {
            statusDetail += "INFO: " + result.get("stdout");
        }

        if (StringUtils.trimToNull(statusDetail) != null) {
            jobStatusManager.setComplete(jobId, statusDetail);
        } else {
            jobStatusManager.setComplete(jobId);
        }
    } catch (Exception e) {
        jobStatusManager.setFailed(jobId, e.getMessage());
        throw e;
    } finally {
        logger.debug("End process Job: {}", jobId);
    }
}

From source file:com.acc.util.InstagramClient.java

private String processJson(final String instagramOutputJson) {

    String profilePic = null;//w  w w.jav  a 2 s  .c  om

    final JSONParser instagramOutputJsonParser = new JSONParser();
    try {

        final JSONObject instagramOutputJsonObject = (JSONObject) instagramOutputJsonParser
                .parse(instagramOutputJson);
        final JSONObject instagramUser = (JSONObject) instagramOutputJsonObject.get("user");
        profilePic = (String) instagramUser.get("profile_picture");

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

    return profilePic;
}