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:edu.vt.vbi.patric.portlets.DataLanding.java

private JSONObject readJsonData(PortletRequest request, String fileUrl) {

    // String url = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + fileUrl;
    String url = "http://localhost" + fileUrl;
    LOGGER.trace("requesting.. {}", url);
    JSONObject jsonData = null;/*  ww  w  . jav  a 2  s . co m*/

    try (CloseableHttpClient client = HttpClientBuilder.create().build()) {
        HttpGet httpRequest = new HttpGet(url);
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        String strResponseBody = client.execute(httpRequest, responseHandler);

        JSONParser parser = new JSONParser();
        jsonData = (JSONObject) parser.parse(strResponseBody);
    } catch (IOException | ParseException e) {
        LOGGER.error(e.getMessage(), e);
    }

    return jsonData;
}

From source file:com.stackmob.example.CRUD.CreateObject.java

@Override
public ResponseToProcess execute(ProcessedAPIRequest request, SDKServiceProvider serviceProvider) {
    String model = "";
    String make = "";
    String year = "";

    LoggerService logger = serviceProvider.getLoggerService(CreateObject.class);
    // JSON object gets passed into the StackMob Logs
    logger.debug(request.getBody());/*from www.jav  a  2s. c  o 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>();

    /* The following try/catch block shows how to properly fetch parameters for PUT/POST operations
     * from the JSON request body
     */
    JSONParser parser = new JSONParser();
    try {
        Object obj = parser.parse(request.getBody());
        JSONObject jsonObject = (JSONObject) obj;

        // Fetch the values passed in by the user from the body of JSON
        model = (String) jsonObject.get("model");
        make = (String) jsonObject.get("make");
        year = (String) jsonObject.get("year");
    } catch (ParseException pe) {
        logger.error(pe.getMessage(), pe);
        return Util.badRequestResponse(errMap);
    }

    if (Util.hasNulls(model, make, year)) {
        return Util.badRequestResponse(errMap);
    }

    feedback.put("model", new SMString(model));
    feedback.put("make", new SMString(make));
    feedback.put("year", new SMInt(Long.parseLong(year)));

    DataService ds = serviceProvider.getDataService();
    try {
        // This is how you create an object in the `car` schema
        ds.createObject("car", new SMObject(feedback));
    } catch (InvalidSchemaException ise) {
        return Util.internalErrorResponse("invalid_schema", ise, errMap); // http 500 - internal server error
    } catch (DatastoreException dse) {
        return Util.internalErrorResponse("datastore_exception", dse, errMap); // http 500 - internal server error
    }

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

From source file:net.sourceforge.fenixedu.presentationTier.Action.externalServices.ISTConnectDA.java

public ActionForward getExternalIds(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    final String externalIds = (String) getFromRequest(request, "externalIds");
    if (doLogin(mapping, actionForm, request, response)) {
        JSONParser parser = new JSONParser();
        final JSONArray extIdsJSONArray = (JSONArray) parser.parse(externalIds);
        final JSONArray jsonArrayResult = new JSONArray();
        for (Object externalId : extIdsJSONArray) {
            jsonArrayResult.add(DomainObjectJSONSerializer
                    .getDomainObject(FenixFramework.getDomainObject((String) externalId)));
        }/*from   w  w  w  .ja v  a2 s. co m*/
        writeJSONObject(response, jsonArrayResult);
    } else {
        response.sendError(404, "Not authorized");
    }
    return null;
}

From source file:capabilities.Display.java

@Override
public String dbSearch(String userAgent) throws Exception {
    String urlInicio, urlCapacidades, urlFim, urlPath;
    String capacidades = "resolution_width%0D%0A" // Largura da tela em pixels
            + "resolution_height%0D%0A" // Altura da tela em pixels
            + "columns%0D%0A" // Numero de colunas apresentadas
            + "rows%0D%0A" // Numero de linhas apresentadas
            + "physical_screen_width%0D%0A" // Largura da tela em milimetros
            + "physical_screen_height%0D%0A" // Altura da tela em milimetros
            + "dual_orientation"; // Se pode ter duas orientacoes

    // Montagem URL de acesso ao Introspector Servlet WURFL
    urlPath = "http://localhost:8080/AdapterAPI/"; // Caminho do projeto
    urlInicio = "introspector.do?action=Form&form=pippo&ua=" + userAgent;
    urlCapacidades = "&capabilities=" + capacidades;
    urlFim = "&wurflEngineTarget=performance&wurflUserAgentPriority=OverrideSideloadedBrowserUserAgent";

    // Conexo com o Servlet
    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpGet getRequest = new HttpGet(urlPath + urlInicio + urlCapacidades + urlFim);
    getRequest.addHeader("accept", "application/json");

    HttpResponse response = httpClient.execute(getRequest);

    if (response.getStatusLine().getStatusCode() != 200) {
        throw new RuntimeException("Failed : HTTP error code : " + response.getStatusLine().getStatusCode());
    }/*from   w ww. j  a  v a 2s .co  m*/

    BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));

    String buffer;
    String dados = "";
    //System.out.println("Output from Server .... \n");
    while ((buffer = br.readLine()) != null) {
        dados += buffer;
    }
    //System.out.println("Sada:\n\t" + dados);

    httpClient.getConnectionManager().shutdown();

    JSONObject my_obj;
    JSONParser parser = new JSONParser();
    my_obj = (JSONObject) parser.parse(dados);
    JSONObject capabilities = (JSONObject) my_obj.get("capabilities");

    return capabilities.toJSONString();
}

