Example usage for org.json.simple JSONValue parse

List of usage examples for org.json.simple JSONValue parse

Introduction

In this page you can find the example usage for org.json.simple JSONValue parse.

Prototype

public static Object parse(String s) 

Source Link

Usage

From source file:net.drgnome.virtualpack.util.Util.java

public static boolean hasUpdate(int projectID, String version) {
        try {//from  ww w. j  a  v  a2  s .  c  om
            HttpURLConnection con = (HttpURLConnection) (new URL(
                    "https://api.curseforge.com/servermods/files?projectIds=" + projectID)).openConnection();
            con.setConnectTimeout(5000);
            con.setRequestMethod("GET");
            con.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; JVM)");
            con.setRequestProperty("Pragma", "no-cache");
            con.connect();
            JSONArray json = (JSONArray) JSONValue.parse(new InputStreamReader(con.getInputStream()));
            String[] cdigits = ((String) ((JSONObject) json.get(json.size() - 1)).get("name")).toLowerCase()
                    .split("\\.");
            String[] vdigits = version.toLowerCase().split("\\.");
            int max = vdigits.length > cdigits.length ? cdigits.length : vdigits.length;
            int a;
            int b;
            for (int i = 0; i < max; i++) {
                a = b = 0;
                try {
                    a = Integer.parseInt(cdigits[i]);
                } catch (Exception e1) {
                    char[] c = cdigits[i].toCharArray();
                    for (int j = 0; j < c.length; j++) {
                        a += (c[j] << ((c.length - (j + 1)) * 8));
                    }
                }
                try {
                    b = Integer.parseInt(vdigits[i]);
                } catch (Exception e1) {
                    char[] c = vdigits[i].toCharArray();
                    for (int j = 0; j < c.length; j++) {
                        b += (c[j] << ((c.length - (j + 1)) * 8));
                    }
                }
                if (a > b) {
                    return true;
                } else if (a < b) {
                    return false;
                } else if ((i == max - 1) && (cdigits.length > vdigits.length)) {
                    return true;
                }
            }
        } catch (Exception e) {
        }
        return false;
    }

From source file:com.iti.request.NearbyService.java

public static List<Address> getNearby(String x, String y, String r, String type) throws IOException {

    String url = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?v=3&location=";
    url = url.concat(x);//  w  w  w.  jav  a  2s  .c  om
    url = url.concat("%2C");
    url = url.concat(y);
    url = url.concat("&radius=");
    url = url.concat(r);
    url = url.concat("&types=");
    url = url.concat(type);
    url = url.concat("&key=AIzaSyAmsScw_ynzyQf32_KSGjbGiej7VN2rL7g");

    String result = httpGet(url);

    Object obj = JSONValue.parse(result.toString());
    JSONObject jsonObj = (JSONObject) obj;
    JSONArray resultsArray = (JSONArray) jsonObj.get("results");
    Iterator i = resultsArray.iterator();

    ArrayList<Address> addresses = new ArrayList<Address>();

    while (i.hasNext()) {

        JSONObject jsonResult = (JSONObject) i.next();
        String name = (String) jsonResult.get("name");
        String vicinity = (String) jsonResult.get("vicinity");

        System.out.println(name);

        Address address = new Address();
        address.setName(name);
        address.setVicinity(vicinity);

        addresses.add(address);

    }

    return addresses;
}

From source file:com.telefonica.pyretic.backendchannel.BackendChannel.java

@Override
void foundTerminator() {
    /*The end of a command or message has been seen.
    * *///from  ww w . j  a v a 2  s.  co m
    Object obj = JSONValue.parse(this.getBuff());
    JSONArray array = (JSONArray) obj;
    String type = array.get(0).toString();

    if (type.equals("packet")) {
        multiHandler.sendToSwitch((JSONObject) array.get(1), type);
    } else if (type.equals("inject_discovery_packet")) {
        JSONObject newObj = new JSONObject();
        newObj.put("switch", array.get(1));
        newObj.put("inport", array.get(2));
        multiHandler.sendToSwitch(newObj, type);
    } else if (type.equals("install")) {
        System.out.println("install");
    } else if (type.equals("delete")) {
        System.out.println("delete");
    } else if (type.equals("clear")) {
        System.out.println("clear");
    } else if (type.equals("barrier")) {
        System.out.println("clear");
    } else if (type.equals("flow_stats_request")) {
        System.out.println("clear");
    } else {
        System.out.println("ERROR: Unknown msg from frontend " + array.get(1));
    }

}

From source file:com.punyal.medusaserver.californiumServer.core.MedusaValidation.java

