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:com.stackmob.example.CreateVerifiedUser.java

@Override
public ResponseToProcess execute(ProcessedAPIRequest request, SDKServiceProvider serviceProvider) {

    String username = "";
    String password = "";
    String uuid = "";

    LoggerService logger = serviceProvider.getLoggerService(com.stackmob.example.CreateVerifiedUser.class);
    //Log the JSON object passed to the StackMob Logs
    logger.debug(request.getBody());/*from ww w  .ja v  a  2  s .co m*/

    // I'll be using these maps to print messages to console as feedback to the operation
    Map<String, SMValue> feedback = new HashMap<String, SMValue>();
    Map<String, String> errMap = new HashMap<String, String>();

    JSONParser parser = new JSONParser();
    try {
        Object obj = parser.parse(request.getBody());
        JSONObject jsonObject = (JSONObject) obj;

        //We use the username passed to query the StackMob datastore
        //and retrieve the user's name and email address
        username = (String) jsonObject.get("username");
        password = (String) jsonObject.get("password");
        uuid = (String) jsonObject.get("uuid");
    } catch (ParseException e) {
        return Util.internalErrorResponse("parse_exception", e, errMap); // error 500
    }

    if (Util.hasNulls(username, password, uuid)) {
        return Util.badRequestResponse(errMap);
    }

    // get the StackMob datastore service and assemble the query
    DataService dataService = serviceProvider.getDataService();

    // build a query
    List<SMCondition> query = new ArrayList<SMCondition>();
    query.add(new SMEquals("username", new SMString(username)));
    query.add(new SMEquals("uuid", new SMString(uuid)));

    List<SMObject> result;

    try {
        // return results from unverified user query
        result = dataService.readObjects("user_unverified", query);
        if (result != null && result.size() == 1) {

            SMObject newUserObject;

            try {
                // Create new User
                Map<String, SMValue> objMap = new HashMap<String, SMValue>();
                objMap.put("username", new SMString(username));
                objMap.put("password", new SMString(password));
                newUserObject = dataService.createObject("user", new SMObject(objMap));

                feedback.put("user_created", new SMString(newUserObject.toString()));

            } catch (InvalidSchemaException e) {
                return Util.internalErrorResponse("invalid_schema", e, errMap); // error 500 // http 500 - internal server error
            } catch (DatastoreException e) {
                return Util.internalErrorResponse("datastore_exception", e, errMap); // http 500 - internal server error
            } catch (Exception e) {
                return Util.internalErrorResponse("unknown_exception", e, errMap); // http 500 - internal server error
            }
        }
    } catch (InvalidSchemaException e) {
        return Util.internalErrorResponse("invalid_schema", e, errMap); // error 500 // http 500 - internal server error
    } catch (DatastoreException e) {
        return Util.internalErrorResponse("datastore_exception", e, errMap); // http 500 - internal server error
    } catch (Exception e) {
        return Util.internalErrorResponse("unknown_exception", e, errMap); // http 500 - internal server error
    }

    return new ResponseToProcess(HttpURLConnection.HTTP_OK, feedback);
}

From source file:model.Post_store.java

public static String getposttitle(int id) {

    JSONParser parser = new JSONParser();
    String title = "";

    try {/*  w w  w  .  jav a2  s .com*/

        Object obj = parser.parse(new FileReader(root + "posts/" + id + ".json"));

        JSONObject jsonObject = (JSONObject) obj;

        title = (String) jsonObject.get("title");
        //System.out.println(title);

    } catch (FileNotFoundException e) {
        System.out.println(e);
    } catch (IOException e) {
        System.out.println(e);
    } catch (ParseException e) {
        System.out.println(e);
    }

    return title;

}

From source file:eu.seaclouds.platform.discoverer.crawler.CloudTypes.java

