Example usage for org.json.simple JSONArray get

List of usage examples for org.json.simple JSONArray get

Introduction

In this page you can find the example usage for org.json.simple JSONArray get.

Prototype

public E get(int index) 

Source Link

Document

Returns the element at the specified position in this list.

Usage

From source file:it.avalz.opendaylight.controller.examples.JsonParser.java

public static void main(String[] args) {

    String s = "{\"ids\":[\"00:00:00:00:00:00:00:01\", \"00:00:00:00:00:00:00:02\"], \"width\":200, \"height\":100}";

    JSONObject json = null;//  w w  w . ja  va 2s  . com
    try {
        json = (JSONObject) new JSONParser().parse(s);
    } catch (ParseException ex) {
        ex.printStackTrace();
    }

    System.out.println(json.get("ids"));

    JSONArray array = (JSONArray) json.get("ids");
    System.out.println(array.get(0));
    System.out.println(json.get("width"));
    System.out.println(json.get("height"));

    List<String> l = new ArrayList<String>();

    l.add("\"DROP\"");
    l.add("\"OUTPUT=2\"");
    System.out.println(l);
}

From source file:bonapetit.ParseJson1.java

public static void main(String[] args) {
    String url = "http://freemusicarchive.org/api/get/genres.json?api_key=60BLHNQCAOUFPIBZ&limit=2";
    /*/*  ww w.j  a  v  a  2s  .  co m*/
     * {"title":"Free Music Archive - Genres","message":"","errors":[],"total" : "161","total_pages":81,"page":1,"limit":"2",
     * "dataset":
     * [{"genre_id": "1","genre_parent_id":"38","genre_title":"Avant-Garde" ,"genre_handle": "Avant-Garde","genre_color":"#006666"},
     * {"genre_id":"2","genre_parent_id" :null,"genre_title":"International","genre_handle":"International","genre_color":"#CC3300"}]}
     */
    try {
        String genreJson = IOUtils.toString(new URL(url));
        JSONObject genreJsonObject = (JSONObject) JSONValue.parseWithException(genreJson);
        // get the title
        System.out.println(genreJsonObject.get("title"));
        // get the data
        JSONArray genreArray = (JSONArray) genreJsonObject.get("dataset");
        // get the first genre
        JSONObject firstGenre = (JSONObject) genreArray.get(0);
        System.out.println(firstGenre.get("genre_title"));
    } catch (IOException | ParseException e) {
        e.printStackTrace();
    }
}

From source file:amazonechoapi.AmazonEchoApi.java

public static void main(String[] args) throws InterruptedException, IOException {
    AmazonEchoApi amazonEchoApi = new AmazonEchoApi("https://pitangui.amazon.com", "username", "password");
    if (amazonEchoApi.httpLogin()) {
        while (true) {
            String output = amazonEchoApi.httpGet("/api/todos?type=TASK&size=1");

            // Parse JSON
            Object obj = JSONValue.parse(output);
            JSONObject jsonObject = (JSONObject) obj;
            JSONArray values = (JSONArray) jsonObject.get("values");
            JSONObject item = (JSONObject) values.get(0);

            // Get text and itemId
            String text = item.get("text").toString();
            String itemId = item.get("itemId").toString();

            if (!checkItemId(itemId)) {
                addItemId(itemId);/*from  w ww  .j a va  2 s . c  om*/
                System.out.println(text);
                // Do something. ie Hue Lights, etc
            } else {
                System.out.println("No new commands");
            }
            // Sleep for 15 seconds
            Thread.sleep(15000);
        }

    }
}

From source file:com.devdungeon.simplejson.DecodeJson.java

public static void main(String[] args) {

    try {//  w  ww.  j  a  v  a 2  s  .c  om
        String jsonData = getJsonFromUrl("http://www.reddit.com/r/houston.json");

        JSONParser jsonParser = new JSONParser();
        JSONObject jsonObject = (JSONObject) jsonParser.parse(jsonData); // The whole JSON value

        //System.out.println(jsonObject);
        JSONObject data = (JSONObject) jsonObject.get("data"); // The data object
        //System.out.println(data); 

        JSONArray children = (JSONArray) data.get("children"); // All children

        // for each child in children
        // get child("data")
        for (int i = 0; i < children.size(); i++) {
            JSONObject child = (JSONObject) children.get(i);
            //System.out.println(child); // The whole post object

            JSONObject childData = (JSONObject) child.get("data");
            System.out.print(childData.get("title") + ": ");
            System.out.println(childData.get("url"));
        }

    } catch (ParseException ex) {
        ex.printStackTrace();
    } catch (NullPointerException ex) {
        ex.printStackTrace();
    }

}

From source file:TwitterClustering.java