From source file:com.mstiles92.plugins.bookrules.localization.LocalizationHandler.java

/**
 * Load the selected language from the language file stored within the jar.
 *
 * @param language the language to load//from  w  ww .j a va2s.c o  m
 * @return true if loading succeeded, false if it failed
 */
public boolean loadLocalization(Language language) {
    String contents;

    InputStream in = LocalizationHandler.class.getResourceAsStream(language.getPath());
    try {
        contents = CharStreams.toString(new InputStreamReader(in, "UTF-8"));
    } catch (IOException e) {
        return false;
    }

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

    try {
        obj = parser.parse(contents);
    } catch (ParseException e) {
        e.printStackTrace();
    }

    if (obj == null) {
        return false;
    } else {
        this.jsonObject = (JSONObject) obj;
        return true;
    }
}

From source file:com.nubits.nubot.pricefeeds.feedservices.YahooPriceFeed.java

@Override
public LastPrice getLastPrice(CurrencyPair pair) {
    long now = System.currentTimeMillis();
    long diff = now - lastRequest;
    if (diff >= refreshMinTime) {
        String url = getUrl(pair);
        String htmlString;/*from w  w w .  j  ava 2  s .  com*/
        try {
            htmlString = Utils.getHTML(url, true);
        } catch (IOException ex) {
            LOG.error(ex.toString());
            return new LastPrice(true, name, pair.getOrderCurrency(), null);
        }
        JSONParser parser = new JSONParser();
        try {
            JSONObject httpAnswerJson = (JSONObject) (parser.parse(htmlString));
            JSONObject query = (JSONObject) httpAnswerJson.get("query");
            JSONObject results = (JSONObject) query.get("results");
            JSONObject rate = (JSONObject) results.get("rate");

            double last = Utils.getDouble((String) rate.get("Rate"));

            lastRequest = System.currentTimeMillis();
            lastPrice = new LastPrice(false, name, pair.getOrderCurrency(),
                    new Amount(last, pair.getPaymentCurrency()));
            return lastPrice;
        } catch (Exception ex) {
            LOG.error(ex.toString());
            lastRequest = System.currentTimeMillis();
            return new LastPrice(true, name, pair.getOrderCurrency(), null);
        }
    } else {
        LOG.warn("Wait " + (refreshMinTime - (System.currentTimeMillis() - lastRequest)) + " ms "
                + "before making a new request. Now returning the last saved price\n\n");
        return lastPrice;
    }
}

From source file:copter.WebSocketServerFactory.java