public CloudHarmonyCrawler() {
    /* json parser */
    this.jsonParser = new JSONParser();

    /* client init */
    this.httpclient = HttpClients.createDefault();

    /* mapping booleans */
    this.booleans = new Hashtable<String, String>();
    this.booleans.put("autoScaling", "auto_scaling");
    this.booleans.put("selfHostable", "self_hostable");
    this.booleans.put("apiRestricted", "api_restricted");
    this.booleans.put("autoFailover", "auto_failover");
    this.booleans.put("processPricing", "process_pricing");
    this.booleans.put("vmBased", "vm_based");

    /* mapping numbers */
    this.numbers = new Hashtable<String, String>();
    this.numbers.put("cpuCores", "num_cpus");
    this.numbers.put("localDisks", "num_disks");
    this.numbers.put("memory", "ram");
    this.numbers.put("localStorage", "disk_size");

    /* mapping strings */
    this.strings = new Hashtable<String, String>();
    this.strings.put("localDiskType", "disk_type");
}

From source file:info.mallmc.framework.util.ProfileLoader.java

private void addProperties(GameProfile profile) {
    String uuid = getUUID(skinOwner);
    try {//from ww w. jav a2  s  .c o m
        // Get the name from SwordPVP
        URL url = new URL(
                "https://sessionserver.mojang.com/session/minecraft/profile/" + uuid + "?unsigned=false");
        URLConnection uc = url.openConnection();
        uc.setUseCaches(false);
        uc.setDefaultUseCaches(false);
        uc.addRequestProperty("User-Agent", "Mozilla/5.0");
        uc.addRequestProperty("Cache-Control", "no-cache, no-store, must-revalidate");
        uc.addRequestProperty("Pragma", "no-cache");

        // Parse it
        String json = new Scanner(uc.getInputStream(), "UTF-8").useDelimiter("\\A").next();
        JSONParser parser = new JSONParser();
        Object obj = parser.parse(json);
        JSONArray properties = (JSONArray) ((JSONObject) obj).get("properties");
        for (int i = 0; i < properties.size(); i++) {
            try {
                JSONObject property = (JSONObject) properties.get(i);
                String name = (String) property.get("name");
                String value = (String) property.get("value");
                String signature = property.containsKey("signature") ? (String) property.get("signature")
                        : null;
                if (signature != null) {
                    profile.getProperties().put(name, new Property(name, value, signature));
                } else {
                    profile.getProperties().put(name, new Property(value, name));
                }
            } catch (Exception e) {
                L.ogError(LL.ERROR, Trigger.LOAD, "Failed to apply auth property",
                        "Failed to apply auth property");
            }
        }
    } catch (Exception e) {
        ; // Failed to load skin
    }
}

From source file:org.kitodo.data.index.elasticsearch.type.TemplateTypeTest.java

@Test
//problem with ordering of objects
public void shouldCreateDocument() throws Exception {
    TemplateType templateType = new TemplateType();
    JSONParser parser = new JSONParser();

    Template template = prepareData().get(0);
    HttpEntity document = templateType.createDocument(template);
    JSONObject workpieceObject = (JSONObject) parser.parse(EntityUtils.toString(document));
    String actual = String.valueOf(workpieceObject.get("process"));
    String excepted = "1";
    assertEquals("Template value for process doesn't match to given plain text!", excepted, actual);

    actual = String.valueOf(workpieceObject.get("properties"));
    excepted = "[{\"title\":\"first\",\"value\":\"1\"},{\"title\":\"second\",\"value\":\"2\"}]";
    assertEquals("Template value for properties doesn't match to given plain text!", excepted, actual);

    template = prepareData().get(1);/*from www.  j av a 2  s.  c o  m*/
    document = templateType.createDocument(template);
    workpieceObject = (JSONObject) parser.parse(EntityUtils.toString(document));
    actual = String.valueOf(workpieceObject.get("process"));
    excepted = "2";
    assertEquals("Template value for process doesn't match to given plain text!", excepted, actual);

    actual = String.valueOf(workpieceObject.get("properties"));
    excepted = "[]";
    assertEquals("Template value for properties  doesn't match to given plain text!", excepted, actual);
}

