Example usage for org.json.simple JSONObject keySet

List of usage examples for org.json.simple JSONObject keySet

Introduction

In this page you can find the example usage for org.json.simple JSONObject keySet.

Prototype

Set<K> keySet();

Source Link

Document

Returns a Set view of the keys contained in this map.

Usage

From source file:me.timothy.ddd.DrunkDuckDispatch.java

License:asdf

public static void main(String[] args) throws LWJGLException {
    try {/*w  ww. ja  va  2 s. c  om*/
        float defaultDisplayWidth = SizeScaleSystem.EXPECTED_WIDTH / 2;
        float defaultDisplayHeight = SizeScaleSystem.EXPECTED_HEIGHT / 2;
        boolean fullscreen = false, defaultDisplay = !fullscreen;
        File resolutionInfo = new File("graphics.json");

        if (resolutionInfo.exists()) {
            try (FileReader fr = new FileReader(resolutionInfo)) {
                JSONObject obj = (JSONObject) new JSONParser().parse(fr);
                Set<?> keys = obj.keySet();
                for (Object o : keys) {
                    if (o instanceof String) {
                        String key = (String) o;
                        switch (key.toLowerCase()) {
                        case "width":
                            defaultDisplayWidth = JSONCompatible.getFloat(obj, key);
                            break;
                        case "height":
                            defaultDisplayHeight = JSONCompatible.getFloat(obj, key);
                            break;
                        case "fullscreen":
                            fullscreen = JSONCompatible.getBoolean(obj, key);
                            defaultDisplay = !fullscreen;
                            break;
                        }
                    }
                }
            } catch (IOException | ParseException e) {
                e.printStackTrace();
            }
            float expHeight = defaultDisplayWidth
                    * (SizeScaleSystem.EXPECTED_HEIGHT / SizeScaleSystem.EXPECTED_WIDTH);
            float expWidth = defaultDisplayHeight
                    * (SizeScaleSystem.EXPECTED_WIDTH / SizeScaleSystem.EXPECTED_HEIGHT);
            if (Math.round(defaultDisplayWidth) != Math.round(expWidth)) {
                if (defaultDisplayHeight < expHeight) {
                    System.err.printf("%f x %f is an invalid resolution; adjusting to %f x %f\n",
                            defaultDisplayWidth, defaultDisplayHeight, defaultDisplayWidth, expHeight);
                    defaultDisplayHeight = expHeight;
                } else {
                    System.err.printf("%f x %f is an invalid resolution; adjusting to %f x %f\n",
                            defaultDisplayWidth, defaultDisplayHeight, expWidth, defaultDisplayHeight);
                    defaultDisplayWidth = expWidth;
                }
            }
        }
        File dir = null;
        String os = getOS();
        if (os.equals("windows")) {
            dir = new File(System.getenv("APPDATA"), "timgames/");
        } else {
            dir = new File(System.getProperty("user.home"), ".timgames/");
        }
        File lwjglDir = new File(dir, "lwjgl-2.9.1/");
        Resources.init();
        Resources.downloadIfNotExists(lwjglDir, "lwjgl-2.9.1.zip", "http://umad-barnyard.com/lwjgl-2.9.1.zip",
                "Necessary LWJGL natives couldn't be found, I can attempt "
                        + "to download it, but I make no promises",
                "Unfortunately I was unable to download it, so I'll open up the "
                        + "link to the official download. Make sure you get LWJGL version 2.9.1, "
                        + "and you put it at " + dir.getAbsolutePath() + "/lwjgl-2.9.1.zip",
                new Runnable() {

                    @Override
                    public void run() {
                        if (!Desktop.isDesktopSupported()) {
                            JOptionPane.showMessageDialog(null,
                                    "I couldn't " + "even do that! Download it manually and try again");
                            return;
                        }

                        try {
                            Desktop.getDesktop().browse(new URI("http://www.lwjgl.org/download.php"));
                        } catch (IOException | URISyntaxException e) {
                            JOptionPane.showMessageDialog(null,
                                    "Oh cmon.. Address is http://www.lwjgl.org/download.php, good luck");
                            System.exit(1);
                        }
                    }

                }, 5843626);

        Resources.extractIfNotFound(lwjglDir, "lwjgl-2.9.1.zip", "lwjgl-2.9.1");
        System.setProperty("org.lwjgl.librarypath",
                new File(dir, "lwjgl-2.9.1/lwjgl-2.9.1/native/" + os).getAbsolutePath()); // deal w/ it
        System.setProperty("net.java.games.input.librarypath", System.getProperty("org.lwjgl.librarypath"));

        Resources.downloadIfNotExists("entities.json", "http://umad-barnyard.com/ddd/entities.json", 16142);
        Resources.downloadIfNotExists("map.binary", "http://umad-barnyard.com/ddd/map.binary", 16142);
        Resources.downloadIfNotExists("victory.txt", "http://umad-barnyard.com/ddd/victory.txt", 168);
        Resources.downloadIfNotExists("failure.txt", "http://umad-barnyard.com/ddd/failure.txt", 321);
        File resFolder = new File("resources/");
        if (!resFolder.exists() && !new File("player-still.png").exists()) {
            Resources.downloadIfNotExists("resources.zip", "http://umad-barnyard.com/ddd/resources.zip", 54484);
            Resources.extractIfNotFound(new File("."), "resources.zip", "player-still.png");
            new File("resources.zip").delete();
        }
        File soundFolder = new File("sounds/");
        if (!soundFolder.exists()) {
            soundFolder.mkdirs();
            Resources.downloadIfNotExists("sounds/sounds.zip", "http://umad-barnyard.com/ddd/sounds.zip",
                    1984977);
            Resources.extractIfNotFound(soundFolder, "sounds.zip", "asdfasdffadasdf");
            new File(soundFolder, "sounds.zip").delete();
        }
        AppGameContainer appgc;
        ddd = new DrunkDuckDispatch();
        appgc = new AppGameContainer(ddd);
        appgc.setTargetFrameRate(60);
        appgc.setShowFPS(false);
        appgc.setAlwaysRender(true);
        if (fullscreen) {
            DisplayMode[] modes = Display.getAvailableDisplayModes();
            DisplayMode current, best = null;
            float ratio = 0f;
            for (int i = 0; i < modes.length; i++) {
                current = modes[i];
                float rX = (float) current.getWidth() / SizeScaleSystem.EXPECTED_WIDTH;
                float rY = (float) current.getHeight() / SizeScaleSystem.EXPECTED_HEIGHT;
                System.out.println(current.getWidth() + "x" + current.getHeight() + " -> " + rX + "x" + rY);
                if (rX == rY && rX > ratio) {
                    best = current;
                    ratio = rX;
                }
            }
            if (best == null) {
                System.out.println("Failed to find an appropriately scaled resolution, using default display");
                defaultDisplay = true;
            } else {
                appgc.setDisplayMode(best.getWidth(), best.getHeight(), true);
                SizeScaleSystem.setRealHeight(best.getHeight());
                SizeScaleSystem.setRealWidth(best.getWidth());
                System.out.println("I choose " + best.getWidth() + "x" + best.getHeight());
            }
        }

        if (defaultDisplay) {
            SizeScaleSystem.setRealWidth(Math.round(defaultDisplayWidth));
            SizeScaleSystem.setRealHeight(Math.round(defaultDisplayHeight));
            appgc.setDisplayMode(Math.round(defaultDisplayWidth), Math.round(defaultDisplayHeight), false);
        }
        ddd.logger.info(
                "SizeScaleSystem: " + SizeScaleSystem.getRealWidth() + "x" + SizeScaleSystem.getRealHeight());
        appgc.start();
    } catch (SlickException ex) {
        LogManager.getLogger(DrunkDuckDispatch.class.getSimpleName()).catching(Level.ERROR, ex);
    }
}