public static void main(String[] args) throws FileNotFoundException, IOException {
    // TODO code application logic here

    File outFile = new File(args[3]);
    Scanner s = new Scanner(new File(args[1])).useDelimiter(",");
    JSONParser parser = new JSONParser();
    Set<Cluster> clusterSet = new HashSet<Cluster>();
    HashMap<String, Tweet> tweets = new HashMap();
    FileWriter fw = new FileWriter(outFile.getAbsoluteFile());
    BufferedWriter bw = new BufferedWriter(fw);

    // init//from w  ww .ja  va  2 s. c om
    try {

        Object obj = parser.parse(new FileReader(args[2]));

        JSONArray jsonArray = (JSONArray) obj;

        for (int i = 0; i < jsonArray.size(); i++) {

            Tweet twt = new Tweet();
            JSONObject jObj = (JSONObject) jsonArray.get(i);
            String text = jObj.get("text").toString();

            long sum = 0;
            for (int y = 0; y < text.toCharArray().length; y++) {

                sum += (int) text.toCharArray()[y];
            }

            String[] token = text.split(" ");
            String tID = jObj.get("id").toString();

            Set<String> mySet = new HashSet<String>(Arrays.asList(token));
            twt.setAttributeValue(sum);
            twt.setText(mySet);
            twt.setTweetID(tID);
            tweets.put(tID, twt);

        }

        // preparing initial clusters
        int i = 0;
        while (s.hasNext()) {
            String id = s.next();// id
            Tweet t = tweets.get(id.trim());
            clusterSet.add(new Cluster(i + 1, t, new LinkedList()));
            i++;
        }

        Iterator it = tweets.entrySet().iterator();

        for (int l = 0; l < 2; l++) { // limit to 25 iterations

            while (it.hasNext()) {
                Map.Entry me = (Map.Entry) it.next();

                // calculate distance to each centroid
                Tweet p = (Tweet) me.getValue();
                HashMap<Cluster, Float> distMap = new HashMap();

                for (Cluster clust : clusterSet) {

                    distMap.put(clust, jaccardDistance(p.getText(), clust.getCentroid().getText()));
                }

                HashMap<Cluster, Float> sorted = (HashMap<Cluster, Float>) sortByValue(distMap);

                sorted.keySet().iterator().next().getMembers().add(p);

            }

            // calculate new centroid and update Clusterset
            for (Cluster clust : clusterSet) {

                TreeMap<String, Long> tDistMap = new TreeMap();

                Tweet newCentroid = null;
                Long avgSumDist = new Long(0);
                for (int j = 0; j < clust.getMembers().size(); j++) {

                    avgSumDist += clust.getMembers().get(j).getAttributeValue();
                    tDistMap.put(clust.getMembers().get(j).getTweetID(),
                            clust.getMembers().get(j).getAttributeValue());
                }
                if (clust.getMembers().size() != 0) {
                    avgSumDist /= (clust.getMembers().size());
                }

                ArrayList<Long> listValues = new ArrayList<Long>(tDistMap.values());

                if (tDistMap.containsValue(findClosestNumber(listValues, avgSumDist))) {
                    // found closest
                    newCentroid = tweets
                            .get(getKeyByValue(tDistMap, findClosestNumber(listValues, avgSumDist)));
                    clust.setCentroid(newCentroid);
                }

            }

        }
        // create an iterator
        Iterator iterator = clusterSet.iterator();

        // check values
        while (iterator.hasNext()) {

            Cluster c = (Cluster) iterator.next();
            bw.write(c.getId() + "\t");
            System.out.print(c.getId() + "\t");

            for (Tweet t : c.getMembers()) {
                bw.write(t.getTweetID() + ", ");
                System.out.print(t.getTweetID() + ",");

            }
            bw.write("\n");
            System.out.println("");
        }

        System.out.println("");

        System.out.println("SSE " + sumSquaredErrror(clusterSet));

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        bw.close();
        fw.close();
    }
}

From source file:ServerStatus.java

License:asdf

/**
 * @param args the command line arguments
 *///from   w ww  . j  a  v a2  s. c  o  m