From source file:net.larry1123.util.api.world.blocks.BlockPropertyStorage.java

public BlockPropertyStorage(String json) throws ParseException, ClassNotFoundException {
    // TODO add a bit of validation
    JSONParser parser = new JSONParser();
    JSONObject jsonObject = (JSONObject) parser.parse(json);
    name = (String) jsonObject.get("keyName");
    blockTypeMachineName = (String) jsonObject.get("blockTypeMachineName");
    blockTypeData = (Short) jsonObject.get("blockTypeData");
    try {/*  w w w . j a va2s. co m*/
        byte[] bytes = Base64.decodeBase64((String) jsonObject.get("value"));
        ObjectInputStream objectInputStream = new ObjectInputStream(new ByteArrayInputStream(bytes));
        value = (Comparable) objectInputStream.readObject();
    } catch (IOException e) {
        throw new Error();
        // Not sure how that could happen but I will see what I may need to do
    }
}

From source file:ch.newscron.encryption.EncryptionJUnitTest.java

@Test
public void decodeTest() throws UnsupportedEncodingException, NoSuchAlgorithmException, ParseException {

    // With null string
    assertNull(Encryption.decode(null));

    // With working string
    String stringEncoded = Encryption.encode(inviteData);
    String stringDecoded = Encryption.decode(stringEncoded);
    assertNotNull(stringDecoded);//from w ww .  j  a  v a2  s  .c  om

    JSONParser parser = new JSONParser();
    JSONObject decodedJSON = (JSONObject) parser.parse(stringDecoded);
    inviteData.remove("hash");
    assertTrue(compareJSONObjects(inviteData, decodedJSON));

    // With not appropriate string (invalid)
    String encodedWrong = "vKnxBLGBGdG3PIZlv4w8DpyQfvPhtz_7HayuA6b2-DC1M45RL7LcBc_p2IIXl4eXDphGxx5esQx74kE-txVij1KuqgW6J7pC2yCSIDxVfJkfHdubKRdvC7aFhclXq";
    assertNull(Encryption.decode(encodedWrong));

    // Hash of valid data
    byte[] hash = Encryption.createMD5Hash(inviteData);

    // Corrupt data
    JSONObject inviteData2 = new JSONObject();
    inviteData2.put("custID", "12345");
    inviteData2.put("rew1", "40%");
    inviteData2.put("rew2", "100%"); //!! Changed (in comparison to inviteData)
    inviteData2.put("val", "05/10/2015");

    //Send corrupt data (inviteData2) with valid hash of inviteData.
    //The hash of the corrupt data will differ from the hash of the valid data.
    String corruptEncodedURL = Encryption.encode(inviteData2, new String(hash, "UTF-8"));
    assertTrue(Encryption.decode(corruptEncodedURL) == null); //Indicating corrupt data

}

From source file:MainFrame.CheckConnection.java

private boolean isOnline() throws MalformedURLException, IOException, Exception {
    String url = "http://www.itstepdeskview.hol.es";
    URL obj = new URL(url);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();

    //add reuqest header
    con.setRequestMethod("POST");
    con.setRequestProperty("User-Agent", "Mozilla/5.0");
    con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");

    String urlParameters = "apideskviewer.checkStatus={}";

    // Send post request
    con.setDoOutput(true);/* www  .j ava2s  .com*/
    DataOutputStream wr = new DataOutputStream(con.getOutputStream());
    wr.writeBytes(urlParameters);
    wr.flush();
    wr.close();

    int responseCode = con.getResponseCode();
    //        System.out.println("\nSending 'POST' request to URL : " + url);
    //        System.out.println("Post parameters : " + urlParameters);
    //        System.out.println("Response Code : " + responseCode);

    BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));

    JSONParser parser = new JSONParser();
    Object parsedResponse = parser.parse(in);

    JSONObject jsonParsedResponse = (JSONObject) parsedResponse;

    String s = (String) jsonParsedResponse.get("response");
    if (s.equals("online")) {
        return true;
    } else {
        return false;
    }
}

