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:EZShare.SubscribeCommandConnection.java

public static void establishPersistentConnection(Boolean secure, int port, String ip, int id,
        JSONObject unsubscribJsonObject, String commandname, String name, String owner, String description,
        String channel, String uri, List<String> tags, String ezserver, String secret, Boolean relay,
        String servers) throws URISyntaxException {
    //secure = false;
    try {//w w w . jav  a  2s.  com
        System.out.print(port + ip);
        Socket socket = null;
        if (secure) {

            SSLSocketFactory sslsocketfactory = (SSLSocketFactory) SSLSocketFactory.getDefault();
            socket = (SSLSocket) sslsocketfactory.createSocket(ip, port);
        } else {
            socket = new Socket(ip, port);
        }
        BufferedReader Reader = new BufferedReader(new InputStreamReader(System.in));
        DataOutputStream output = new DataOutputStream(socket.getOutputStream());
        DataInputStream input = new DataInputStream(socket.getInputStream());

        JSONObject command = new JSONObject();
        Resource resource = new Resource();
        command = resource.inputToJSON(commandname, id, name, owner, description, channel, uri, tags, ezserver,
                secret, relay, servers);

        output.writeUTF(command.toJSONString());
        Client.debug("SEND", command.toJSONString());
        //output.writeUTF(command.toJSONString());
        new Thread(new Runnable() {
            @Override
            public void run() {
                String string = null;
                try {
                    while (true/*(string = input.readUTF()) != null*/) {
                        String serverResponse = input.readUTF();
                        JSONParser parser = new JSONParser();
                        JSONObject response = (JSONObject) parser.parse(serverResponse);
                        Client.debug("RECEIVE", response.toJSONString());
                        //System.out.println(serverResponse);          
                        //                     if((string = Reader.readLine()) != null){
                        //                        if(onKeyPressed(output,string,unsubscribJsonObject)) break;
                        //                     }
                        if (flag == 1) {
                            break;
                        }
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (ParseException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }).start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                String string = null;
                try {
                    while ((string = Reader.readLine()) != null) {
                        flag = 1;
                        if (onKeyPressed(output, string, unsubscribJsonObject))
                            break;
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:iracing.webapi.SeasonStandingsParser.java

public static long parse(String json, ItemHandler handler) {
    JSONParser parser = new JSONParser();
    //        System.err.println(json);
    long output = 0;
    try {/*from  w ww .j  ava 2s  .  c  o m*/
        JSONObject root = (JSONObject) parser.parse(json);
        JSONObject arrayRoot = (JSONObject) root.get("d");
        output = getLong(arrayRoot, "27");
        JSONArray results = (JSONArray) arrayRoot.get("r");
        for (int i = 0; i < results.size(); i++) {
            JSONObject result = (JSONObject) results.get(i);
            SeasonStanding standing = new SeasonStanding();
            standing.setDroppedWeeks(getInt(result, "1"));
            standing.setClubName(getString(result, "2", true));
            standing.setCountryCode(getString(result, "3", true));
            standing.setLicenseSubLevel(getString(result, "4"));
            standing.setAverageFinish(getInt(result, "5"));
            standing.setIrating(getInt(result, "6"));
            standing.setTotalTopFives(getInt(result, "7"));
            standing.setMaxLicenseLevel(getInt(result, "8"));
            standing.setDriverName(getString(result, "9", true));
            standing.setClubId(getInt(result, "10"));
            standing.setTotalStarts(getInt(result, "11"));
            standing.setDisplayCountry(getString(result, "14", true));
            standing.setTotalLapsLed(getInt(result, "13"));
            standing.setCountry(getString(result, "15", true));
            standing.setTotalWins(getInt(result, "16"));
            standing.setTotalIncidents(getInt(result, "17"));
            Object o = result.get("18");
            double d;
            if (o instanceof Long) {
                Long l = (Long) o;
                d = l.doubleValue();
            } else {
                d = (Double) o;
            }
            standing.setTotalPoints(d);
            standing.setRank(getInt(result, "20"));
            standing.setDivision(getInt(result, "22"));
            standing.setDriverCustomerId(getLong(result, "24"));
            standing.setWeeksCounted(getInt(result, "26"));
            standing.setTotalLaps(getLong(result, "28"));
            standing.setAverageStart(getInt(result, "29"));
            standing.setTotalPoles(getInt(result, "30"));
            standing.setPosition(getLong(result, "31"));
            if (!handler.onSeasonStandingParsed(standing))
                break;
        }
    } catch (ParseException ex) {
        Logger.getLogger(SeasonStandingsParser.class.getName()).log(Level.SEVERE, null, ex);
    }
    return output;
}

From source file:flow.visibility.tapping.OpenDayLightUtils.java

/** The function for inserting the flow */

public static void FlowEntry(String ODPURL, String ODPAccount, String ODPPassword) throws Exception {

    //String user = "admin";
    //String password = "admin";
    String baseURL = "http://" + ODPURL + "/controller/nb/v2/flowprogrammer";
    String containerName = "default";

    /** Check the connection for ODP REST API */

    try {/*from   ww w. j ava2s . c  om*/

        // Create URL = base URL + container
        URL url = new URL(baseURL + "/" + containerName);

        // Create authentication string and encode it to Base64
        String authStr = ODPAccount + ":" + ODPPassword;
        String encodedAuthStr = Base64.encodeBase64String(authStr.getBytes());

        // Create Http connection
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        // Set connection properties
        connection.setRequestMethod("GET");
        connection.setRequestProperty("Authorization", "Basic " + encodedAuthStr);
        connection.setRequestProperty("Accept", "application/json");

        // Get the response from connection's inputStream
        InputStream content = (InputStream) connection.getInputStream();

        /** The create the frame and blank pane */
        OpenDayLightUtils object = new OpenDayLightUtils();
        object.setVisible(true);

        /** Read the Flow entry in JSON Format */
        BufferedReader in = new BufferedReader(new InputStreamReader(content));
        String line = "";

        /** Print line by line in Pane with Pretty JSON */
        while ((line = in.readLine()) != null) {

            JSONParser jsonParser = new JSONParser();
            JSONObject jsonObject = (JSONObject) jsonParser.parse(line);

            Gson gson = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create();
            String json = gson.toJson(jsonObject);
            System.out.println(json);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

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

/**
 * Given a String, it is decoded and the result is returned as a String as well.
 * @param encodedUrl is a String that have the full data encrypted
 * @return decoded String/*from  w  ww . j ava 2 s .c  om*/
 */
public static String decode(String encodedUrl) {

    try {

        //Decode URL
        final SecretKeySpec secretKey = new SecretKeySpec(key, "AES");
        cipher.init(Cipher.DECRYPT_MODE, secretKey,
                new IvParameterSpec(initializationVector.getBytes("UTF-8")));

        String result = new String(cipher.doFinal(Base64.decodeBase64(encodedUrl)));

        //Extract and remove hash from JSONObject
        JSONParser parser = new JSONParser();
        JSONObject receivedData = (JSONObject) parser.parse(result);
        String receivedHash = (String) receivedData.get("hash");
        receivedData.remove("hash");

        //Compare received hash with newly computed hash
        if (checkDataValidity(receivedData)) {
            byte[] hashOfData = createMD5Hash(receivedData);

            if (receivedHash.equals(new String(hashOfData, "UTF-8"))) { //Valid data
                return receivedData.toString();
            }
        }
    } catch (Exception e) {
    } //Invalid data (including encryption algorithm exceptions

    return null;
}

From source file:iracing.webapi.SeasonParser.java

public static List<Season> parse(String json) {
    JSONParser parser = new JSONParser();
    List<Season> output = null;
    try {// w w w  . j  av a  2s .co m
        JSONArray rootArray = (JSONArray) parser.parse(json);
        output = new ArrayList<Season>();
        for (int i = 0; i < rootArray.size(); i++) {
            JSONObject r = (JSONObject) rootArray.get(i);
            Season season = new Season();
            season.setId(getInt(r, "seasonid"));
            season.setPrefImage(getString(r, "prefimg", true));
            season.setSeriesName(getString(r, "seriesname", true));
            season.setSeasonShortName(getString(r, "seasonshortname", true));
            season.setWhatsHotImage(getString(r, "whatshotimg", true));
            season.setCautionTypeRoad(getInt(r, "cautionTypeRoad"));
            season.setCautionTypeOval(getInt(r, "cautionTypeOval"));
            season.setRaceWeeks(getInt(r, "raceweek"));
            season.setActive((Boolean) r.get("active"));
            season.setMinimumSafetyRating(getString(r, "minsr"));
            season.setMinimumLicenseLevel(getInt(r, "minlicenselevel"));
            season.setMaximumLicenseLevel(getInt(r, "maxlicenselevel"));
            JSONArray array = (JSONArray) r.get("tracks");
            List<Season.Track> trackList = new ArrayList<Season.Track>();
            // to work around a website bug where tracks are listed 3 times each, 
            // we only add ones that have different raceweek values
            int lastRaceWeek = -1;
            for (int j = 0; j < array.size(); j++) {
                //{"config":"","priority":0,"raceweek":0,"pkgid":90,"night":0,"name":"Mosport+International+Raceway","id":144,"lowername":"mosport+international+raceway"}
                JSONObject o = (JSONObject) array.get(j);
                int raceWeek = getInt(o, "raceweek");
                if (raceWeek != lastRaceWeek) {
                    Season.Track track = new Season.Track();
                    track.setId(getInt(o, "id"));
                    track.setNightMode((getInt(o, "night")) == 1);
                    trackList.add(track);
                    lastRaceWeek = raceWeek;
                }
            }
            season.setTracks(trackList);
            //"carclasses":[{"carsinclass":[{"name":"Cadillac+CTS-V+Racecar","id":41}],"shortname":"Cadillac+CTS-VR","name":"Cadillac+CTS-VR","id":45,"lowername":"cadillac+cts-vr"}]
            List<Integer> carClasses = new ArrayList<Integer>();
            array = (JSONArray) r.get("carclasses");
            for (int j = 0; j < array.size(); j++) {
                JSONObject o = (JSONObject) array.get(j);
                //JSONArray array2 = (JSONArray)o.get("carsinclass");
                carClasses.add(getInt(o, "id"));
            }
            season.setCarClasses(carClasses);
            season.setApiUserClubAllowed((Boolean) r.get("isClubAllowed"));
            season.setSeriesLicenseGroupId(getInt(r, "serieslicgroupid"));
            season.setCurrentTrack(getInt(r, "currentTrack"));
            season.setSeriesId(getInt(r, "seriesid"));
            season.setLicenseGroupId(getInt(r, "licgroupid"));
            season.setLicenseIgnoredForPractice((Boolean) r.get("ignoreLicenseForPractice"));
            season.setWorldCupEvent((Boolean) r.get("isWorldCup"));
            season.setStartDate(new Date(getLong(r, "start")));
            season.setEndDate(new Date(getLong(r, "end")));
            array = (JSONArray) r.get("cars");
            List<Integer> carList = new ArrayList<Integer>();
            for (int j = 0; j < array.size(); j++) {
                JSONObject o = (JSONObject) array.get(j);
                carList.add(getInt(o, "id"));
            }
            season.setCars(carList);
            season.setMultiClass((Boolean) r.get("multiclass"));
            season.setRegionalCompetitionEvent((Boolean) r.get("isRegionCompetition"));
            season.setQuarter(getInt(r, "quarter"));
            season.setYear(getInt(r, "year"));
            season.setSeriesShortName(getString(r, "seriesshortname", true));
            season.setCategoryId(getInt(r, "catid")); // also stored under 'category'
            season.setOfficial((Boolean) r.get("isOfficial"));
            season.setApiUserLicenseEligible((Boolean) r.get("licenseEligible"));
            season.setComplete((Boolean) r.get("complete"));
            output.add(season);
        }
    } catch (ParseException ex) {
        Logger.getLogger(SeasonParser.class.getName()).log(Level.SEVERE, null, ex);
    }
    return output;
}

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

/**
 * Put.//from w ww .  ja  v  a  2  s  . c o m
 * 
 * @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.telefonica.iot.cygnus.utils.NGSIUtils.java

/**
 * Gets a geometry value, ready for insertion in CartoDB, given a NGSI attribute value and its metadata.
 * If the attribute is not geo-related, it is returned as it is.
 * @param attrValue/*from  w  ww.  jav  a2  s  .  c o m*/
 * @param attrType
 * @param metadata
 * @param swapCoordinates
 * @return The geometry value, ready for insertion in CartoDB/PostGIS, or the value as it is
 */
public static ImmutablePair<String, Boolean> getGeometry(String attrValue, String attrType, String metadata,
        boolean swapCoordinates) {
    // First, check the attribute type
    if (attrType.equals("geo:point")) {
        String[] split = attrValue.split(",");

        if (swapCoordinates) {
            return new ImmutablePair(
                    "ST_SetSRID(ST_MakePoint(" + split[1].trim() + "," + split[0].trim() + "), 4326)", true);
        } else {
            return new ImmutablePair(
                    "ST_SetSRID(ST_MakePoint(" + split[0].trim() + "," + split[1].trim() + "), 4326)", true);
        } // if else
    } // if

    if (attrType.equals("geo:json")) {
        return new ImmutablePair("ST_GeomFromGeoJSON(" + attrValue + ")", true);
    } // if

    // TBD: What about:  ?
    // 'geo:line'
    // 'geo:box'
    // 'geo:polygon'
    // 'geo:multipoint'
    // 'geo:multiline'
    // 'geo:multipolygon'

    // The type was not 'geo:point' nor 'geo:json', thus try the metadata
    JSONParser parser = new JSONParser();
    JSONArray mds;

    try {
        mds = (JSONArray) parser.parse(metadata);
    } catch (ParseException e) {
        LOGGER.error("Error while parsing the metadata. Details: " + e.getMessage());
        return new ImmutablePair(attrValue, false);
    } // try catch

    for (Object mdObject : mds) {
        JSONObject md = (JSONObject) mdObject;
        String mdName = (String) md.get("name");
        String mdType = (String) md.get("type");
        String mdValue = (String) md.get("value");

        if (mdName.equals("location") && mdType.equals("string") && mdValue.equals("WGS84")) {
            String[] split = attrValue.split(",");

            if (swapCoordinates) {
                return new ImmutablePair(
                        "ST_SetSRID(ST_MakePoint(" + split[1].trim() + "," + split[0].trim() + "), 4326)",
                        true);
            } else {
                return new ImmutablePair(
                        "ST_SetSRID(ST_MakePoint(" + split[0].trim() + "," + split[1].trim() + "), 4326)",
                        true);
            } // if else
        } // if
    } // for

    // The attribute was not related to a geolocation
    return new ImmutablePair(attrValue, false);
}

From source file:info.pancancer.arch3.utils.Utilities.java

public static JSONObject parseJSONStr(String jsonStr) {
    JSONObject data = null;//from   w  w w  . j a  v a2 s.  c  om

    JSONParser parser = new JSONParser();
    try {
        data = (JSONObject) parser.parse(jsonStr);
    } catch (ParseException ex) {
        throw new RuntimeException(ex);
    }

    return data;
}

From source file:com.github.itoshige.testrail.util.ConfigrationUtil.java

private static JSONObject getConfig() {
    try {/*w w  w  .j a v a 2s .  c om*/
        JSONObject obj = configs.get(CONFIG_FILE);
        if (obj != null && !obj.isEmpty())
            return obj;

        JSONParser parser = new JSONParser();
        configs.putIfAbsent(CONFIG_FILE,
                (JSONObject) parser.parse(new FileReader(FilePathSearchUtil.getPath(CONFIG_FILE))));

        return configs.get(CONFIG_FILE);
    } catch (Exception e) {
        throw new TestInitializerException(String.format("%s can't be read.", CONFIG_FILE), e);
    }
}

From source file:hoot.services.controllers.job.JobControllerBase.java

protected static JSONArray parseParams(String params) throws ParseException {
    JSONParser parser = new JSONParser();
    JSONObject command = (JSONObject) parser.parse(params);
    JSONArray commandArgs = new JSONArray();

    for (Object o : command.entrySet()) {
        Map.Entry<Object, Object> mEntry = (Map.Entry<Object, Object>) o;
        String key = (String) mEntry.getKey();
        String val = (String) mEntry.getValue();

        JSONObject arg = new JSONObject();
        arg.put(key, val);
        commandArgs.add(arg);/*w  w w  . j av  a2 s.c o  m*/

    }

    return commandArgs;
}