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:com.releasequeue.server.ReleaseQueueServer.java

private Object postJsonRequest(URL url, JSONObject payload) throws IOException {
    HttpPost request = new HttpPost(url.toString());
    setAuthHeader(request);//from  w w w  . j a  v a  2s  .c  o m

    CloseableHttpClient httpClient = HttpClients.createDefault();

    try {
        StringWriter data = new StringWriter();
        payload.writeJSONString(data);

        StringEntity params = new StringEntity(data.toString());
        request.addHeader("content-type", "application/json");
        request.setEntity(params);

        HttpResponse response = httpClient.execute(request);
        StatusLine statusLine = response.getStatusLine();
        int statusCode = statusLine.getStatusCode();
        if (statusCode >= 400) {
            throw new HttpException(statusLine.getReasonPhrase());
        }

        String json_string = EntityUtils.toString(response.getEntity());
        JSONParser parser = new JSONParser();

        return parser.parse(json_string);
    } catch (ParseException pe) {
        throw new RuntimeException("Failed to parse json responce", pe);
    } finally {
        httpClient.getConnectionManager().shutdown();
    }

}

From source file:com.treasure_data.td_import.reader.JSONRecordReader.java

@Override
public void sample(Task task) throws PreparePartsException {
    BufferedReader sampleReader = null;
    try {//  w  ww  .  j  a va 2  s.c  o m
        sampleReader = new BufferedReader(new InputStreamReader(
                task.createInputStream(conf.getCompressionType()), conf.getCharsetDecoder()));

        // read first line only
        line = sampleReader.readLine();
        if (line == null) {
            String msg = String.format("Anything is not read or EOF [line: 1] %s", task.getSource());
            LOG.severe(msg);
            throw new PreparePartsException(msg);
        }

        try {
            JSONParser sampleParser = new JSONParser();
            row = (Map<String, Object>) sampleParser.parse(line);
            if (row == null) {
                String msg = String.format("Anything is not parsed [line: 1] %s", task.getSource());
                LOG.severe(msg);
                throw new PreparePartsException(msg);
            }
        } catch (ParseException e) {
            LOG.log(Level.SEVERE, String.format("Anything is not parsed [line: 1] %s", task.getSource()), e);
            throw new PreparePartsException(e);
        }

        // print first sample record
        printSample();
    } catch (IOException e) {
        LOG.log(Level.SEVERE, "during sample method execution", e);
        throw new PreparePartsException(e);
    } finally {
        if (sampleReader != null) {
            try {
                sampleReader.close();
            } catch (IOException e) {
                LOG.log(Level.SEVERE, "sampling reader cannot be closed", e);
                throw new PreparePartsException(e);
            }
        }
    }
}

From source file:io.personium.engine.source.FsServiceResourceSourceManager.java

/**
 * Get .pmeta in JSON format./*from  w w w  .  j  av  a2  s.c  o  m*/
 * @param metaDirPath Directory path in which meta file to be acquired is stored
 * @return .pmeta in JSON format
 * @throws PersoniumEngineException Meta file not found.
 */
private JSONObject getMetaData(String metaDirPath) throws PersoniumEngineException {
    String separator = "";
    if (!metaDirPath.endsWith(File.separator)) {
        separator = File.separator;
    }
    File metaFile = new File(metaDirPath + separator + ".pmeta");
    JSONObject json = null;
    try (Reader reader = Files.newBufferedReader(metaFile.toPath(), Charsets.UTF_8)) {
        JSONParser parser = new JSONParser();
        json = (JSONObject) parser.parse(reader);
    } catch (IOException | ParseException e) {
        // IO failure or JSON is broken
        log.info("Meta file not found or invalid (" + this.fsPath + ")");
        throw new PersoniumEngineException("500 Server Error",
                PersoniumEngineException.STATUSCODE_SERVER_ERROR);
    }
    return json;
}

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