public static Client check(String medusaServerAddress, String myTicket, String ticket) {
    CoapClient coapClient = new CoapClient();
    Logger.getLogger("org.eclipse.californium.core.network.CoAPEndpoint").setLevel(Level.OFF);
    Logger.getLogger("org.eclipse.californium.core.network.EndpointManager").setLevel(Level.OFF);
    Logger.getLogger("org.eclipse.californium.core.network.stack.ReliabilityLayer").setLevel(Level.OFF);

    CoapResponse response;// w  w w  .j  a va 2s .c  o m

    coapClient.setURI(medusaServerAddress + "/" + MEDUSA_SERVER_VALIDATION_SERVICE_NAME);
    JSONObject json = new JSONObject();
    json.put(JSON_MY_TICKET, myTicket);
    json.put(JSON_TICKET, ticket);
    response = coapClient.put(json.toString(), 0);

    if (response != null) {
        //System.out.println(response.getResponseText());

        try {
            json.clear();
            json = (JSONObject) JSONValue.parse(response.getResponseText());
            long expireTime = (Long) json.get(JSON_TIME_TO_EXPIRE) + (new Date()).getTime();
            String userName = json.get(JSON_USER_NAME).toString();
            String[] temp = json.get(JSON_ADDRESS).toString().split("/");
            String address;
            if (temp[1] != null)
                address = temp[1];
            else
                address = "0.0.0.0";
            Client client = new Client(InetAddress.getByName(address), userName, null,
                    UnitConversion.hexStringToByteArray(ticket), expireTime);
            return client;
        } catch (Exception e) {
        }

    } else {
        // TODO: take 
    }
    return null;
}

From source file:ch.simas.jtoggl.User.java

public User(String jsonString) {
    JSONObject object = (JSONObject) JSONValue.parse(jsonString);
    this.id = (Long) object.get("id");
    this.jquery_timeofday_format = (String) object.get("jquery_timeofday_format");
    this.api_token = (String) object.get("api_token");
    this.time_entry_retention_days = (Long) object.get("retention");
    this.jquery_date_format = (String) object.get("jquery_date_format");
    this.date_format = (String) object.get("date_format");
    this.default_workspace_id = (Long) object.get("default_wid");
    this.fullname = (String) object.get("fullname");
    this.language = (String) object.get("language");
    this.beginning_of_week = (Long) object.get("beginning_of_week");
    this.timeofday_format = (String) object.get("timeofday_format");
    this.email = (String) object.get("email");
    this.timeZone = (String) object.get("timezone");
}

From source file:ch.zhaw.icclab.tnova.expressionsolver.OTFlyEval.java

@POST
@Consumes(MediaType.APPLICATION_JSON)/*ww  w . jav a  2 s.c  om*/
@Produces(MediaType.APPLICATION_JSON)
public Response evalOnTheFly(String incomingMsg) {
    JSONObject incoming = (JSONObject) JSONValue.parse(incomingMsg);
    JSONObject outgoing = new JSONObject();
    String result = "";
    try {
        String expression = (String) incoming.get("exp");
        JSONArray vals = (JSONArray) incoming.get("values");
        Stack<Double> param = new Stack<Double>();
        for (int i = 0; i < vals.size(); i++) {
            Double val = new Double((String) vals.get(i));
            param.push(val);
        }
        double threshold = Double.parseDouble((String) incoming.get("threshold"));
        result = evaluateExpression(expression, param, threshold);
    } catch (Exception ex) {
        if (App.showExceptions)
            ex.printStackTrace();
    }
    logger.info("received expression: " + incoming.get("exp"));
    logger.info("expression evaluation result: " + result);
    //construct proper JSON response.
    outgoing.put("info", "t-nova expression evaluation service");
    if (result != null && result.length() != 0) {
        outgoing.put("result", result);
        outgoing.put("status", "ok");
        KPI.expressions_evaluated += 1;
        KPI.api_calls_success += 1;
        return Response.ok(outgoing.toJSONString(), MediaType.APPLICATION_JSON_TYPE).build();
    } else {
        outgoing.put("status", "execution failed");
        outgoing.put("msg",
                "malformed request parameters, check your expression or parameter list for correctness.");
        KPI.expressions_evaluated += 1;
        KPI.api_calls_failed += 1;
        return Response.status(Response.Status.BAD_REQUEST).entity(outgoing.toJSONString())
                .encoding(MediaType.APPLICATION_JSON).build();
    }
}

From source file:net.jakobnielsen.imagga.crop_slice.convert.ApiUsageConverter.java

