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:applab.search.client.JsonSimpleParser.java

public JsonSimpleParser(Handler progressHandler, Handler responseHandler, InputStream newKeywordStream) {
    this.keywordStream = newKeywordStream;
    this.responseHandler = responseHandler;
    JsonSimpleParser.progressHandler = progressHandler;
    this.keywordHandler = new KeywordParseHandler();
    menuIdsCollection = new ArrayList<String>();
    updatedImages = new ArrayList<String>();
    deletedImages = new ArrayList<String>();

    try {/*from   w ww .ja v  a 2  s  . c o m*/
        this.jsonParser = new JSONParser();
    } catch (FactoryConfigurationError e) {
        // Needed to avoid java warnings, newSAXParser will never throw on Android
    }
}

From source file:com.justgiving.raven.kissmetrics.utils.KissmetricsLocalSchemaExtractor.java

/****
 * This function counts the total occurrences of keys, in the json records files
 *  /*from w  ww .j a v a  2s .c  o m*/
 * @param input_filename path to a json file
 * @return a HashMap with the keys / total counts pairs
 */
private static KeyValueCounter countKeysInJsonRecordsFile(String input_filename) {
    InputStream fis;
    BufferedReader bufferedReader;
    String line;
    JSONParser jsonParser = new JSONParser();
    KeyValueCounter keyValueCounter = new KeyValueCounter();
    String jsonValue = "";
    try {
        fis = new FileInputStream(input_filename);
        bufferedReader = new BufferedReader(new InputStreamReader(fis, Charset.forName("UTF-8")));
        while ((line = bufferedReader.readLine()) != null) {
            JSONObject jsonObject = (JSONObject) jsonParser.parse(line);
            Set<String> keyset = jsonObject.keySet();
            for (String jsonkey : keyset) {
                if (jsonObject.get(jsonkey) != null) {
                    jsonValue = (String) jsonObject.get(jsonkey).toString();
                    if (jsonValue == null || jsonValue == "") {
                        jsonValue = "";
                    }
                    int lenValue = jsonValue.length();
                    keyValueCounter.incrementKeyCounter(jsonkey);
                    keyValueCounter.putValueLength(jsonkey, lenValue);
                } else {
                    if (jsonkey.compareTo("user_agent") != 0) {
                        logger.error("Errot typing to get jsonkey " + jsonkey);
                    }

                }
            }
        }
        bufferedReader.close();
    } catch (ParseException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
    //System.out.println(keyCounter.toString());
    //System.out.println(sortHashByKey(keyCounter));      
    return keyValueCounter;
}

From source file:biz.dfch.j.graylog.plugin.filter.metricsValidation.java

public metricsValidation() throws IOException, URISyntaxException {
    try {//from  w w  w . ja  va2 s.c om
        LOG.debug(String.format("[%d] Initialising plugin ...\r\n", Thread.currentThread().getId()));

        // get config file
        CodeSource codeSource = this.getClass().getProtectionDomain().getCodeSource();
        URI uri = codeSource.getLocation().toURI();

        // String path = uri.getSchemeSpecificPart();
        // path would contain absolute path including jar file name with extension
        // String path = FilenameUtils.getPath(uri.getPath());
        // path would contain relative path (no leading '/' and no jar file name

        String path = FilenameUtils.getPath(uri.getPath());
        if (!path.startsWith("/")) {
            path = String.format("/%s", path);
        }
        String baseName = FilenameUtils.getBaseName(uri.getSchemeSpecificPart());
        if (null == baseName || baseName.isEmpty()) {
            baseName = this.getClass().getPackage().getName();
        }

        // get config values
        configurationFileName = FilenameUtils.concat(path, baseName + ".conf");
        JSONParser jsonParser = new JSONParser();
        LOG.info(String.format("Loading configuration file '%s' ...", configurationFileName));
        Object object = jsonParser.parse(new FileReader(configurationFileName));

        JSONObject jsonObject = (JSONObject) object;
        String pluginPriority = (String) jsonObject.get(DF_PLUGIN_PRIORITY);
        Boolean pluginDropMessage = (Boolean) jsonObject.get(DF_PLUGIN_DROP_MESSAGE);
        Boolean pluginDisabled = (Boolean) jsonObject.get(DF_PLUGIN_DISABLED);
        //            metrics = (HashMap) jsonObject.get("metrics");
        //            String fieldName = "cpu.average";
        //            Set<String> keys = metrics.keySet();
        //            for(String key : keys)
        //            {
        //                Map metric = (Map) metrics.get(key);
        //                LOG.info(String.format("%s [type %s] [range %s .. %s]", key, metric.get("type").toString(), metric.get("minValue").toString(), metric.get("maxValue").toString()));
        //            }
        // set configuration
        Map<String, Object> map = new HashMap<>();
        map.put(DF_PLUGIN_PRIORITY, pluginPriority);
        map.put(DF_PLUGIN_DROP_MESSAGE, pluginDropMessage);
        map.put(DF_PLUGIN_DISABLED, pluginDisabled);
        //map.put(DF_PLUGIN_METRICS, metrics);

        initialize(new Configuration(map));
    } catch (IOException ex) {
        LOG.error(String.format("[%d] Initialising plugin FAILED. Filter will be disabled.\r\n%s\r\n",
                Thread.currentThread().getId(), ex.getMessage()));
        LOG.error("*** " + DF_PLUGIN_NAME + "::dfchBizExecScript() - IOException - Filter will be disabled.");
        ex.printStackTrace();
    } catch (Exception ex) {
        LOG.error(String.format("[%d] Initialising plugin FAILED. Filter will be disabled.\r\n",
                Thread.currentThread().getId()));
        LOG.error("*** " + DF_PLUGIN_NAME + "::dfchBizExecScript() - Exception - Filter will be disabled.");
        ex.printStackTrace();
    }
}

From source file:com.dagobert_engine.core.service.MtGoxApiAdapter.java

/**
 * Get ID key/*from  www  .j ava 2s .  co m*/
 */
public String getIdKey() {
    CurrencyType curr = config.getDefaultCurrency();

    String resultJson = query(MtGoxQueryUtil.create(curr, API_ID_KEY));

    JSONParser parser = new JSONParser();

    try {
        JSONObject root = (JSONObject) (parser.parse(resultJson));
        String result = (String) root.get("result");

        if (!"success".equals(result)) {
            throw new MtGoxException(result);
        }

        String data = (String) root.get("data");
        return data;
    } catch (ParseException ex) {
        logger.log(Level.SEVERE, ex.toString());
        return null;
    }

}

From source file:model.Post_store.java

public static String getpostcontent(int id) {

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

    try {//from  ww  w . j  a  v a 2s.c  om

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

        JSONObject jsonObject = (JSONObject) obj;

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

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

    return content;

}

From source file:net.bashtech.geobot.JSONUtil.java

public static String BOIFloor(String channel) {

    try {/*from  w w w .ja  v  a2s. com*/
        JSONParser parser = new JSONParser();
        Object obj = parser.parse(
                BotManager.getRemoteContent("http://coebot.tv/configs/boir/" + channel.substring(1) + ".json"));

        JSONObject jsonObject = (JSONObject) obj;

        String floor = (String) jsonObject.get("floor");

        return floor;
    } catch (Exception ex) {
        return null;
    }
}

From source file:eg.nileu.cis.nilestore.main.HttpDealer.java

/**
 * Put./*www .j  av  a  2 s. c om*/
 * 
 * @param filepath
 *            the filepath
 * @param url
 *            the url
 * @throws ClientProtocolException
 *             the client protocol exception
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
public static void put(String filepath, String url) throws ClientProtocolException, IOException {
    url = url + (url.endsWith("/") ? "" : "/") + "upload?t=json";
    HttpClient client = new DefaultHttpClient();
    client.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);

    HttpPost post = new HttpPost(url);
    MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

    File file = new File(filepath);
    final double filesize = file.length();

    ContentBody fbody = new FileBodyProgress(file, new ProgressListener() {

        @Override
        public void transfered(long bytes, float rate) {
            int percent = (int) ((bytes / filesize) * 100);
            String bar = ProgressUtils.progressBar("Uploading file to the gateway : ", percent, rate);
            System.err.print("\r" + bar);
            if (percent == 100) {
                System.err.println();
                System.err.println("wait the gateway is processing and saving your file");
            }
        }
    });

    entity.addPart("File", fbody);

    post.setEntity(entity);

    HttpResponse response = client.execute(post);

    if (response != null) {
        System.err.println(response.getStatusLine());
        HttpEntity ht = response.getEntity();
        String json = EntityUtils.toString(ht);
        JSONParser parser = new JSONParser();
        try {
            JSONObject obj = (JSONObject) parser.parse(json);
            System.out.println(obj.get("cap"));
        } catch (ParseException e) {
            System.err.println("Error during parsing the response: " + e.getMessage());
            System.exit(-1);
        }
    } else {
        System.err.println("Error: response = null");
    }

    client.getConnectionManager().shutdown();
}

From source file:com.conwet.silbops.msg.UnadvertiseMsgTest.java

@Test
public void shouldDeserializeOptionalUncovered() throws ParseException {

    // this test covers the case clients are sending unsubscribe
    UnadvertiseMsg msg = new UnadvertiseMsg();
    msg.setAdvertise(new Advertise().attribute("attr1", Type.STRING).attribute("attr2", Type.STRING)
            .attribute("attr3", Type.DOUBLE));

    Advertise covered = new Advertise();
    covered.attribute("attrCov", Type.DOUBLE);
    Set<Advertise> uncovered = new HashSet<>();
    uncovered.add(covered);/*from w w w.  j  a v  a 2s .c  o m*/

    msg.setUncovered(uncovered);
    JSONObject jsonTmp = msg.toJSON();

    // delete uncovered part
    ((JSONObject) jsonTmp.get("payload")).remove("uncovered");
    uncovered.clear();

    String jsonStr = jsonTmp.toJSONString();
    JSONObject json = (JSONObject) new JSONParser().parse(jsonStr);
    UnadvertiseMsg newMsg = (UnadvertiseMsg) UnadvertiseMsg.fromJSON(json);
    assertThat(newMsg).isEqualTo(msg);
    assertThat(newMsg.getUncovered()).isEqualTo(uncovered);
}

From source file:com.example.austin.test.TextActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_text);

    Thread thread = new Thread(new Runnable() {
        @Override//from ww w .j  a v a  2s .c o m
        public void run() {
            try {
                Bundle bundle = getIntent().getExtras();
                Bitmap photo = (Bitmap) bundle.get("photo");
                ByteArrayOutputStream stream1 = new ByteArrayOutputStream();
                photo.compress(Bitmap.CompressFormat.PNG, 100, stream1);
                byte[] fileContent = stream1.toByteArray();

                String license_code = "59D1D7B4-61FD-49EB-A549-C77E08B7103A";
                String user_name = "austincheng16";

                String ocrURL = "http://www.ocrwebservice.com/restservices/processDocument?gettext=true";
                URL url = new URL(ocrURL);

                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setDoOutput(true);
                connection.setDoInput(true);
                connection.setRequestMethod("POST");

                connection.setRequestProperty("Authorization", "Basic "
                        + new String(Base64.encodeBase64((user_name + ":" + license_code).getBytes())));

                connection.setRequestProperty("Content-Type", "application/json");

                connection.setRequestProperty("Content-Length", Integer.toString(fileContent.length));

                try {
                    OutputStream stream = connection.getOutputStream();

                    stream.write(fileContent);
                    stream.close();

                    int httpCode = connection.getResponseCode();

                    if (httpCode == HttpURLConnection.HTTP_OK) {
                        String jsonResponse = GetResponseToString(connection.getInputStream());
                        PrintOCRResponse(jsonResponse);
                    } else {
                        String jsonResponse = GetResponseToString(connection.getErrorStream());
                        JSONParser parser = new JSONParser();
                        JSONObject jsonObj = (JSONObject) parser.parse(jsonResponse);
                        Log.i("austin", "Error Message: " + jsonObj.get("ErrorMessage"));
                    }
                    connection.disconnect();
                } catch (IOException e) {
                    Log.i("austin", "IOException");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
    thread.start();
}

From source file:forumbox.PostingnewpostServlet.java

public void filewrite(String url, String username, String title, String description,
        HttpServletResponse response, String id) throws IOException {

    count++;/*from  ww  w.ja v  a  2s.c  o m*/
    /*   BufferedWriter out ;
       out = new BufferedWriter(new FileWriter(url,true));
       out.write(count+"/"+array[0]+"/"+array[1]+"/"+array[2]+";");
       out.close();
               
               
      }catch (Exception e) {
    System.out.println("Error: " + e.getMessage());
      } */

    JSONObject post = new JSONObject();
    JSONArray comments = new JSONArray();
    JSONArray toapprove = new JSONArray();
    JSONParser parser = new JSONParser();
    JSONObject list = null;

    post.put("title", title);
    post.put("description", description);
    post.put("id", id);
    post.put("username", username);
    //  post.put("comments",comments);
    //  post.put("toapprove",toapprove);

    try {

        Object obj = parser.parse(new FileReader(url + "list.json"));
        list = (JSONObject) obj;

        JSONArray msg = (JSONArray) list.get("list");
        msg.add(id);

        list.remove("list");
        list.put("list", msg);

    } catch (Exception e) {
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.println("Adding new ID is unsuccessful");
        out.println(e);
        out.println("......................");
    }

    try {

        File file = new File(url + id + ".json");
        file.createNewFile();
        BufferedWriter out;
        out = new BufferedWriter(new FileWriter(file));
        out.write(post.toJSONString());
        out.close();

        File fileList = new File(url + "list.json");
        //  fileList.createNewFile();
        // BufferedWriter outin ;
        //  outin = new BufferedWriter(new FileWriter(fileList));
        // outin.write(post.toJSONString());
        FileWriter listwrite = new FileWriter(fileList);
        listwrite.write(list.toJSONString());
        listwrite.flush();
        listwrite.close();
        //outin.close();

    } catch (IOException e) {

        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.println("adding new post is unsuccessful");
        out.println(e);
        out.println("......................");
    }

}