public static void main(String[] args)
        throws InterruptedException, FileNotFoundException, IOException, ParseException {
    FileReader reader = null;
    ArrayList<BankInfo2> BankArray = new ArrayList<BankInfo2>();
    reader = new FileReader(args[0]);
    JSONParser jp = new JSONParser();
    JSONObject doc = (JSONObject) jp.parse(reader);
    JSONObject banks = (JSONObject) doc.get("banks");
    //Set bankKeys = banks.keySet();
    //Object [] bankNames = bankKeys.toArray();
    Object[] bankNames = banks.keySet().toArray();
    for (int i = 0; i < bankNames.length; i++) {

        //System.out.println(bankNames[i]);
        String bname = (String) bankNames[i];
        BankInfo2 binfo = new BankInfo2(bname);
        JSONObject banki = (JSONObject) banks.get(bname);
        JSONArray chain = (JSONArray) banki.get("chain");
        int chainLength = chain.size();
        //System.out.println(chainLength);
        for (Object chain1 : chain) {

            JSONObject serv = (JSONObject) chain1;
            ServerInfo sinfo = new ServerInfo((String) serv.get("ip"), serv.get("port").toString(),
                    serv.get("start_delay").toString(), serv.get("lifetime").toString(),
                    serv.get("receive").toString(), serv.get("send").toString());
            binfo.servers.add(sinfo);
            //System.out.println(serv.get("ip") + ":" + serv.get("port"));
        }
        BankArray.add(binfo);
    }
    //System.out.println("Done Processing Servers");
    JSONArray clients = (JSONArray) doc.get("clients");
    ArrayList<ClientInfo> clientsList = new ArrayList<ClientInfo>();
    for (int i = 0; i < clients.size(); i++) {
        JSONObject client_i = (JSONObject) clients.get(i);
        //This is for hard coded requests in the json file
        //System.out.println(client_i);
        //System.out.println(client_i.getClass());
        String typeOfClient = client_i.get("requests").getClass().toString();

        //This is for a client that has hardCoded requests
        if (typeOfClient.equals("class org.json.simple.JSONArray")) {
            //System.out.println("JSONArray");
            JSONArray requests = (JSONArray) client_i.get("requests");
            ClientInfo c = new ClientInfo(client_i.get("reply_timeout").toString(),
                    client_i.get("request_retries").toString(), client_i.get("resend_head").toString());
            c.prob_failure = client_i.get("prob_failure").toString();
            c.msg_send_delay = client_i.get("msg_delay").toString();
            System.out.println(
                    "Successfully added prob failure and msg_send " + c.prob_failure + "," + c.msg_send_delay);
            ArrayList<RequestInfo> req_list = new ArrayList<RequestInfo>();
            for (int j = 0; j < requests.size(); j++) {
                JSONObject request_j = (JSONObject) requests.get(j);
                String req = request_j.get("request").toString();
                String bank = request_j.get("" + "bank").toString();
                String acc = request_j.get("account").toString();
                String seq = request_j.get("seq_num").toString();
                String amt = null;
                try {
                    amt = request_j.get("amount").toString();
                } catch (NullPointerException e) {
                    //System.out.println("Amount not specified.");
                }
                RequestInfo r;
                if (amt == null) {
                    r = new RequestInfo(req, bank, acc, seq);
                } else {
                    r = new RequestInfo(req, bank, acc, amt, seq);
                }
                //RequestInfo r = new RequestInfo(request_j.get("request").toString(), request_j.get("bank").toString(), request_j.get("account").toString(), request_j.get("amount").toString());
                req_list.add(r);
            }
            c.requests = req_list;
            c.PortNumber = 60000 + i;
            clientsList.add(c);
            //System.out.println(client_i);
        }
        //This is for Random client requests
        else if (typeOfClient.equals("class org.json.simple.JSONObject")) {
            JSONObject randomReq = (JSONObject) client_i.get("requests");
            String seed = randomReq.get("seed").toString();
            String num_requests = randomReq.get("num_requests").toString();
            String prob_balance = randomReq.get("prob_balance").toString();
            String prob_deposit = randomReq.get("prob_deposit").toString();
            String prob_withdraw = randomReq.get("prob_withdrawal").toString();
            String prob_transfer = randomReq.get("prob_transfer").toString();
            //ClientInfo c = new ClientInfo(true, seed, num_requests, prob_balance, prob_deposit, prob_withdraw, prob_transfer);
            ClientInfo c = new ClientInfo(client_i.get("reply_timeout").toString(),
                    client_i.get("request_retries").toString(), client_i.get("resend_head").toString(), seed,
                    num_requests, prob_balance, prob_deposit, prob_withdraw, prob_transfer);
            c.PortNumber = 60000 + i;
            clientsList.add(c);
        }
    }
    //System.out.println(clients.size());
    double lowerPercent = 0.0;
    double upperPercent = 1.0;
    double result;
    String bankChainInfoMaster = "";
    for (int x = 0; x < BankArray.size(); x++) {
        BankInfo2 analyze = BankArray.get(x);
        String chain = analyze.bank_name + "#";
        //analyze.servers
        for (int j = 0; j < analyze.servers.size(); j++) {
            if (analyze.servers.get(j).Start_delay.equals("0")) {
                if (j == 0) {
                    chain += analyze.servers.get(j).Port;
                } else {
                    chain += "#" + analyze.servers.get(j).Port;
                }
            }
        }
        if (x == 0) {
            bankChainInfoMaster += chain;
        } else {
            bankChainInfoMaster += "@" + chain;
        }
    }
    //System.out.println("CHAIN: "+ bankChainInfoMaster);

    String clientInfoMaster = "";
    for (int x = 0; x < clientsList.size(); x++) {
        ClientInfo analyze = clientsList.get(x);
        if (x == 0) {
            clientInfoMaster += analyze.PortNumber;
        } else {
            clientInfoMaster += "#" + analyze.PortNumber;
        }

    }
    //System.out.println("Clients: "+ clientInfoMaster);

    //RUN MASTER HERE 
    String MasterPort = "49999";
    String masterExec = "java Master " + MasterPort + " " + clientInfoMaster + " " + bankChainInfoMaster;
    Process masterProcess = Runtime.getRuntime().exec(masterExec);
    System.out.println(masterExec);
    ArrayList<ServerInfoForClient> servInfoCli = new ArrayList<ServerInfoForClient>();

    // List of all servers is saved so that we can wait for them to exit.
    ArrayList<Process> serverPros = new ArrayList<Process>();
    //ArrayList<String> execServs = new ArrayList<String>();
    for (int i = 0; i < BankArray.size(); i++) {
        BankInfo2 analyze = BankArray.get(i);
        //System.out.println(analyze.bank_name);
        //One server in the chain
        String execCmd = "java Server ";
        String hIP = "", hPort = "", tIP = "", tPort = "", bn = "";
        bn = analyze.bank_name;
        boolean joinFlag = false;
        if (analyze.servers.size() == 2 && analyze.servers.get(1).Start_delay.equals("0")) {
            joinFlag = false;
        } else {
            joinFlag = true;
        }

        if (analyze.servers.size() == 1 && joinFlag == false) {
            //if(analyze.servers.size() == 1){
            ServerInfo si = analyze.servers.get(0);
            execCmd += "HEAD_TAIL " + si.IP + ":" + si.Port;
            execCmd += " localhost:0 localhost:0 localhost:" + MasterPort + " " + si.Start_delay + " "
                    + si.Lifetime + " " + si.Receive + " " + si.Send + " " + analyze.bank_name;
            ;
            hIP = si.IP;
            hPort = si.Port;
            tIP = si.IP;
            tPort = si.Port;
            System.out.println(execCmd);
            Thread.sleep(500);
            Process pro = Runtime.getRuntime().exec(execCmd);
            serverPros.add(pro);
            //}
        } else if (analyze.servers.size() == 2 && joinFlag == true) {
            ServerInfo si = analyze.servers.get(0);
            execCmd += "HEAD_TAIL " + si.IP + ":" + si.Port;
            execCmd += " localhost:0 localhost:0 localhost:" + MasterPort + " " + si.Start_delay + " "
                    + si.Lifetime + " " + si.Receive + " " + si.Send + " " + analyze.bank_name;
            ;
            hIP = si.IP;
            hPort = si.Port;
            tIP = si.IP;
            tPort = si.Port;
            System.out.println(execCmd);
            Thread.sleep(500);
            Process pro = Runtime.getRuntime().exec(execCmd);
            serverPros.add(pro);

            execCmd = "java Server ";
            ServerInfo si2 = analyze.servers.get(1);
            execCmd += "TAIL " + si2.IP + ":" + si2.Port;
            execCmd += " localhost:0 localhost:0 localhost:" + MasterPort + " " + si2.Start_delay + " "
                    + si2.Lifetime + " " + si2.Receive + " " + si2.Send + " " + analyze.bank_name;
            ;
            hIP = si.IP;
            hPort = si.Port;
            tIP = si.IP;
            tPort = si.Port;
            System.out.println(execCmd);
            Thread.sleep(500);
            Process pro2 = Runtime.getRuntime().exec(execCmd);
            serverPros.add(pro2);
        } else {
            int icount = 0;
            for (int x = 0; x < analyze.servers.size(); x++) {
                ServerInfo si = analyze.servers.get(x);
                if (si.Start_delay.equals("0")) {
                    icount++;
                }
            }
            System.out.println("icount:" + icount);
            for (int j = 0; j < icount; j++) {
                //for(int j = 0; j < analyze.servers.size(); j++){
                execCmd = "java Server ";
                ServerInfo si = analyze.servers.get(j);
                //Head server
                if (j == 0) {
                    ServerInfo siSucc = analyze.servers.get(j + 1);
                    execCmd += "HEAD " + si.IP + ":" + si.Port + " ";
                    execCmd += "localhost:0 " + siSucc.IP + ":" + siSucc.Port + " localhost:" + MasterPort;
                    execCmd += " " + si.Start_delay + " " + si.Lifetime + " " + si.Receive + " " + si.Send + " "
                            + analyze.bank_name;
                    System.out.println(execCmd);
                    hIP = si.IP;
                    hPort = si.Port;

                }
                //Tail Server
                else if (j == (icount - 1)) {//analyze.servers.size() - 1) ){
                    ServerInfo siPred = analyze.servers.get(j - 1);
                    execCmd += "TAIL " + si.IP + ":" + si.Port + " ";
                    execCmd += siPred.IP + ":" + siPred.Port + " localhost:0 localhost:" + MasterPort;
                    execCmd += " " + si.Start_delay + " " + si.Lifetime + " " + si.Receive + " " + si.Send + " "
                            + analyze.bank_name;
                    tIP = si.IP;
                    tPort = si.Port;
                    System.out.println(execCmd);
                }
                //Middle Server
                else {
                    ServerInfo siSucc = analyze.servers.get(j + 1);
                    ServerInfo siPred = analyze.servers.get(j - 1);
                    execCmd += "MIDDLE " + si.IP + ":" + si.Port + " ";
                    execCmd += siPred.IP + ":" + siPred.Port + " " + siSucc.IP + ":" + siSucc.Port
                            + " localhost:" + MasterPort;
                    execCmd += " " + si.Start_delay + " " + si.Lifetime + " " + si.Receive + " " + si.Send + " "
                            + analyze.bank_name;
                    System.out.println(execCmd);
                }
                Thread.sleep(500);
                Process pro = Runtime.getRuntime().exec(execCmd);
                serverPros.add(pro);
            }
            for (int j = icount; j < analyze.servers.size(); j++) {
                execCmd = "java Server ";
                ServerInfo si = analyze.servers.get(j);
                ServerInfo siPred = analyze.servers.get(j - 1);
                execCmd += "TAIL " + si.IP + ":" + si.Port + " ";
                execCmd += siPred.IP + ":" + siPred.Port + " localhost:0 localhost:" + MasterPort;
                execCmd += " " + si.Start_delay + " " + si.Lifetime + " " + si.Receive + " " + si.Send + " "
                        + analyze.bank_name;
                tIP = si.IP;
                tPort = si.Port;
                System.out.println(execCmd);
                Thread.sleep(500);
                Process pro = Runtime.getRuntime().exec(execCmd);
                serverPros.add(pro);
            }
        }
        ServerInfoForClient newServInfoForCli = new ServerInfoForClient(hPort, hIP, tPort, tIP, bn);
        servInfoCli.add(newServInfoForCli);
    }
    String banksCliParam = "";
    for (int i = 0; i < servInfoCli.size(); i++) {
        ServerInfoForClient temp = servInfoCli.get(i);
        String add = "@" + temp.bank_name + "#" + temp.HeadIP + ":" + temp.HeadPort + "#" + temp.TailIP + ":"
                + temp.TailPort;
        banksCliParam += add;
    }
    banksCliParam = banksCliParam.replaceFirst("@", "");
    //System.out.println(banksCliParam);

    // List of clients is saved so that we can wait for them to exit.
    ArrayList<Process> clientPros = new ArrayList<Process>();
    for (int i = 0; i < clientsList.size(); i++) {
        ClientInfo analyze = clientsList.get(i);
        String requestsString = "";
        if (analyze.isRandom) {
            double balance = Double.parseDouble(analyze.prob_balance);
            //System.out.println(analyze.prob_balance);
            double deposit = Double.parseDouble(analyze.prob_deposit);
            double withdraw = Double.parseDouble(analyze.prob_withdraw);
            int numRequests = Integer.parseInt(analyze.num_requests);
            for (int j = 0; j < numRequests; j++) {
                result = Math.random() * (1.0 - 0.0) + 0.0;
                int randAccount = (int) (Math.random() * (10001 - 0) + 0);
                double randAmount = Math.random() * (10001.00 - 0.0) + 0;
                int adjustMoney = (int) randAmount * 100;
                randAmount = (double) adjustMoney / 100.00;
                int randBank = (int) (Math.random() * (bankNames.length - 0) + 0);
                if (result < balance) {
                    //withdrawal#clientIPPORT%bank_name%accountnum%seq#amount
                    requestsString += "@balance#localhost:" + analyze.PortNumber + "%" + bankNames[randBank]
                            + "%" + randAccount + "%" + j;
                } else if (result < (deposit + balance)) {
                    requestsString += "@deposit#localhost:" + analyze.PortNumber + "%" + bankNames[randBank]
                            + "%" + randAccount + "%" + j + "#" + randAmount;
                } else {
                    requestsString += "@withdrawal#localhost:" + analyze.PortNumber + "%" + bankNames[randBank]
                            + "%" + randAccount + "%" + j + "#" + randAmount;
                }
            }

        } else {
            for (int j = 0; j < analyze.requests.size(); j++) {

                RequestInfo req = analyze.requests.get(j);
                //System.out.println("Sequence ###" + req.sequenceNum);
                if (req.request.equals("balance")) {
                    requestsString += "@" + req.request + "#localhost:" + analyze.PortNumber + "%"
                            + req.bankName + "%" + req.accountNum + "%" + req.sequenceNum;
                } else {
                    requestsString += "@" + req.request + "#localhost:" + analyze.PortNumber + "%"
                            + req.bankName + "%" + req.accountNum + "%" + req.sequenceNum + "#" + req.amount;
                }

            }
        }
        requestsString = requestsString.replaceFirst("@", "");
        String execCommand;
        int p = 60000 + i;
        if (analyze.isRandom) {
            execCommand = "java Client localhost:" + p + " " + banksCliParam + " " + requestsString + " "
                    + analyze.reply_timeout + " " + analyze.request_retries + " " + analyze.resend_head + " "
                    + analyze.prob_failure + " " + analyze.msg_send_delay + " " + analyze.prob_balance + ","
                    + analyze.prob_deposit + "," + analyze.prob_withdraw + "," + analyze.prob_transfer;
        } else {
            execCommand = "java Client localhost:" + p + " " + banksCliParam + " " + requestsString + " "
                    + analyze.reply_timeout + " " + analyze.request_retries + " " + analyze.resend_head + " "
                    + analyze.prob_failure + " " + analyze.msg_send_delay;

        }
        Thread.sleep(500);
        System.out.println(execCommand);
        System.out.println("Client " + (i + 1) + " started");
        Process cliPro = Runtime.getRuntime().exec(execCommand);
        clientPros.add(cliPro);
        //System.out.println(requestsString);
    }
    // Wait for all the clients to terminate
    for (Process clientPro : clientPros) {
        try {
            clientPro.waitFor();
            System.out.println("Client process finished.");
        } catch (InterruptedException e) {
            System.out.println("Interrupted while waiting for client.");
        }
    }
    // Sleep for two seconds
    Thread.sleep(2000);
    // Force termination of the servers
    for (Process serverPro : serverPros) {
        serverPro.destroy();
        System.out.println("Killed server.");
    }
    masterProcess.destroy();
    System.out.println("Killed Master");
    //System.out.println("asdf");
}