@Override
public void onMessage(WebSocket conn, String message) {

    JSONObject res = new JSONObject();
    String command = null;/* w  ww  . j a v  a2s .  c o m*/
    JSONObject jsonObj = null;
    try {
        JSONParser parser = new JSONParser();
        Object obj = parser.parse(message);
        jsonObj = (JSONObject) obj;
        command = (String) jsonObj.get("command");

        if (command == null || command.isEmpty()) {
            return;
        }
        if (!command.equals(Constants.PING_COMMAND)) {
            logger.log("websocket message received: " + message);
        }
        switch (command) {
        case Constants.REBOOT_COMMAND:
            res.put("message", LinuxCommandsUtil.getInstance().rebootSystem());
            break;
        case Constants.CAMERA_COMMAND:
            res.put("message", CameraControl.getInstance().doAction(jsonObj));
            break;
        case Constants.GPS_COMMAND:
            res.put("message", GpsdConnector.getInstance().doAction(jsonObj, conn));
            break;
        case Constants.HCSR04_COMMAND:
            res.put("message", HCSR04.getInstance().doAction(jsonObj, conn));
            break;
        case Constants.MPU_COMMAND:
            res.put("message", MPU9150.getInstance().doAction(jsonObj, conn));
            break;
        case Constants.ENGINE_COMMAND:
            Engine.getInstance().doAction(jsonObj, conn);
            break;
        case Constants.GPIO_COMMAND:
            res.put("message", GpioControl.getInstance().doAction(jsonObj));
            break;
        case Constants.PING_COMMAND:
            res.put("status", "ok");
            String ping_id = (String) jsonObj.get("ping_id");
            res.put("ping_id", ping_id);
            break;
        default:
            res.put("message", "Unknown command '" + command + "'.");
            break;
        }

    } catch (Exception ex) {
        String err = "Json parse error: " + ex.getMessage();
        logger.log(err);
        res.put("message", err);
    }
    if (!res.isEmpty()) {
        conn.send(res.toJSONString());
        if (!command.equals(Constants.PING_COMMAND)) {
            logger.log("websocket response: " + res.toJSONString());
        }
    }
}

From source file:Graphite.java

private void parseDashboard() {
    JSONParser parser = new JSONParser();
    Object obj;//  w  w w  .j  a  va2s. c  o m
    try {
        obj = parser.parse(getJsonDashboard());
    } catch (ParseException | IOException e) {
        log.error("Failed to parse Graphite dashboard: " + dashboardUrl, e);
        throw new IllegalArgumentException("invalid dashboard link " + dashboardUrl, e);
    }
    JSONObject jsonObject = (JSONObject) obj;
    JSONArray graphs = (JSONArray) ((JSONObject) jsonObject.get("state")).get("graphs");
    for (Object graph : graphs) {
        String title = ((JSONObject) ((JSONArray) graph).get(1)).get("title").toString();
        String graphUrl = ((String) ((JSONArray) graph).get(2));
        images.add(new Image(baseUrl + graphUrl, title, from, until));
    }
}

From source file:com.stackmob.example.CRUD.UpdateObject.java

@Override
public ResponseToProcess execute(ProcessedAPIRequest request, SDKServiceProvider serviceProvider) {
    String carID = "";
    String year = "";

    LoggerService logger = serviceProvider.getLoggerService(UpdateObject.class);
    logger.debug(request.getBody());//from  w  w w  . j  a v a 2 s  . co m
    Map<String, String> errMap = new HashMap<String, String>();

    /* The following try/catch block shows how to properly fetch parameters for PUT/POST operations
     * from the JSON request body
     */
    JSONParser parser = new JSONParser();
    try {
        Object obj = parser.parse(request.getBody());
        JSONObject jsonObject = (JSONObject) obj;

        // Fetch the values passed in by the user from the body of JSON
        carID = (String) jsonObject.get("car_ID");
        year = (String) jsonObject.get("year");

    } catch (ParseException pe) {
        logger.error(pe.getMessage(), pe);
        return Util.badRequestResponse(errMap, pe.getMessage());
    }

    if (Util.hasNulls(year, carID)) {
        return Util.badRequestResponse(errMap);
    }

    Map<String, SMValue> feedback = new HashMap<String, SMValue>();
    feedback.put("updated year", new SMInt(Long.parseLong(year)));

    DataService ds = serviceProvider.getDataService();
    List<SMUpdate> update = new ArrayList<SMUpdate>();

    /* Create the changes in the form of an Update that you'd like to apply to the object
     * In this case I want to make changes to year by overriding existing values with user input
     */
    update.add(new SMSet("year", new SMInt(Long.parseLong(year))));

    SMObject result;
    try {
        // Remember that the primary key in this car schema is `car_id`
        result = ds.updateObject("car", new SMString(carID), update);
        feedback.put("updated object", result);

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

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

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

public JSONSection(JSONParser p, String data) {
    try {// ww w.  java2 s .co m
        this.obj = (JSONObject) p.parse(data);
    } catch (Exception e) {
        e.printStackTrace();

        this.obj = null;
    }
}