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

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

Introduction

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

Prototype

JSONParser

Source Link

Usage

From source file:de.Keyle.MyPet.util.configuration.ConfigurationJSON.java

public boolean load() {
    config = new JSONObject();
    BufferedReader reader = null;
    try {/*from  w  ww  .j a v a 2  s.c  o m*/
        reader = new BufferedReader(new FileReader(jsonFile));
        JSONParser parser = new JSONParser();
        Object obj = parser.parse(reader);
        config = (JSONObject) obj;
    } catch (ParseException e) {
        MyPetLogger.write(ChatColor.RED + "Could not parse/load " + jsonFile.getName());
        DebugLogger.warning("Could not parse/load " + jsonFile.getName());
        return false;
    } catch (Exception e) {
        e.printStackTrace();
        DebugLogger.printThrowable(e);
        return false;
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException ignored) {
            }
        }
    }
    return true;
}

From source file:cqels_shim.StdinStream.java

/**
 * start listening to stdin and forwarding to cqels
 *///from  w  w w . j  av  a2s . com
public void run() {
    try {
        JSONParser parser = new JSONParser();
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        String line;

        while ((line = reader.readLine()) != null && !stop) {
            try {
                Object obj = parser.parse(line);
                JSONArray array = (JSONArray) obj;

                //stream the triple
                stream(n((String) array.get(0)), n((String) array.get(1)), n((String) array.get(2)));
            } catch (ParseException pe) {
                System.err.println("Error when parsing input, incorrect JSON.");
            }

            if (sleep > 0) {
                try {
                    Thread.sleep(sleep);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:me.wxwsk8er.Knapsack.Configuration.JSONSection.java

@Override
public ConfigurationSection createSection(String name, HashMap<?, ?> map) {
    obj.put(name, map);//from  w w  w .  j  a v a2  s  . com

    return new JSONSection(new JSONParser(), obj.get(name).toString());
}

From source file:m.dekmak.License.java

public String validate() {
    String msg = "";
    URL location = License.class.getProtectionDomain().getCodeSource().getLocation();
    String url = location.getFile();
    String path = url.substring(0, url.length() - 38);
    String licensePath = path + "license";
    File f = new File(licensePath);
    if (f.exists() && !f.isDirectory()) {
        JSONParser parser = new JSONParser();
        try {/*  w w w.ja va  2  s  .c o  m*/
            Object obj = parser.parse(new FileReader(licensePath));
            JSONObject jsonObject = (JSONObject) obj;
            String client = (String) jsonObject.get("client");
            if (client == null || client.equals("")) {
                msg = "Invalid license (client not defined)";
            } else {
                String product = (String) jsonObject.get("product");
                if (product == null || product.equals("")) {
                    msg = "Invalid license (product not defined)";
                } else {
                    String nbOfUsers = (String) jsonObject.get("nbOfUsers");
                    if (nbOfUsers == null || nbOfUsers.equals("")) {
                        msg = "Invalid license (Nb Of Users not defined)";
                    } else {
                        String expiresOn = (String) jsonObject.get("expiresOn");
                        if (expiresOn == null || expiresOn.equals("")) {
                            msg = "Invalid license (Expires on date not defined)";
                        } else {
                            Encryptor encr = new Encryptor(client);
                            String license = (String) jsonObject.get("license");
                            if (license == null || license.equals("")) {
                                msg = "Invalid license (license not defined)";
                            } else {
                                product = encr.decrypt(product);
                                nbOfUsers = encr.decrypt(nbOfUsers);
                                expiresOn = encr.decrypt(expiresOn);
                                license = encr.decrypt(license);
                                if (license.equals(client)) {
                                    setExpiresOn(expiresOn);
                                    setNbOfUsers(nbOfUsers);
                                    setClient(client);
                                    setProduct(product);
                                    msg = "success";
                                } else {
                                    msg = "Invalid license";
                                }
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            msg = "Invalid license for given client";
        }
    } else {
        msg = "License file not exists";
    }

    return msg;
}

From source file:net.BiggerOnTheInside.Knapsack.configuration.JSONConfiguration.java

/**
 * @param string Does this configuration use string parsing or file parsing?
 *//*w w w  . j ava2 s  .  c o m*/
@Override
protected void init(boolean string) {
    this.fileParser = new JSONParser();
    this.stringParser = new JSONParser();

    if (!string) {
        if (!remote) {
            try {
                this.jsonData = fileParser.parse(new FileReader(Knapsack.getInstance().getFolderPath()));
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            try {
                this.stringData = RemoteUtil.readUrl(filePath);
                this.jsonData = stringParser.parse(stringData);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    } else {
        try {
            this.jsonData = stringParser.parse(stringData);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    this.jsonObject = (JSONObject) jsonData;
}

From source file:emcali.ami.control.webservice.IPTVAMIWebService.java

/**
 * This is a sample web service operation
 *
 * @param args//  ww  w .  j  a  va 2  s  .co m
 * @return
 */
@WebMethod(operationName = "execute")
public String execute(@WebParam(name = "args") String args) {
    JSONObject jsonResponse = new JSONObject();
    try {
        JSONParser parser = new JSONParser();
        Object obj = parser.parse(args);
        JSONObject jsonRequest = (JSONObject) obj;

        String user = (String) jsonRequest.get("user");
        String password = (String) jsonRequest.get("password");

        Credentials credentials = new Credentials();
        String message = credentials.authenticate(user, password);

        switch (message) {
        case "user unauthorized":
            jsonResponse.put("type", "error");
            jsonResponse.put("message", message);
            break;

        case "wrong password":
            jsonResponse.put("type", "error");
            jsonResponse.put("message", message);
            break;

        case "success":
            jsonResponse.put("type", "info");
            jsonResponse.put("message", message);

            if (((String) jsonRequest.get("command")).equals("getData")) {
                jsonResponse = this.getData(jsonRequest, jsonResponse);
            }
            break;
        }

        return jsonResponse.toJSONString();

    } catch (ParseException ex) {
        jsonResponse.put("type", "error");
        jsonResponse.put("message", "JSON Format error: " + ex.getMessage());

        return jsonResponse.toJSONString();
    }
}

From source file:at.uni_salzburg.cs.ckgroup.cscpp.mapper.algorithm.VehicleStatusTestCase.java

@Test
public void testCase01() throws ParseException {
    String status = "{\"vehicle.id\":\"b2345527-2796-4ea9-b500-d842d6f2b638\",\"state\":\"active\",\"latitude\":47.82211311,\"longitude\":13.04076076,\"altitude\":30.0,"
            + "\"tolerance\":1.2,\"actions\":[\"photo\"]}";
    @SuppressWarnings("serial")
    Set<String> expectedSensors = new HashSet<String>() {
        {//from  w  w  w.  java 2  s.com
            add("photo");
        }
    };

    JSONParser parser = new JSONParser();
    VehicleStatus s = new VehicleStatus((JSONObject) parser.parse(status));
    Assert.assertEquals("b2345527-2796-4ea9-b500-d842d6f2b638", s.getId());
    Assert.assertEquals("active", s.getState().toString().toLowerCase());
    Assert.assertEquals(47.82211311, s.getPosition().getLatitude(), 1E-9);
    Assert.assertEquals(13.04076076, s.getPosition().getLongitude(), 1E-9);
    Assert.assertEquals(30.0, s.getPosition().getAltitude(), 1E-9);
    Assert.assertEquals(1.2, s.getTolerance(), 1E-9);
    Assert.assertTrue(s.getActions().containsAll(expectedSensors));
    Assert.assertTrue(expectedSensors.containsAll(s.getActions()));
    System.out.println("testCase01-1: " + s.toJSONString());

    s = new VehicleStatus((JSONObject) parser.parse(s.toJSONString()));
    Assert.assertEquals("b2345527-2796-4ea9-b500-d842d6f2b638", s.getId());
    Assert.assertEquals("active", s.getState().toString().toLowerCase());
    Assert.assertEquals(47.82211311, s.getPosition().getLatitude(), 1E-9);
    Assert.assertEquals(13.04076076, s.getPosition().getLongitude(), 1E-9);
    Assert.assertEquals(30.0, s.getPosition().getAltitude(), 1E-9);
    Assert.assertEquals(1.2, s.getTolerance(), 1E-9);
    Assert.assertTrue(s.getActions().containsAll(expectedSensors));
    Assert.assertTrue(expectedSensors.containsAll(s.getActions()));
}

From source file:com.best.otp.CLegTo.java

String getLegTo() {
    try {// w ww. j  av  a 2  s . co m
        if (m_legJsonObject != null) {
            Object legToObject = m_legJsonObject.get("to");
            if (legToObject != null) {
                legToJsonObject = (JSONObject) legToObject;
                if (legToJsonObject.get("name") != null)
                    LegToName = legToJsonObject.get("name").toString();

                if (legToJsonObject.get("geometry") != null)
                    LegToGeometry = legToJsonObject.get("geometry").toString();
                String LegToGeometryObject = legToJsonObject.get("geometry").toString();
                JSONObject jsonobj = (JSONObject) new JSONParser().parse(LegToGeometryObject);

                legToStopCode = legToJsonObject.get("stopCode");
                legToArrival = legToJsonObject.get("arrival");
                legToDeparture = legToJsonObject.get("departure");
                legToOrig = legToJsonObject.get("orig");
                legToZoneId = legToJsonObject.get("zoneId");

                if (legToJsonObject.get("lon") != null)
                    legToLon = Double.valueOf(legToJsonObject.get("lon").toString());

                if (legToJsonObject.get("lat") != null)
                    legToLat = Double.valueOf(legToJsonObject.get("lat").toString());
                LegToGeometryTypeObject = jsonobj.get("type");
                if (LegToGeometryTypeObject != null)
                    LegToGeometryType = (LegToGeometryTypeObject.toString());

                LegToGeometrycoordinatesObject = jsonobj.get("coordinates");
                if (LegToGeometrycoordinatesObject != null)
                    LegToGeometrycoordinates = (LegToGeometrycoordinatesObject).toString();

                System.out.println(LegToGeometryType + " LegToGeometryType");
                System.out.println(LegToGeometryPoint + " LegToGeometryPoint");
                System.out.println(LegToGeometrycoordinates + " LegToGeometrycoordinate");

                legToStopId = new CLegToStopId(legToJsonObject);
                legToStopId.getlegToStopId();
            }
        }
    } catch (Exception e) {
        System.out.println(e);
    }
    return (LegToName);
}

From source file:Bing.java

/**
 *
 * @param query - query to use for the search
 * @return - a json array of results. each contains a title, description, url,
 * and some other metadata that can be easily extracted since its in json format
 *///from   www.j a  v a 2  s  .c  om
public static JSONArray search(String query) {
    try {
        query = "'" + query + "'";
        String encodedQuery = URLEncoder.encode(query, "UTF-8");
        System.out.println(encodedQuery);
        //            URL url = new URL("https://api.datamarket.azure.com/Bing/Search/v1/Composite?Sources=%27web%27&Query=%27car%27");
        //            URL url = new URL("http://csb.stanford.edu/class/public/pages/sykes_webdesign/05_simple.html");
        String webPage = "https://api.datamarket.azure.com/Bing/Search/v1/Composite?Sources=%27web%27&Query="
                + encodedQuery + "&$format=JSON";
        String name = "6604d12c-3e89-4859-8013-3132f78c1595";
        String password = "cefgNRl3OL4PrJJvssxkqLw0VKfYNCgyTe8wNXotUmQ";

        String authString = name + ":" + password;
        System.out.println("auth string: " + authString);
        byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
        String authStringEnc = new String(authEncBytes);
        System.out.println("Base64 encoded auth string: " + authStringEnc);

        URL url = new URL(webPage);
        URLConnection urlConnection = url.openConnection();
        urlConnection.setRequestProperty("Authorization", "Basic " + authStringEnc);

        BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
        String inputLine;
        StringBuilder response = new StringBuilder();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine).append("\n");
        }

        in.close();
        JSONParser parser = new JSONParser();
        JSONArray arr = (JSONArray) ((JSONObject) ((JSONObject) parser.parse(response.toString())).get("d"))
                .get("results");
        JSONObject obj = (JSONObject) arr.get(0);
        JSONArray out = (JSONArray) obj.get("Web");

        return out;

        //

    } catch (MalformedURLException ex) {
        Logger.getLogger(Bing.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(Bing.class.getName()).log(Level.SEVERE, null, ex);
    } catch (ParseException ex) {
        Logger.getLogger(Bing.class.getName()).log(Level.SEVERE, null, ex);
    }
    return null;
}

From source file:de.fraunhofer.iosb.tc_lib_helloworld.HelloWorldTcParam.java

public HelloWorldTcParam(final String paramJson) throws TcInconclusive {
    JSONParser jsonParser = new JSONParser();
    JSONObject jsonObject;//  w w w .  ja  va  2  s . c om
    try {
        jsonObject = (JSONObject) jsonParser.parse(paramJson);
        // get a String from the JSON object
        federation_name = (String) jsonObject.get("federationName");
        if (federation_name == null) {
            throw new TcInconclusive("The key  federationName  was not found");
        }
        // get a String from the JSON object
        rtiHost = (String) jsonObject.get("rtiHostName");
        if (rtiHost == null) {
            throw new TcInconclusive("The key  rtiHostName  was not found");
        }
        settingsDesignator = "crcAddress=" + this.rtiHost;
        // get a String from the JSON object
        sutFederate = (String) jsonObject.get("sutFederateName");
        if (sutFederate == null) {
            throw new TcInconclusive("The key  sutFederateName  was not found");
        }
    } catch (ParseException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    this.urls[0] = this.getClass().getClassLoader().getResource("HelloWorld.xml");
}