@Test
public void shouldCreateDocument() throws Exception {
    HistoryType historyType = new HistoryType();
    JSONParser parser = new JSONParser();

    History history = prepareData().get(0);
    HttpEntity document = historyType.createDocument(history);
    JSONObject actual = (JSONObject) parser.parse(EntityUtils.toString(document));
    JSONObject expected = (JSONObject) parser.parse("{\"date\":\"2017-01-14\",\"numericValue\":1.0,"
            + "\"stringValue\":\"1\",\"process\":1,\"type\":0}");
    assertEquals("History JSONObject doesn't match to given JSONObject!", expected, actual);

    history = prepareData().get(1);//from ww w  .  ja  v  a2s  .  c  o  m
    document = historyType.createDocument(history);
    actual = (JSONObject) parser.parse(EntityUtils.toString(document));
    expected = (JSONObject) parser
            .parse("{\"date\":null,\"numericValue\":2.0,\"stringValue\":\"2\"," + "\"process\":2,\"type\":12}");
    assertEquals("History JSONObject doesn't match to given JSONObject!", expected, actual);
}

From source file:com.opensoc.parsing.test.BasicIseParserTest.java

/**
 * Test method for/*w w  w.j av a2  s.c o  m*/
 * {@link com.opensoc.parsing.parsers.BasicIseParser#parse(byte[])}.
 * 
 * @throws IOException
 * @throws Exception
 */
public void testParse() throws ParseException, IOException, Exception {
    for (String inputString : getInputStrings()) {
        JSONObject parsed = parser.parse(inputString.getBytes());
        assertNotNull(parsed);

        System.out.println(parsed);
        JSONParser parser = new JSONParser();

        Map<?, ?> json = null;
        try {
            json = (Map<?, ?>) parser.parse(parsed.toJSONString());
            assertEquals(true, validateJsonData(super.getSchemaJsonString(), json.toString()));
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }
}

From source file:de.uni_koblenz.aggrimm.icp.interfaceAgents.AbstractResultParser.java

/**
 * @param resultJSONString result String that has yet to be parsed to JSON.
 * @param source           from where the results are ("web" or "image").
 * @param skip             integer of manually skipped values.
 *
 * @return parsed <code>IWebResult</code>s in
 *          an <code>IResultsContainer</code>.
 * @throws ParseException           if the {@code resultJSONString} cannot be
 *                                   properly parsed.
 * @throws IllegalArgumentException if {@code source} is neither "web" nor
 *                                   "image".
 *///w  w w . j a v a 2  s.  co m
public IResultsContainer<IResult> parseJSONString(String resultJSONString, String source, int skip)
        throws ParseException {
    if (!source.equals("web") && !source.equals("image")) {
        throw new IllegalArgumentException("The source parameter \"" + source + "\" is unknown.");
    }
    JSONParser parser = new JSONParser();
    JSONObject parsedString = (JSONObject) (parser.parse(resultJSONString));

    return convertToResultContainer(parsedString, source, skip);
}

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

@Test
public void shouldCreateDocument() throws Exception {
    UserGroupType userGroupType = new UserGroupType();
    JSONParser parser = new JSONParser();

    UserGroup userGroup = prepareData().get(0);
    HttpEntity document = userGroupType.createDocument(userGroup);
    JSONObject actual = (JSONObject) parser.parse(EntityUtils.toString(document));
    JSONObject expected = (JSONObject) parser
            .parse("{\"title\":\"Administrator\",\"permission\":1," + "\"users\":[{\"id\":1},{\"id\":2}]}");
    assertEquals("UserGroup JSONObject doesn't match to given JSONObject!", expected, actual);

    userGroup = prepareData().get(1);/*from w  w  w . j a v  a 2  s .co  m*/
    document = userGroupType.createDocument(userGroup);
    actual = (JSONObject) parser.parse(EntityUtils.toString(document));
    expected = (JSONObject) parser.parse("{\"title\":\"Random\",\"permission\":4,\"users\":[]}");
    assertEquals("UserGroup JSONObject doesn't match to given JSONObject!", expected, actual);
}

From source file:com.ibm.bluemix.hack.image.ImageEvaluator.java

@SuppressWarnings("unchecked")
public JSONObject analyzeImage(byte[] buf) throws IOException {

    JSONObject imageProcessingResults = new JSONObject();

    JSONObject creds = VcapServicesHelper.getCredentials("watson_vision_combined", null);

    String baseUrl = creds.get("url").toString();
    String apiKey = creds.get("api_key").toString();
    String detectFacesUrl = baseUrl + "/v3/detect_faces?api_key=" + apiKey + "&version=2016-05-20";
    String classifyUrl = baseUrl + "/v3/classify?api_key=" + apiKey + "&version=2016-05-20";

    OkHttpClient client = new OkHttpClient();

    RequestBody requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM)
            .addFormDataPart("images_file", "sample.jpg", RequestBody.create(MediaType.parse("image/jpg"), buf))
            .build();/* ww  w .  j a  v a 2s .  c o m*/

    Request request = new Request.Builder().url(detectFacesUrl).post(requestBody).build();

    Response response = client.newCall(request).execute();
    String result = response.body().string();

    JSONParser jsonParser = new JSONParser();

    try {
        JSONObject results = (JSONObject) jsonParser.parse(result);
        // since we only process one image at a time, let's simplfy the json 
        // we send to the JSP.
        JSONArray images = (JSONArray) results.get("images");
        if (images != null && images.size() > 0) {
            JSONObject firstImage = (JSONObject) images.get(0);
            JSONArray faces = (JSONArray) firstImage.get("faces");
            imageProcessingResults.put("faces", faces);
        }
    } catch (ParseException e) {
        e.printStackTrace();
    }

    // now request classification
    request = new Request.Builder().url(classifyUrl).post(requestBody).build();

    response = client.newCall(request).execute();
    result = response.body().string();
    try {
        JSONObject results = (JSONObject) jsonParser.parse(result);
        // since we only process one image at a time, let's simplfy the json 
        // we send to the JSP.
        JSONArray images = (JSONArray) results.get("images");
        if (images != null && images.size() > 0) {
            JSONObject firstImage = (JSONObject) images.get(0);
            JSONArray classifiers = (JSONArray) firstImage.get("classifiers");
            imageProcessingResults.put("classifiers", classifiers);
        }
    } catch (ParseException e) {
        e.printStackTrace();
    }

    return imageProcessingResults;
}

From source file:com.ibm.stocator.fs.swift.auth.PasswordScopeAccessProvider.java

/**
 * Authentication logic/*from  www . ja va  2  s  .  c  om*/
 *
 * @return Access JOSS access object
 * @throws IOException if failed to parse the response
 */
public Access passwordScopeAuth() throws IOException {
    InputStreamReader reader = null;
    BufferedReader bufReader = null;
    try {
        JSONObject user = new JSONObject();
        user.put("id", mUserId);
        user.put("password", mPassword);
        JSONObject password = new JSONObject();
        password.put("user", user);
        JSONArray methods = new JSONArray();
        methods.add("password");
        JSONObject identity = new JSONObject();
        identity.put("methods", methods);
        identity.put("password", password);
        JSONObject project = new JSONObject();
        project.put("id", mProjectId);
        JSONObject scope = new JSONObject();
        scope.put("project", project);
        JSONObject auth = new JSONObject();
        auth.put("identity", identity);
        auth.put("scope", scope);
        JSONObject requestBody = new JSONObject();
        requestBody.put("auth", auth);
        HttpURLConnection connection = (HttpURLConnection) new URL(mAuthUrl).openConnection();
        connection.setDoOutput(true);
        connection.setRequestProperty("Accept", "application/json");
        connection.setRequestProperty("Content-Type", "application/json");
        OutputStream output = connection.getOutputStream();
        output.write(requestBody.toString().getBytes());
        int status = connection.getResponseCode();
        if (status != 201) {
            return null;
        }
        reader = new InputStreamReader(connection.getInputStream());
        bufReader = new BufferedReader(reader);
        String res = bufReader.readLine();
        JSONParser parser = new JSONParser();
        JSONObject jsonResponse = (JSONObject) parser.parse(res);

        String token = connection.getHeaderField("X-Subject-Token");
        PasswordScopeAccess access = new PasswordScopeAccess(jsonResponse, token, mPrefferedRegion);
        bufReader.close();
        reader.close();
        connection.disconnect();
        return access;

    } catch (Exception e) {
        if (bufReader != null) {
            bufReader.close();
        }
        if (reader != null) {
            reader.close();
        }
        throw new IOException(e);
    }
}