List of usage examples for org.json.simple JSONObject get
V get(Object key);
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 ww w. jav a2 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:my.yelp.populate.java
public static void main(String[] args) throws FileNotFoundException, ParseException, IOException, java.text.ParseException { try {//from w w w .j ava 2s. 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:at.nonblocking.cliwix.cli.CliwixCliClient.java
public static void main(String[] args) throws Exception { Options options = null;//ww w. ja v a2s .c o m try { options = Options.parseArgs(args); } catch (CliwixCliClientArgumentException e) { if (debug) console.printStacktrace(e); console.printlnError("Error: Invalid arguments: " + e.getMessage()); Options.printUsage(); console.exit(EXIT_STATUS_FAIL); return; } if (options == null || Options.COMMAND_HELP.equals(options.getCommand())) { Options.printUsage(); console.exit(0); return; } if (Options.COMMAND_CREATE_CONFIG.equals(options.getCommand())) { if (args.length < 2) { console.printlnError("Error: No config file location given!"); console.exit(EXIT_STATUS_FAIL); return; } File configFile = new File(args[1]); options.copyDefaultPropertiesTo(configFile); console.println("Configuration saved under: " + configFile.getAbsolutePath()); console.exit(0); return; } debug = options.isDebug(); String cliwixServerUrl = options.getServerCliwixUrl(); String username = options.getServerUsername(); String password = options.getServerPassword(); if (cliwixServerUrl == null) { console.printlnError("Error: Property server.cliwix.url is required!"); console.exit(EXIT_STATUS_FAIL); return; } cookieManager.clear(); //Login if (username != null && password != null) { JSONObject loginData = new JSONObject(); loginData.put("username", username); loginData.put("password", password); JSONObject result = postJson(cliwixServerUrl, "/services/login", loginData); JSONObject loginResult = (JSONObject) result.get("loginResult"); if (loginResult.get("succeeded") == Boolean.TRUE) { console.println("Login successful"); } else { console.printlnError("Error: Login failed! Reason: " + loginData.get("errorMessage")); console.exit(EXIT_STATUS_FAIL); return; } } else if (username != null) { console.printlnError("Error: If -user is set -pass is required!"); console.exit(EXIT_STATUS_FAIL); return; } else if (password != null) { console.printlnError("Error: If -pass is set -user is required!"); console.exit(EXIT_STATUS_FAIL); return; } switch (options.getCommand()) { case Options.COMMAND_INFO: doInfo(cliwixServerUrl, options); break; case Options.COMMAND_EXPORT: doExport(cliwixServerUrl, options); break; case Options.COMMAND_IMPORT: doImport(cliwixServerUrl, options); break; default: case Options.COMMAND_HELP: Options.printUsage(); } }
From source file:ServerStatus.java
License:asdf
/** * @param args the command line arguments *//*from w ww . j a v 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:com.headswilllol.basiclauncher.Launcher.java
public static void main(String[] args) { int i = 0;/*from w w w . j ava 2s . c o m*/ for (String s : args) { if (s.equalsIgnoreCase("-dir")) { downloadDir = args[i + 1]; if (!new File(downloadDir).exists()) { try { new File(downloadDir).mkdir(); } catch (Exception ex) { ex.printStackTrace(); progress = "Failed to create download directory"; fail = "Errors occurred; see console for details"; launcher.paintImmediately(0, 0, width, height); } } } i += 1; } try { JSONObject info = ((JSONObject) new JSONParser() .parse(new InputStreamReader(Launcher.class.getResourceAsStream("/gameinfo.json")))); NAME = (String) info.get("name"); FOLDER_NAME = "." + NAME.toLowerCase(); JSON_LOCATION = (String) info.get("resource-info"); } catch (Exception ex) { ex.printStackTrace(); progress = "Failed to retrieve program information!"; fail = "Errors occurred; see log for details"; createExceptionLog(ex); launcher.paintImmediately(0, 0, width, height); } SwingUtilities.invokeLater(new Runnable() { public void run() { createAndShowGUI(); } }); }
From source file:fr.bmartel.protocol.google.main.LaunchOauthApiServer.java
/** * The main method./*from w ww . j a v a 2 s.co m*/ * * @param args the arguments */ public static void main(String[] args) { webPath = ""; clientId = ""; clientSecret = ""; if (args.length == 3) { for (int i = 0; i < 3; i++) { if (args[i].toLowerCase().startsWith("webpath=")) webPath = args[i].substring(args[i].indexOf("webpath=") + "webpath=".length() + 1, args[i].length()); if (args[i].toLowerCase().startsWith("clientid=")) clientId = args[i].substring(args[i].indexOf("clientid=") + "clientid=".length() + 1, args[i].length()); if (args[i].toLowerCase().startsWith("clientsecret=")) clientSecret = args[i].substring( args[i].indexOf("clientsecret=") + "clientsecret=".length() + 1, args[i].length()); } if (webPath.equals("")) { printHelp("Error web path is missing"); return; } else if (clientId.equals("")) { printHelp("Error client Id is missing"); return; } else if (clientSecret.equals("")) { printHelp("Error client secret is missing"); return; } } else { printHelp(""); return; } // start http server HttpServer server = new HttpServer(SERVER_PORT); websocketServer = new WebsocketServer(WEBSOCKET_SERVER_PORT); websocketServer.addServerEventListener(new IClientEventListener() { @SuppressWarnings("unchecked") @Override public void onMessageReceivedFromClient(final IWebsocketClient client, String message) { JSONObject obj = (JSONObject) JSONValue.parse(message); if (obj != null && obj.containsKey(JsonConstants.API_ACTION)) { System.out.println("[API] > " + obj.toJSONString()); String action = obj.get(JsonConstants.API_ACTION).toString(); if (action != null) { if (action.equals(JsonConstants.API_REGISTRATION_STATE)) { JSONObject registrationResponse = new JSONObject(); if (calendarNotifManager != null && calendarNotifManager.getOauthRegistration() != null) { registrationResponse.put(JsonConstants.GOOGLE_OAUTH_DEVICE_CODE, calendarNotifManager.getOauthRegistration().getDeviceCode()); registrationResponse.put(JsonConstants.GOOGLE_OAUTH_EXPIRING_BEFORE, calendarNotifManager.getOauthRegistration().getExpiringBefore()); registrationResponse.put(JsonConstants.GOOGLE_OAUTH_INTERVAL, calendarNotifManager.getOauthRegistration().getInterval()); registrationResponse.put(JsonConstants.GOOGLE_OAUTH_USERCODE, calendarNotifManager.getOauthRegistration().getUserCode()); registrationResponse.put(JsonConstants.GOOGLE_OAUTH_VERIFICATION_URL, calendarNotifManager.getOauthRegistration().getVerificationUrl()); } System.out.println("[API] < " + registrationResponse.toJSONString()); client.sendMessage(registrationResponse.toJSONString()); } else if (action.equals(JsonConstants.API_TOKEN_STATE)) { JSONObject requestTokenResponse = new JSONObject(); if (calendarNotifManager != null && calendarNotifManager.getCurrentToken() != null) { requestTokenResponse.put(JsonConstants.GOOGLE_OAUTH_ACCESS_TOKEN, calendarNotifManager.getCurrentToken().getAccessToken()); requestTokenResponse.put(JsonConstants.GOOGLE_OAUTH_TOKEN_TYPE, calendarNotifManager.getCurrentToken().getTokenType()); requestTokenResponse.put(JsonConstants.GOOGLE_OAUTH_EXPIRE_IN, calendarNotifManager.getCurrentToken().getExpiresIn()); } System.out.println("[API] < " + requestTokenResponse.toJSONString()); client.sendMessage(requestTokenResponse.toJSONString()); } else if (action.equals(JsonConstants.API_REGISTRATION)) { calendarNotifManager = new CalendarNotifManager(clientId, clientSecret); calendarNotifManager.requestDeviceAuth(new IOauthDeviceResponseListener() { @Override public void onResponseReceived(OauthForDeviceResponse response) { if (response != null) { JSONObject registrationResponse = new JSONObject(); registrationResponse.put(JsonConstants.GOOGLE_OAUTH_DEVICE_CODE, response.getDeviceCode()); registrationResponse.put(JsonConstants.GOOGLE_OAUTH_EXPIRING_BEFORE, response.getExpiringBefore()); registrationResponse.put(JsonConstants.GOOGLE_OAUTH_INTERVAL, response.getInterval()); registrationResponse.put(JsonConstants.GOOGLE_OAUTH_USERCODE, response.getUserCode()); registrationResponse.put(JsonConstants.GOOGLE_OAUTH_VERIFICATION_URL, response.getVerificationUrl()); System.out.println("[API] < " + registrationResponse.toJSONString()); client.sendMessage(registrationResponse.toJSONString()); } } }); } else if (action.equals(JsonConstants.API_REQUEST_TOKEN)) { if (calendarNotifManager != null) { calendarNotifManager.requestToken(new IRequestTokenListener() { @Override public void onRequestTokenReceived(OauthToken token) { if (token != null) { JSONObject requestTokenResponse = new JSONObject(); requestTokenResponse.put(JsonConstants.GOOGLE_OAUTH_ACCESS_TOKEN, token.getAccessToken()); requestTokenResponse.put(JsonConstants.GOOGLE_OAUTH_TOKEN_TYPE, token.getTokenType()); requestTokenResponse.put(JsonConstants.GOOGLE_OAUTH_EXPIRE_IN, token.getExpiresIn()); System.out.println("[API] < " + requestTokenResponse.toJSONString()); client.sendMessage(requestTokenResponse.toJSONString()); } } @Override public void onRequestTokenError(String description) { String response = "{\"error\":\"request token error\",\"error_description\":\"" + description + "\"}"; System.out.println("[API] < " + response); client.sendMessage(response); } }); } } else if (action.equals(JsonConstants.API_REVOKE_TOKEN)) { if (calendarNotifManager != null) { calendarNotifManager.revokeToken(new IRevokeTokenListener() { @Override public void onSuccess() { System.out.println("[API] < " + "{\"revokeToken\":\"success\"}"); client.sendMessage("{\"revokeToken\":\"success\"}"); } @Override public void onError(String description) { String response = "{\"error\":\"request token error\",\"error_description\":\"" + description + "\"}"; System.out.println("[API] < " + response); client.sendMessage(response); } }); } } else if (action.equals(JsonConstants.API_USER_PROFILE)) { if (calendarNotifManager != null) { calendarNotifManager.getUserProfileManager() .getUserProfile(new IUserProfileListener() { @Override public void onSuccess(UserProfile userProfile) { if (userProfile != null) { JSONObject userProfileResponse = new JSONObject(); userProfileResponse.put(JsonConstants.GOOGLE_API_PROFILE_GENDER, userProfile.getGender()); userProfileResponse.put( JsonConstants.GOOGLE_API_PROFILE_DISPLAY_NAME, userProfile.getDisplayName()); userProfileResponse.put( JsonConstants.GOOGLE_API_PROFILE_FAMILY_NAME, userProfile.getFamilyName()); userProfileResponse.put( JsonConstants.GOOGLE_API_PROFILE_GIVEN_NAME, userProfile.getGivenName()); userProfileResponse.put( JsonConstants.GOOGLE_API_PROFILE_LANGUAGE, userProfile.getLanguage()); System.out.println( "[API] < " + userProfileResponse.toJSONString()); client.sendMessage(userProfileResponse.toJSONString()); } } @Override public void onError(String description) { String response = "{\"error\":\"request token error\",\"error_description\":\"" + description + "\"}"; System.out.println("[API] < " + response); client.sendMessage(response); } }); } } else if (action.equals(JsonConstants.API_CREATE_EVENT) && obj.containsKey(JsonConstants.API_DATE_BEGIN) && obj.containsKey(JsonConstants.API_DATE_END) && obj.containsKey(JsonConstants.API_SUMMARY)) { String dateBegin = obj.get(JsonConstants.API_DATE_BEGIN).toString(); String dateEnd = obj.get(JsonConstants.API_DATE_END).toString(); String summary = obj.get(JsonConstants.API_SUMMARY).toString(); if (calendarNotifManager != null) { calendarNotifManager.getCalendarManager().createEvent(dateBegin, dateEnd, summary, new ICreateEventListener() { @Override public void onError(String description) { String response = "{\"error\":\"request token error\",\"error_description\":\"" + description + "\"}"; System.out.println("[API] < " + response); client.sendMessage( "{\"error\":\"request token error\",\"error_description\":\"" + description + "\"}"); } @Override public void onCreateSuccess(String id) { String response = "{\"createEvent\":\"success\",\"eventId\":\"" + id + "\"}"; System.out.println("[API] < " + response); client.sendMessage(response); } }); } } else if (action.equals(JsonConstants.API_DELETE_EVENT) && obj.containsKey(JsonConstants.API_EVENT_ID)) { final String eventId = obj.get(JsonConstants.API_EVENT_ID).toString(); calendarNotifManager.getCalendarManager().deleteEvent(eventId, new IDeleteEventListener() { @Override public void onSuccess() { String response = "{\"deleteEvent\":\"success\",\"eventId\":\"" + eventId + "\"}"; System.out.println("[API] < " + response); client.sendMessage(response); } @Override public void onError(String description) { String response = "{\"error\":\"request token error\",\"error_description\":\"" + description + "\"}"; System.out.println("[API] < " + response); client.sendMessage(response); } }); } else if (action.equals(JsonConstants.API_GET_EVENTS) && obj.containsKey(JsonConstants.API_DATE_BEGIN) && obj.containsKey(JsonConstants.API_DATE_END) && obj.containsKey("searchText") && calendarNotifManager != null) { String dateBegin = obj.get(JsonConstants.API_DATE_BEGIN).toString(); String dateEnd = obj.get(JsonConstants.API_DATE_END).toString(); String searchText = obj.get(JsonConstants.API_SEARCH_TEXT).toString(); calendarNotifManager.getCalendarManager().getEventList(dateBegin, dateEnd, searchText, new IEventListListener() { @Override public void onEventListReceived(List<CalendarEvents> calendarEventList) { String response = "{\"eventList\":" + CalendarUtils .convertCalendarListToJsonArray(calendarEventList) .toJSONString() + "}"; System.out.println("[API] < " + response); client.sendMessage(response); } @Override public void onError(String description) { String response = "{\"error\":\"request token error\",\"error_description\":\"" + description + "\"}"; System.out.println("[API] < " + response); client.sendMessage(response); } }); } else if (action.equals(JsonConstants.API_SUBSCRIBE_EVENT) && obj.containsKey(JsonConstants.API_EVENT_ID) && obj.containsKey(JsonConstants.API_TIME_ABOUT_TO_START)) { String eventId = obj.get(JsonConstants.API_EVENT_ID).toString(); int timeAboutToStart = Integer .parseInt(obj.get(JsonConstants.API_TIME_ABOUT_TO_START).toString()); calendarNotifManager.getNotificationManager().subscribeEvent(eventId, timeAboutToStart, new IEventListener() { @Override public void onEventStart(String eventId, String summary) { String response = "{\"subscribedEvent\":\"" + eventId + "\",\"eventType\":\"started\",\"summary\":\"" + summary + "\"}"; System.out.println("[API] < " + response); client.sendMessage(response); } @Override public void onEventAboutToStart(String eventId, String summary) { String response = "{\"subscribedEvent\":\"" + eventId + "\",\"eventType\":\"aboutToStart\",\"summary\":\"" + summary + "\"}"; System.out.println("[API] < " + response); client.sendMessage(response); } }); } else if (action.equals(JsonConstants.API_UNSUBSCRIBE_EVENT) && obj.containsKey(JsonConstants.API_EVENT_ID)) { String eventId = obj.get(JsonConstants.API_EVENT_ID).toString(); calendarNotifManager.getNotificationManager().unsubscribeEvent(eventId); } else { System.out.println("[API] Error api target is inconsistent"); } } } } @Override public void onClientConnection(IWebsocketClient client) { System.out.println("Websocket client connected"); } @Override public void onClientClose(IWebsocketClient client) { System.out.println("Websocket client disconnected"); } }); Runnable websocketTask = new Runnable() { @Override public void run() { websocketServer.start(); } }; Thread thread = new Thread(websocketTask, "WEBSOCKET_THREAD"); thread.start(); server.addServerEventListener(new IHttpServerEventListener() { @Override public void onHttpFrameReceived(IHttpFrame httpFrame, HttpStates receptionStates, IHttpStream httpStream) { // check if http frame is OK if (receptionStates == HttpStates.HTTP_FRAME_OK) { // you can check here http frame type (response or request // frame) if (httpFrame.isHttpRequestFrame()) { // we want to send a message to client for http GET // request on page with uri /index if (httpFrame.getMethod().equals("GET") && httpFrame.getUri().equals("/gcalendar")) { String defaultPage = ""; try { defaultPage = FileUtils.readFile(webPath + "/index.html", "UTF-8"); } catch (IOException e) { e.printStackTrace(); } // return default html page for this HTTP Server httpStream.writeHttpFrame(new HttpResponseFrame(StatusCodeList.OK, new HttpVersion(1, 1), new HashMap<String, String>(), defaultPage.getBytes()) .toString().getBytes()); } else if (httpFrame.getMethod().equals("GET") && (httpFrame.getUri().endsWith(".css") || httpFrame.getUri().endsWith(".js"))) { String defaultPage = ""; try { defaultPage = FileUtils.readFile(webPath + httpFrame.getUri(), "UTF-8"); } catch (IOException e) { e.printStackTrace(); } // return default html page for this HTTP Server httpStream.writeHttpFrame(new HttpResponseFrame(StatusCodeList.OK, new HttpVersion(1, 1), new HashMap<String, String>(), defaultPage.getBytes()) .toString().getBytes()); } } } } }); server.start(); thread.interrupt(); }
From source file:de.ingrid.external.gemet.JSONUtils.java
public static String getId(JSONObject json) { return (String) json.get("uri"); }
From source file:de.ingrid.external.gemet.JSONUtils.java
public static String getType(JSONObject json) { return (String) json.get("thesaurus"); }
From source file:de.ingrid.external.gemet.JSONUtils.java
public static String getTarget(JSONObject json) { return (String) json.get("target"); }
From source file:me.timothy.ddd.entities.JSONCompatible.java
public static boolean getBoolean(JSONObject obj, String key) { return obj.get(key) == Boolean.TRUE; }