From source file:my.yelp.populate.java

public static void main(String[] args)
        throws FileNotFoundException, ParseException, IOException, java.text.ParseException {
    try {/*from w w w  . 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:ServerStatus.java

License:asdf

/**
 * @param args the command line arguments
 *///w ww .j av  a  2 s  . c  om
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
 *//* w w  w  . j  a va  2 s .  c  om*/
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:iracing.webapi.LicenseLevelParser.java

static List<LicenseLevel> parse(String json) {
    //var licenseLevels = extractJSON('{"22":{"groupId":6,"name":"Pro+%282.0%29","id":22,"colorIndex":240},"23":{"groupId":6,"name":"Pro+%283.0%29","id":23,"colorIndex":240},"24":{"groupId":6,"name":"Pro+%284.0%29","id":24,"colorIndex":240},"25":{"groupId":7,"name":"Pro%2FWC+%281.0%29","id":25,"colorIndex":240},"26":{"groupId":7,"name":"Pro%2FWC+%282.0%29","id":26,"colorIndex":240},"27":{"groupId":7,"name":"Pro%2FWC+%283.0%29","id":27,"colorIndex":240},"28":{"groupId":7,"name":"Pro%2FWC+%284.0%29","id":28,"colorIndex":240},"10":{"groupId":3,"name":"Class+C+%282.0%29","id":10,"colorIndex":116},"11":{"groupId":3,"name":"Class+C+%283.0%29","id":11,"colorIndex":116},"12":{"groupId":3,"name":"Class+C+%284.0%29","id":12,"colorIndex":116},"13":{"groupId":4,"name":"Class+B+%281.0%29","id":13,"colorIndex":86},"14":{"groupId":4,"name":"Class+B+%282.0%29","id":14,"colorIndex":86},"15":{"groupId":4,"name":"Class+B+%283.0%29","id":15,"colorIndex":86},"16":{"groupId":4,"name":"Class+B+%284.0%29","id":16,"colorIndex":86},"17":{"groupId":5,"name":"Class+A+%281.0%29","id":17,"colorIndex":107},"18":{"groupId":5,"name":"Class+A+%282.0%29","id":18,"colorIndex":107},"19":{"groupId":5,"name":"Class+A+%283.0%29","id":19,"colorIndex":107},"1":{"groupId":1,"name":"Rookie+%281.0%29","id":1,"colorIndex":112},"2":{"groupId":1,"name":"Rookie+%282.0%29","id":2,"colorIndex":112},"3":{"groupId":1,"name":"Rookie+%283.0%29","id":3,"colorIndex":112},"4":{"groupId":1,"name":"Rookie+%284.0%29","id":4,"colorIndex":112},"5":{"groupId":2,"name":"Class+D+%281.0%29","id":5,"colorIndex":130},"6":{"groupId":2,"name":"Class+D+%282.0%29","id":6,"colorIndex":130},"7":{"groupId":2,"name":"Class+D+%283.0%29","id":7,"colorIndex":130},"8":{"groupId":2,"name":"Class+D+%284.0%29","id":8,"colorIndex":130},"9":{"groupId":3,"name":"Class+C+%281.0%29","id":9,"colorIndex":116},"20":{"groupId":5,"name":"Class+A+%284.0%29","id":20,"colorIndex":107},"21":{"groupId":6,"name":"Pro+%281.0%29","id":21,"colorIndex":240}}');
    JSONParser parser = new JSONParser();
    List<LicenseLevel> output = null;
    try {/*w  ww.  j  a va  2  s.c  o m*/
        JSONObject root = (JSONObject) parser.parse(json);
        output = new ArrayList<LicenseLevel>();
        for (Object key : root.keySet()) {
            LicenseLevel ll = new LicenseLevel();
            JSONObject o = (JSONObject) root.get(key);
            ll.setLicenseGroupId(getInt(o, "groupId"));
            ll.setName(getString(o, "name", true));
            ll.setId(getInt(o, "id"));
            output.add(ll);
        }
    } catch (ParseException ex) {
        Logger.getLogger(LicenseLevelParser.class.getName()).log(Level.SEVERE, null, ex);
    }
    return output;
}

From source file:net.duckling.falcon.xss.JSONConfig.java

private static void addProtocols(Whitelist whitelist, JSONObject config) {
    JSONObject protocolsJson = (JSONObject) config.get("protocols");
    for (String key : protocolsJson.keySet()) {
        String[] pair = key.split("\\.");
        if (pair.length == 2) {
            JSONArray protocols = (JSONArray) protocolsJson.get(key);
            for (Object p : protocols) {
                whitelist.addProtocols(pair[0], pair[1], (String) p);
            }//from  ww  w  .  j a  v  a  2s  . c o m
        }
    }
}

From source file:net.duckling.falcon.xss.JSONConfig.java

private static void addTags(Whitelist whitelist, JSONObject config) {
    JSONObject whiteListJson = (JSONObject) config.get("whiteList");
    for (String tagname : whiteListJson.keySet()) {
        whitelist.addTags(tagname);/*from   w  w  w . java 2s. c o m*/
        JSONArray attributes = (JSONArray) whiteListJson.get(tagname);
        for (Object attribute : attributes) {
            whitelist.addAttributes(tagname, (String) attribute);
        }
    }
}

From source file:io.fabric8.mq.controller.util.BrokerJmxUtils.java

public static List<ObjectName> getDestinations(J4pClient client, ObjectName root, String type)
        throws Exception {
    List<ObjectName> list = new ArrayList<>();
    String objectNameStr = root.toString() + ",destinationType=" + type + ",destinationName=*";
    J4pResponse<J4pReadRequest> response = client
            .execute(new J4pReadRequest(new ObjectName(objectNameStr), "Name"));
    JSONObject value = response.getValue();
    for (Object key : value.keySet()) {
        ObjectName objectName = new ObjectName(key.toString());
        list.add(objectName);/*from  www.  j a v  a2s  .  c  o m*/
    }

    return list;
}

From source file:fr.free.movierenamer.utils.JSONUtils.java

public static JSONObject selectFirstObject(final JSONObject rootObject) {
    try {//from   w ww  .j  a va2  s .co  m
        JSONObject toSearch = rootObject;
        return (JSONObject) toSearch.get(toSearch.keySet().iterator().next());
    } catch (Exception e) {
        //
    }
    return null;
}

From source file:mml.handler.json.Dialect.java

private static boolean compareObjects(JSONObject o1, JSONObject o2) {
    boolean res = true;
    Set<String> keys = o1.keySet();
    Iterator<String> iter = keys.iterator();
    while (iter.hasNext() && res) {
        String key = iter.next();
        Object obj1 = o1.get(key);
        Object obj2 = o2.get(key);
        if (obj1 != null && obj2 != null && obj1.getClass().equals(obj2.getClass())) {
            if (obj1 instanceof String)
                res = obj1.equals(obj2);
            else if (obj1 instanceof Number)
                return obj1.equals(obj2);
            else if (obj1 instanceof JSONArray)
                res = compareArrays((JSONArray) obj1, (JSONArray) obj2);
            else if (obj1 instanceof JSONObject)
                res = compareObjects((JSONObject) obj1, (JSONObject) obj2);
            else if (obj1 instanceof Boolean)
                res = obj1.equals(obj2);
            else// w w w  . j  av  a  2  s .c  om
                res = false;
        } else
            res = false;
    }
    return res;
}