From source file:dependencies.DependencyResolving.java

/**
 * @param args the command line arguments
 *///from w  w w. j a va 2  s  .c o m
public static void main(String[] args) {
    // TODO code application logic here
    JSONParser parser = new JSONParser(); //we use JSONParser in order to be able to read from JSON file
    try { //here we declare the file reader and define the path to the file dependencies.json
        Object obj = parser.parse(new FileReader(
                "C:\\Users\\Vladimir\\Documents\\NetBeansProjects\\DependenciesResolving\\src\\dependencies\\dependencies.json"));
        JSONObject project = (JSONObject) obj; //a JSON object containing all the data in the .json file
        JSONArray dependencies = (JSONArray) project.get("dependencies"); //get array of objects with key "dependencies"
        System.out.print("We need to install the following dependencies: ");
        Iterator<String> iterator = dependencies.iterator(); //define an iterator over the array "dependencies"
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        } //on the next line we declare another object, which parses a Parser object and reads from all_packages.json
        Object obj2 = parser.parse(new FileReader(
                "C:\\Users\\Vladimir\\Documents\\NetBeansProjects\\DependenciesResolving\\src\\dependencies\\all_packages.json"));
        JSONObject tools = (JSONObject) obj2; //a JSON object containing all thr data in the file all_packages.json
        for (int i = 0; i < dependencies.size(); i++) {
            if (tools.containsKey(dependencies.get(i))) {
                System.out.println(
                        "In order to install " + dependencies.get(i) + ", we need the following programs:");
                JSONArray temporaryArray = (JSONArray) tools.get(dependencies.get(i)); //a temporary JSON array in which we store the keys and values of the dependencies
                for (i = 0; i < temporaryArray.size(); i++) {
                    System.out.println(temporaryArray.get(i));
                }
                ArrayList<Object> arraysOfJsonData = new ArrayList<Object>(); //an array in which we will store the keys of the objects, after we use the values and won't need them anymore
                for (i = 0; i < temporaryArray.size(); i++) {
                    System.out.println("Installing " + temporaryArray.get(i));
                }
                while (!temporaryArray.isEmpty()) {

                    for (Object element : temporaryArray) {

                        if (tools.containsKey(element)) {
                            JSONArray secondaryArray = (JSONArray) tools.get(element); //a temporary array within the scope of the if-statement
                            if (secondaryArray.size() != 0) {
                                System.out.println("In order to install " + element + ", we need ");
                            }
                            for (i = 0; i < secondaryArray.size(); i++) {
                                System.out.println(secondaryArray.get(i));
                            }

                            for (Object o : secondaryArray) {

                                arraysOfJsonData.add(o);
                                //here we create a file with the installed dependency
                                File file = new File(
                                        "C:\\Users\\Vladimir\\Documents\\NetBeansProjects\\DependenciesResolving\\src\\dependencies\\installed_modules\\"
                                                + o);
                                if (file.createNewFile()) {
                                    System.out.println(file.getName() + " is installed!");
                                } else {
                                }
                            }
                            secondaryArray.clear();
                        }
                    }
                    temporaryArray.clear();
                    for (i = 0; i < arraysOfJsonData.size(); i++) {
                        temporaryArray.add(arraysOfJsonData.get(i));
                    }
                    arraysOfJsonData.clear();
                }
            }
        }
        Set<String> keys = tools.keySet(); // here we define a set of keys of the objects in all_packages.json
        for (String s : keys) {
            File file = new File(
                    "C:\\Users\\Vladimir\\Documents\\NetBeansProjects\\DependenciesResolving\\src\\dependencies\\installed_modules\\"
                            + s);
            if (file.createNewFile()) {
                System.out.println(file.getName() + " is installed.");
            } else {
            }
        }
    } catch (IOException ex) {
        Logger.getLogger(DependencyResolving.class.getName()).log(Level.SEVERE, null, ex);
    } catch (ParseException ex) {
        Logger.getLogger(DependencyResolving.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:my.yelp.populate.java

public static void main(String[] args)
        throws FileNotFoundException, ParseException, IOException, java.text.ParseException {
    try {/*from w ww . j a  va  2  s  .  co  m*/

        DbConnection A1 = new DbConnection();
        Connection con = A1.getConnection();

        JSONParser jsonParser;
        jsonParser = new JSONParser();

        Object obj1 = jsonParser.parse(new FileReader("C:\\Users\\Sanjay Desai\\Desktop\\yelp_user.json"));
        Object obj2 = jsonParser.parse(new FileReader("C:\\Users\\Sanjay Desai\\Desktop\\yelp_business.json"));
        Object obj3 = jsonParser.parse(new FileReader("C:\\Users\\Sanjay Desai\\Desktop\\yelp_review.json"));
        Object obj4 = jsonParser.parse(new FileReader("C:\\Users\\Sanjay Desai\\Desktop\\yelp_checkin.json"));

        JSONArray jsonArray1;
        jsonArray1 = (JSONArray) obj1;

        JSONArray jsonArray2;
        jsonArray2 = (JSONArray) obj2;

        JSONArray jsonArray3;
        jsonArray3 = (JSONArray) obj3;

        JSONArray jsonArray4;
        jsonArray4 = (JSONArray) obj4;

        // yelp_user
        String yelping_since, name1, user_id, type1;
        Long review_count1, fans;
        Double average_stars;
        Statement stmt;

        stmt = con.createStatement();
        stmt.executeUpdate("Delete from N_User");

        for (int i = 0; i < (jsonArray1.size()); i++)

        {
            JSONObject jsonObject = (JSONObject) jsonArray1.get(i);
            yelping_since = (String) jsonObject.get("yelping_since") + "-01";

            JSONArray friends = (JSONArray) jsonObject.get("friends");
            int friends_size = friends.size();

            review_count1 = (Long) jsonObject.get("review_count");
            name1 = (String) jsonObject.get("name");
            user_id = (String) jsonObject.get("user_id");
            fans = (Long) jsonObject.get("fans");
            average_stars = (Double) jsonObject.get("average_stars");
            type1 = (String) jsonObject.get("type");

            try (PreparedStatement pstmt1 = con.prepareStatement(
                    "Insert INTO N_User(yelping_since,friends_size,review_count,name,user_id,fans,average_stars,type) VALUES(?,?,?,?,?,?,?,?)")) {

                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                java.util.Date myDate = format.parse(yelping_since);

                pstmt1.setDate(1, new java.sql.Date(myDate.getTime()));
                pstmt1.setInt(2, friends_size);
                pstmt1.setLong(3, review_count1);
                pstmt1.setString(4, name1);
                pstmt1.setString(5, user_id);
                pstmt1.setLong(6, fans);
                pstmt1.setDouble(7, average_stars);
                pstmt1.setString(8, type1);
                pstmt1.executeUpdate();
            } catch (java.text.ParseException ex) {
                Logger.getLogger(populate.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

        //yelp_business

        String business_id, address, city, state, name, type_business;

        Double stars;

        for (int i = 0; i < jsonArray2.size(); i++) {
            JSONObject jsonObject = (JSONObject) jsonArray2.get(i);
            business_id = (String) jsonObject.get("business_id");
            address = (String) jsonObject.get("full_address");
            city = (String) jsonObject.get("city");
            state = (String) jsonObject.get("state");
            name = (String) jsonObject.get("name");
            stars = (Double) jsonObject.get("stars");
            type_business = (String) jsonObject.get("type");

            try (PreparedStatement pstmt2 = con.prepareStatement(
                    "Insert INTO N_Business(business_id,address,city,state,name,stars,type_business) VALUES(?,?,?,?,?,?,?)")) {
                pstmt2.setString(1, business_id);
                pstmt2.setString(2, address);
                pstmt2.setString(3, city);
                pstmt2.setString(4, state);
                pstmt2.setString(5, name);
                pstmt2.setDouble(6, stars);
                pstmt2.setString(7, type_business);
                pstmt2.executeUpdate();
                pstmt2.close();
            }

        }

        //Category Table
        String[] categories = { "Active Life", "Arts & Entertainment", "Automotive", "Car Rental", "Cafes",
                "Beauty & Spas", "Convenience Stores", "Dentists", "Doctors", "Drugstores", "Department Stores",
                "Education", "Event Planning & Services", "Flowers & Gifts", "Food", "Health & Medical",
                "Home Services", "Home & Garden", "Hospitals", "Hotels & travel", "Hardware stores", "Grocery",
                "Medical Centers", "Nurseries & Gardening", "Nightlife", "Restaurants", "Shopping",
                "Transportation" };

        JSONArray category;
        String[] individual_category = new String[100];
        int count = 0, flag = 0, m = 0, n = 0;
        String[] business_category = new String[50];
        String[] subcategory = new String[50];

        for (int i = 0; i < jsonArray2.size(); i++) {
            JSONObject jsonObject3 = (JSONObject) jsonArray2.get(i);
            String business_id2 = (String) jsonObject3.get("business_id");
            category = (JSONArray) jsonObject3.get("categories");
            for (int j = 0; j < category.size(); j++) {
                individual_category[j] = (String) category.get(j);
                count = count + 1;
            }
            for (int k = 0; k < count; k++) {
                for (String categorie : categories) {

                    if (individual_category[k].equals(categorie)) {
                        flag = 1;
                        break;
                    }
                }
                if (flag == 1) {
                    business_category[m] = individual_category[k];
                    m = m + 1;
                    flag = 0;
                } else {
                    subcategory[n] = individual_category[k];
                    n = n + 1;
                }
            }
            for (int p = 0; p < m; p++) {
                for (int q = 0; q < n; q++) {
                    try (PreparedStatement pstmt3 = con.prepareStatement(
                            "INSERT INTO N_Category(business_id,category,subcategory) VALUES(?,?,?)")) {
                        pstmt3.setString(1, business_id2);
                        pstmt3.setString(2, business_category[p]);
                        pstmt3.setString(3, subcategory[q]);
                        pstmt3.executeUpdate();

                    }
                }
            }
            count = 0;
            m = 0;
            n = 0;
        }

        //yelp_review

        String user_id3, review_id, type3, business_id3, text, text1, review_date;
        Long stars3;
        int votes = 0;
        Integer no_votes;

        JSONObject votes_info;
        Set<String> keys;

        for (int i = 0; i < jsonArray3.size(); i++) {
            JSONObject jsonObject = (JSONObject) jsonArray3.get(i);

            votes_info = (JSONObject) jsonObject.get("votes");
            keys = votes_info.keySet();
            for (String r_key : keys) {
                votes = (int) (votes + (Long) votes_info.get(r_key));
            }
            no_votes = toIntExact(votes);
            user_id3 = (String) jsonObject.get("user_id");

            review_id = (String) jsonObject.get("review_id");
            business_id3 = (String) jsonObject.get("business_id");
            review_date = (String) jsonObject.get("date");
            text1 = (String) jsonObject.get("text");
            text = text1.substring(0, Math.min(1000, text1.length()));
            stars3 = (Long) jsonObject.get("stars");
            type3 = (String) jsonObject.get("type");

            try (PreparedStatement pstmt4 = con.prepareStatement(
                    "Insert INTO N_Review(no_votes,user_id,review_id,business_id,review_date,text,stars,type) VALUES(?,?,?,?,?,?,?,?)")) {
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                java.util.Date myDate = format.parse(review_date);

                pstmt4.setInt(1, no_votes);
                pstmt4.setString(2, user_id3);
                pstmt4.setString(3, review_id);
                pstmt4.setString(4, business_id3);
                pstmt4.setDate(5, new java.sql.Date(myDate.getTime()));
                pstmt4.setString(6, text);
                pstmt4.setLong(7, stars3);
                pstmt4.setString(8, type3);
                pstmt4.executeUpdate();
                pstmt4.close();
            }

        }

        //Checkin_Info
        JSONObject checkin_info;
        String business_id4;
        Long check_in_count;
        Set<String> keys1;
        String[] timing = new String[10];
        int n1 = 0, time, hour;

        //Inserting into checkin_info
        for (int i = 0; i < jsonArray4.size(); i++) {
            JSONObject jsonObject4 = (JSONObject) jsonArray4.get(i);
            checkin_info = (JSONObject) jsonObject4.get("checkin_info");
            business_id4 = (String) jsonObject4.get("business_id");
            keys1 = checkin_info.keySet();

            for (String key : keys1) {
                check_in_count = (Long) checkin_info.get(key);
                for (String x : key.split("-")) {
                    timing[n1] = x;
                    n1 = n1 + 1;
                }
                n1 = 0;
                hour = Integer.parseInt(timing[0]);
                time = Integer.parseInt(timing[1]);

                try (PreparedStatement pstmt5 = con.prepareStatement(
                        "INSERT INTO check_info(business_id,hour,day,check_in_count)VALUES(?,?,?,?)")) {
                    pstmt5.setString(1, business_id4);
                    pstmt5.setInt(2, hour);
                    pstmt5.setInt(3, time);
                    pstmt5.setLong(4, check_in_count);
                    pstmt5.executeUpdate();
                }
            }

        }

        con.close();

    } catch (SQLException ex) {
        Logger.getLogger(populate.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:featureExtractor.popularityMeasure.java

static double ParseJSON_getScore(String s) throws ParseException {
    JSONObject json = (JSONObject) new JSONParser().parse(s);
    JSONArray results = (JSONArray) json.get("result");
    JSONObject resultObject = (JSONObject) results.get(0);
    return (double) resultObject.get("score");
}

From source file:manager.computerVisionManager.java

public static String getImageDescription(String path) {
    if (json == null) {
        getJson(path);//from   w  ww . jav a2s  . c o m
    }
    try {
        System.out.println(json.toString());
        JSONArray captions = (JSONArray) json.get("captions");
        JSONObject text = (JSONObject) captions.get(0);
        return text.get("text").toString();
    } catch (Exception e) {
        System.err.println(e.getMessage());
    }
    return "error";
}