@Override
public ApiUsage convert(String jsonString) {
    if (jsonString == null) {
        throw new ConverterException("The given JSON string is null");
    }//from   w  w w  .  j a va  2 s.c o  m

    JSONObject json = (JSONObject) JSONValue.parse(jsonString);

    if (!json.containsKey(API_USAGE)) {
        throw new ConverterException(API_USAGE + " key missing from json : " + jsonString);
    }
    json = (JSONObject) json.get(API_USAGE);

    return doConvert(json);
}

From source file:ee.ioc.phon.netspeechapi.recsession.ChunkedWebRecSessionResult.java

public ChunkedWebRecSessionResult(InputStreamReader reader) throws IOException {
    Object obj = JSONValue.parse(reader);

    if (obj == null) {
        throw new IOException("Server response is not well-formed");
    }//from   w w w. ja  va 2  s. c o  m

    JSONObject jsonObj = (JSONObject) obj;
    for (Object o1 : (JSONArray) jsonObj.get("hypotheses")) {
        JSONObject jo1 = (JSONObject) o1;
        add(mUtterances, jo1.get("utterance"));
        Object lins = jo1.get("linearizations");
        List<Linearization> linearizations = new ArrayList<Linearization>();
        if (lins != null) {
            for (Object o2 : (JSONArray) lins) {
                JSONObject jo2 = (JSONObject) o2;
                add(mLinearizations, jo2.get("output"));

                String output = objToString(jo2.get("output"));
                String lang = objToString(jo2.get("lang"));
                linearizations.add(new Linearization(output, lang));
            }
        }
        mHypotheses.add(new Hypothesis(objToString(jo1.get("utterance")), linearizations));
    }
}

From source file:me.neatmonster.spacebukkit.PanelListener.java

/**
 * Interprets a raw command from the panel
 * @param string input from panel//  w  w w .  ja  v a 2 s.c  om
 * @return result of the action
 * @throws InvalidArgumentsException Thrown when the wrong arguments are used by the panel
 * @throws UnhandledActionException Thrown when there is no handler for the action
 */
@SuppressWarnings("unchecked")
private static Object interpret(final String string)
        throws InvalidArgumentsException, UnhandledActionException {
    final int indexOfMethod = string.indexOf("?method=");
    final int indexOfArguments = string.indexOf("&args=");
    final int indexOfKey = string.indexOf("&key=");
    final String method = string.substring(indexOfMethod + 8, indexOfArguments);
    final String argumentsString = string.substring(indexOfArguments + 6, indexOfKey);
    final List<Object> arguments = (List<Object>) JSONValue.parse(argumentsString);
    try {
        if (SpaceBukkit.getInstance().actionsManager.contains(method))
            return SpaceBukkit.getInstance().actionsManager.execute(method, arguments.toArray());
        else {
            final RequestEvent event = new RequestEvent(method, arguments.toArray());
            Bukkit.getPluginManager().callEvent(event);
            return JSONValue.toJSONString(event.getResult());
        }
    } catch (final InvalidArgumentsException e) {
        e.printStackTrace();
    } catch (final UnhandledActionException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:net.jakobnielsen.imagga.crop_slice.convert.DivisionRegionConverter.java

@Override
public List<DivisionRegion> convert(String jsonString) {
    if (jsonString == null) {
        throw new ConverterException("The given JSON string is null");
    }/*from ww w  . j a  v a 2s.co m*/

    JSONObject json = (JSONObject) JSONValue.parse(jsonString);
    if (!json.containsKey(DIVISION_REGIONS)) {
        throw new ConverterException(DIVISION_REGIONS + " key missing from json : " + jsonString);
    }
    JSONArray jsonArray = (JSONArray) json.get(DIVISION_REGIONS);
    List<DivisionRegion> divisionRegions = new ArrayList<DivisionRegion>();

    for (Object aJsonArray : jsonArray) {

        JSONObject divisionRegionObject = (JSONObject) aJsonArray;

        String url = getString("url", divisionRegionObject);

        List<Region> regions = new ArrayList<Region>();

        if (divisionRegionObject.containsKey(REGIONS)) {

            if (divisionRegionObject.get(REGIONS) != null
                    && divisionRegionObject.get(REGIONS) instanceof JSONArray) {
                JSONArray regionsArrays = (JSONArray) divisionRegionObject.get(REGIONS);

                for (Object aRegionsArray : regionsArrays) {

                    JSONObject regionObject = (JSONObject) aRegionsArray;

                    regions.add(new Region(getInteger("x1", regionObject), getInteger("y1", regionObject),
                            getInteger("x2", regionObject), getInteger("y2", regionObject)));
                }
                divisionRegions.add(new DivisionRegion(url, regions));
            }
        }
    }

    return divisionRegions;
}