From source file:buspathcontroller.JSONFileParser.java

public void generateRouteStopsAndPath() {
    JSONParser parser = new JSONParser();
    ArrayList<String> routeList = new ArrayList<String>();
    try {//from www. j a v  a  2 s  . c  o  m
        FileReader reader = new FileReader("/Users/Zhaowei/Desktop/BusPath/allRoutes.txt");
        BufferedReader br = new BufferedReader(reader);
        String line;
        while ((line = br.readLine()) != null) {
            String routeName = line.split(";")[1];
            routeList.add(routeName);
        }
        br.close();
        reader.close();

        Iterator<String> it = routeList.iterator();
        while (it.hasNext()) {
            String routeName = it.next();
            PrintWriter writer = new PrintWriter(
                    "/Users/Zhaowei/Desktop/BusPath/routeInfo/stops/" + routeName + ".txt");
            Object obj = parser.parse(
                    new FileReader("/Users/Zhaowei/Desktop/BusPath/RawJSON/route/" + routeName + ".json"));
            JSONObject jsonObject = (JSONObject) obj;
            JSONObject route = (JSONObject) jsonObject.get("route");
            JSONArray directions = (JSONArray) route.get("directions");
            for (int i = 0; i < directions.size(); i++) {
                JSONObject direction = (JSONObject) directions.get(i);
                writer.println(direction.get("direction"));
                JSONArray stops = (JSONArray) direction.get("stops");
                Iterator iter = stops.iterator();
                while (iter.hasNext()) {
                    JSONObject stop = (JSONObject) iter.next();
                    writer.println(stop.get("stopnumber") + ";" + stop.get("stoptitle") + ";"
                            + stop.get("stoplat") + ";" + stop.get("stoplng"));
                }
            }
            writer.close();
        }

    } catch (Exception e) {
        System.out.println(e);
    }
}

From source file:com.zb.app.biz.service.WeixinTest.java

public void login() {
    httpClient = new HttpClient();
    PostMethod post = new PostMethod(loginUrl);
    post.addParameter(new NameValuePair("username", account));
    post.addParameter(new NameValuePair("pwd", DigestUtils.md5Hex(password)));
    post.addParameter(new NameValuePair("imgcode", ""));
    post.addParameter(new NameValuePair("f", "json"));
    post.setRequestHeader("Host", "mp.weixin.qq.com");
    post.setRequestHeader("Referer", "https://mp.weixin.qq.com/cgi-bin/loginpage?t=wxm2-login&lang=zh_CN");

    try {/*w ww  .  j a v a  2  s .  c  o m*/
        int code = httpClient.executeMethod(post);
        if (HttpStatus.SC_OK == code) {
            String res = post.getResponseBodyAsString();
            JSONParser parser = new JSONParser();
            JSONObject obj = (JSONObject) parser.parse(res);
            JSONObject _obj = (JSONObject) obj.get("base_resp");
            @SuppressWarnings("unused")
            String msg = (String) _obj.get("err_msg");
            String redirect_url = (String) obj.get("redirect_url");
            Long errCode = (Long) _obj.get("ret");
            if (0 == errCode) {
                isLogin = true;
                token = StringUtils.substringAfter(redirect_url, "token=");
                if (null == token) {
                    token = StringUtils.substringBetween(redirect_url, "token=", "&");
                }
                StringBuffer cookie = new StringBuffer();
                for (Cookie c : httpClient.getState().getCookies()) {
                    cookie.append(c.getName()).append("=").append(c.getValue()).append(";");
                }
                this.cookiestr = cookie.toString();
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}