List of usage examples for org.json.simple JSONObject toJSONString
public String toJSONString()
From source file:fr.bmartel.protocol.google.main.LaunchOauthApiServer.java
/** * The main method./* w w w . ja va2 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:contractEditor.contractHOST2.java
public static void main(String[] args) { JSONObject obj = new JSONObject(); obj.put("name", "HOST2"); obj.put("context", "VM-deployment"); //obj.put("Context", new Integer); HashMap serviceDescription = new HashMap(); serviceDescription.put("location", "UK"); serviceDescription.put("certificate", "false"); serviceDescription.put("volume", "200_GB"); serviceDescription.put("price", "5_euro"); obj.put("serviceDescription", serviceDescription); HashMap gauranteeTerm = new HashMap(); gauranteeTerm.put("availability", "more_99_percentage"); obj.put("gauranteeTerm", gauranteeTerm); //Constraint1 HashMap host_rule1 = new HashMap(); HashMap VM_rule1 = new HashMap(); host_rule1.put("ID", "HOST2"); VM_rule1.put("data", "private"); ArrayList rule1 = new ArrayList(); rule1.add("prohibition"); rule1.add(host_rule1);/* w w w.j av a 2s. c o m*/ rule1.add(VM_rule1); ArrayList policyInConstraint1 = new ArrayList(); policyInConstraint1.add(rule1); ArrayList creationConstraint1 = new ArrayList(); creationConstraint1.add("other"); creationConstraint1.add("true"); creationConstraint1.add("true"); creationConstraint1.add(policyInConstraint1); ArrayList totalConstraint = new ArrayList(); totalConstraint.add(creationConstraint1); obj.put("creationConstraint", totalConstraint); try { FileWriter file = new FileWriter("confSP" + File.separator + "Host2.json"); file.write(obj.toJSONString()); file.flush(); file.close(); } catch (IOException e) { e.printStackTrace(); } System.out.print(obj); /* JSONParser parser = new JSONParser(); try { Object obj2 = parser.parse(new FileReader("confSP\\confHost1.json")); JSONObject jsonObject = (JSONObject) obj2; HashMap serviceDescription2=(HashMap) jsonObject.get("serviceDescription"); method.printHashMap(serviceDescription2); HashMap gauranteeTerm2=(HashMap) jsonObject.get("gauranteeTerm"); method.printHashMap(gauranteeTerm2); ArrayList creationConstraint=(ArrayList) jsonObject.get("creationConstraint"); method.printArrayList(creationConstraint); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (ParseException e) { e.printStackTrace(); } */ }
From source file:contractEditor.contractHOST1.java
public static void main(String[] args) { JSONObject obj = new JSONObject(); obj.put("name", "HOST1"); obj.put("context", "VM-deployment"); //obj.put("Context", new Integer); HashMap serviceDescription = new HashMap(); serviceDescription.put("location", "France"); serviceDescription.put("certificate", "true"); serviceDescription.put("volume", "100_GB"); serviceDescription.put("price", "6_euro"); obj.put("serviceDescription", serviceDescription); HashMap gauranteeTerm = new HashMap(); gauranteeTerm.put("availability", "more_98_percentage"); obj.put("gauranteeTerm", gauranteeTerm); //Constraint1 HashMap host_rule1 = new HashMap(); HashMap VM_rule1 = new HashMap(); host_rule1.put("ID", "HOST1"); VM_rule1.put("purpose", "test"); ArrayList rule1 = new ArrayList(); rule1.add("prohibition"); rule1.add(host_rule1);/*w ww . j a v a 2 s . co m*/ rule1.add(VM_rule1); ArrayList policyInConstraint1 = new ArrayList(); policyInConstraint1.add(rule1); ArrayList creationConstraint1 = new ArrayList(); creationConstraint1.add("other"); creationConstraint1.add("true"); creationConstraint1.add("true"); creationConstraint1.add(policyInConstraint1); ArrayList totalConstraint = new ArrayList(); totalConstraint.add(creationConstraint1); obj.put("creationConstraint", totalConstraint); try { FileWriter file = new FileWriter("confSP" + File.separator + "Host1.json"); file.write(obj.toJSONString()); file.flush(); file.close(); } catch (IOException e) { e.printStackTrace(); } System.out.print(obj); /* JSONParser parser = new JSONParser(); try { Object obj2 = parser.parse(new FileReader("confSP\\confHost1.json")); JSONObject jsonObject = (JSONObject) obj2; HashMap serviceDescription2=(HashMap) jsonObject.get("serviceDescription"); method.printHashMap(serviceDescription2); HashMap gauranteeTerm2=(HashMap) jsonObject.get("gauranteeTerm"); method.printHashMap(gauranteeTerm2); ArrayList creationConstraint=(ArrayList) jsonObject.get("creationConstraint"); method.printArrayList(creationConstraint); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (ParseException e) { e.printStackTrace(); } */ }
From source file:contractEditor.contractHOST3.java
public static void main(String[] args) { JSONObject obj = new JSONObject(); obj.put("name", "HOST3"); obj.put("context", "VM-deployment"); //obj.put("Context", new Integer); HashMap serviceDescription = new HashMap(); serviceDescription.put("location", "China"); serviceDescription.put("certificate", "false"); serviceDescription.put("volume", "70_GB"); serviceDescription.put("price", "4_euro"); obj.put("serviceDescription", serviceDescription); HashMap gauranteeTerm = new HashMap(); gauranteeTerm.put("availability", "more_97_percentage"); obj.put("gauranteeTerm", gauranteeTerm); //Constraint1 HashMap host_rule1 = new HashMap(); HashMap VM_rule1 = new HashMap(); host_rule1.put("ID", "HOST3"); VM_rule1.put("application", "internal"); ArrayList rule1 = new ArrayList(); rule1.add("prohibition"); rule1.add(host_rule1);// ww w . j av a 2 s . c o m rule1.add(VM_rule1); ArrayList policyInConstraint1 = new ArrayList(); policyInConstraint1.add(rule1); ArrayList creationConstraint1 = new ArrayList(); creationConstraint1.add("other"); creationConstraint1.add("true"); creationConstraint1.add("true"); creationConstraint1.add(policyInConstraint1); ArrayList totalConstraint = new ArrayList(); totalConstraint.add(creationConstraint1); obj.put("creationConstraint", totalConstraint); try { FileWriter file = new FileWriter("confSP" + File.separator + "Host3.json"); file.write(obj.toJSONString()); file.flush(); file.close(); } catch (IOException e) { e.printStackTrace(); } System.out.print(obj); /* JSONParser parser = new JSONParser(); try { Object obj2 = parser.parse(new FileReader("confSP\\confHost1.json")); JSONObject jsonObject = (JSONObject) obj2; HashMap serviceDescription2=(HashMap) jsonObject.get("serviceDescription"); method.printHashMap(serviceDescription2); HashMap gauranteeTerm2=(HashMap) jsonObject.get("gauranteeTerm"); method.printHashMap(gauranteeTerm2); ArrayList creationConstraint=(ArrayList) jsonObject.get("creationConstraint"); method.printArrayList(creationConstraint); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (ParseException e) { e.printStackTrace(); } */ }
From source file:com.entertailion.java.caster.Main.java
/** * @param args//from w ww .j a va2 s.co m */ public static void main(String[] args) { // http://commons.apache.org/proper/commons-cli/usage.html Option help = new Option("h", "help", false, "Print this help message"); Option version = new Option("V", "version", false, "Print version information"); Option list = new Option("l", "list", false, "List ChromeCast devices"); Option verbose = new Option("v", "verbose", false, "Verbose debug logging"); Option transcode = new Option("t", "transcode", false, "Transcode media; -f also required"); Option rest = new Option("r", "rest", false, "REST API server"); Option url = OptionBuilder.withLongOpt("stream").hasArg().withValueSeparator() .withDescription("HTTP URL for streaming content; -d also required").create("s"); Option server = OptionBuilder.withLongOpt("device").hasArg().withValueSeparator() .withDescription("ChromeCast device IP address").create("d"); Option id = OptionBuilder.withLongOpt("app-id").hasArg().withValueSeparator() .withDescription("App ID for whitelisted device").create("id"); Option mediaFile = OptionBuilder.withLongOpt("file").hasArg().withValueSeparator() .withDescription("Local media file; -d also required").create("f"); Option transcodingParameters = OptionBuilder.withLongOpt("transcode-parameters").hasArg() .withValueSeparator().withDescription("Transcode parameters; -t also required").create("tp"); Option restPort = OptionBuilder.withLongOpt("rest-port").hasArg().withValueSeparator() .withDescription("REST API port; default 8080").create("rp"); Options options = new Options(); options.addOption(help); options.addOption(version); options.addOption(list); options.addOption(verbose); options.addOption(url); options.addOption(server); options.addOption(id); options.addOption(mediaFile); options.addOption(transcode); options.addOption(transcodingParameters); options.addOption(rest); options.addOption(restPort); // create the command line parser CommandLineParser parser = new PosixParser(); //String[] arguments = new String[] { "-vr" }; try { // parse the command line arguments CommandLine line = parser.parse(options, args); Option[] lineOptions = line.getOptions(); if (lineOptions.length == 0) { System.out.println("caster: try 'java -jar caster.jar -h' for more information"); System.exit(0); } Log.setVerbose(line.hasOption("v")); // Custom app-id if (line.hasOption("id")) { Log.d(LOG_TAG, line.getOptionValue("id")); appId = line.getOptionValue("id"); } // Print version if (line.hasOption("V")) { System.out.println("Caster version " + VERSION); } // List ChromeCast devices if (line.hasOption("l")) { final DeviceFinder deviceFinder = new DeviceFinder(new DeviceFinderListener() { @Override public void discoveringDevices(DeviceFinder deviceFinder) { Log.d(LOG_TAG, "discoveringDevices"); } @Override public void discoveredDevices(DeviceFinder deviceFinder) { Log.d(LOG_TAG, "discoveredDevices"); TrackedDialServers trackedDialServers = deviceFinder.getTrackedDialServers(); for (DialServer dialServer : trackedDialServers) { System.out.println(dialServer.toString()); // keep system for output } } }); deviceFinder.discoverDevices(); } // Stream media from internet if (line.hasOption("s") && line.hasOption("d")) { Log.d(LOG_TAG, line.getOptionValue("d")); Log.d(LOG_TAG, line.getOptionValue("s")); try { Playback playback = new Playback(platform, appId, new DialServer(InetAddress.getByName(line.getOptionValue("d"))), new PlaybackListener() { private int time; private int duration; private int state; @Override public void updateTime(Playback playback, int time) { Log.d(LOG_TAG, "updateTime: " + time); this.time = time; } @Override public void updateDuration(Playback playback, int duration) { Log.d(LOG_TAG, "updateDuration: " + duration); this.duration = duration; } @Override public void updateState(Playback playback, int state) { Log.d(LOG_TAG, "updateState: " + state); // Stop the app if the video reaches the end if (time > 0 && time == duration && state == 0) { playback.doStop(); System.exit(0); } } public int getTime() { return time; } public int getDuration() { return duration; } public int getState() { return state; } }); playback.stream(line.getOptionValue("s")); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } // Play local media file if (line.hasOption("f") && line.hasOption("d")) { Log.d(LOG_TAG, line.getOptionValue("d")); Log.d(LOG_TAG, line.getOptionValue("f")); final String file = line.getOptionValue("f"); String device = line.getOptionValue("d"); try { Playback playback = new Playback(platform, appId, new DialServer(InetAddress.getByName(device)), new PlaybackListener() { private int time; private int duration; private int state; @Override public void updateTime(Playback playback, int time) { Log.d(LOG_TAG, "updateTime: " + time); this.time = time; } @Override public void updateDuration(Playback playback, int duration) { Log.d(LOG_TAG, "updateDuration: " + duration); this.duration = duration; } @Override public void updateState(Playback playback, int state) { Log.d(LOG_TAG, "updateState: " + state); // Stop the app if the video reaches the end if (time > 0 && time == duration && state == 0) { playback.doStop(); System.exit(0); } } public int getTime() { return time; } public int getDuration() { return duration; } public int getState() { return state; } }); if (line.hasOption("t") && line.hasOption("tp")) { playback.setTranscodingParameters(line.getOptionValue("tp")); } playback.play(file, line.hasOption("t")); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } // REST API server if (line.hasOption("r")) { final DeviceFinder deviceFinder = new DeviceFinder(new DeviceFinderListener() { @Override public void discoveringDevices(DeviceFinder deviceFinder) { Log.d(LOG_TAG, "discoveringDevices"); } @Override public void discoveredDevices(DeviceFinder deviceFinder) { Log.d(LOG_TAG, "discoveredDevices"); TrackedDialServers trackedDialServers = deviceFinder.getTrackedDialServers(); for (DialServer dialServer : trackedDialServers) { Log.d(LOG_TAG, dialServer.toString()); } } }); deviceFinder.discoverDevices(); int port = 0; if (line.hasOption("rp")) { try { port = Integer.parseInt(line.getOptionValue("rp")); } catch (NumberFormatException e) { Log.e(LOG_TAG, "invalid rest port", e); } } Playback.startWebserver(port, new WebListener() { String[] prefixes = { "/playback", "/devices" }; HashMap<String, Playback> playbackMap = new HashMap<String, Playback>(); HashMap<String, RestPlaybackListener> playbackListenerMap = new HashMap<String, RestPlaybackListener>(); final class RestPlaybackListener implements PlaybackListener { private String device; private int time; private int duration; private int state; public RestPlaybackListener(String device) { this.device = device; } @Override public void updateTime(Playback playback, int time) { Log.d(LOG_TAG, "updateTime: " + time); this.time = time; } @Override public void updateDuration(Playback playback, int duration) { Log.d(LOG_TAG, "updateDuration: " + duration); this.duration = duration; } @Override public void updateState(Playback playback, int state) { Log.d(LOG_TAG, "updateState: " + state); this.state = state; // Stop the app if the video reaches the end if (this.time > 0 && this.time == this.duration && state == 0) { playback.doStop(); playbackMap.remove(device); playbackListenerMap.remove(device); } } public int getTime() { return time; } public int getDuration() { return duration; } public int getState() { return state; } } @Override public Response handleRequest(String uri, String method, Properties header, Properties parms) { Log.d(LOG_TAG, "handleRequest: " + uri); if (method.equals("GET")) { if (uri.startsWith(prefixes[0])) { // playback String device = parms.getProperty("device"); if (device != null) { RestPlaybackListener playbackListener = playbackListenerMap.get(device); if (playbackListener != null) { // https://code.google.com/p/json-simple/wiki/EncodingExamples JSONObject obj = new JSONObject(); obj.put("time", playbackListener.getTime()); obj.put("duration", playbackListener.getDuration()); switch (playbackListener.getState()) { case 0: obj.put("state", "idle"); break; case 1: obj.put("state", "stopped"); break; case 2: obj.put("state", "playing"); break; default: obj.put("state", "idle"); break; } return new Response(HttpServer.HTTP_OK, "text/plain", obj.toJSONString()); } else { // Nothing is playing JSONObject obj = new JSONObject(); obj.put("time", 0); obj.put("duration", 0); obj.put("state", "stopped"); return new Response(HttpServer.HTTP_OK, "text/plain", obj.toJSONString()); } } } else if (uri.startsWith(prefixes[1])) { // devices // https://code.google.com/p/json-simple/wiki/EncodingExamples JSONArray list = new JSONArray(); TrackedDialServers trackedDialServers = deviceFinder.getTrackedDialServers(); for (DialServer dialServer : trackedDialServers) { JSONObject obj = new JSONObject(); obj.put("name", dialServer.getFriendlyName()); obj.put("ip_address", dialServer.getIpAddress().getHostAddress()); list.add(obj); } return new Response(HttpServer.HTTP_OK, "text/plain", list.toJSONString()); } } else if (method.equals("POST")) { if (uri.startsWith(prefixes[0])) { // playback String device = parms.getProperty("device"); if (device != null) { String stream = parms.getProperty("stream"); String file = parms.getProperty("file"); String state = parms.getProperty("state"); String transcode = parms.getProperty("transcode"); String transcodeParameters = parms.getProperty("transcode-parameters"); Log.d(LOG_TAG, "transcodeParameters=" + transcodeParameters); if (stream != null) { try { if (playbackMap.get(device) == null) { DialServer dialServer = deviceFinder.getTrackedDialServers() .findDialServer(InetAddress.getByName(device)); if (dialServer != null) { RestPlaybackListener playbackListener = new RestPlaybackListener( device); playbackMap.put(device, new Playback(platform, appId, dialServer, playbackListener)); playbackListenerMap.put(device, playbackListener); } } Playback playback = playbackMap.get(device); if (playback != null) { playback.stream(stream); return new Response(HttpServer.HTTP_OK, "text/plain", "Ok"); } } catch (Exception e1) { Log.e(LOG_TAG, "playback", e1); } } else if (file != null) { try { if (playbackMap.get(device) == null) { DialServer dialServer = deviceFinder.getTrackedDialServers() .findDialServer(InetAddress.getByName(device)); if (dialServer != null) { RestPlaybackListener playbackListener = new RestPlaybackListener( device); playbackMap.put(device, new Playback(platform, appId, dialServer, playbackListener)); playbackListenerMap.put(device, playbackListener); } } Playback playback = playbackMap.get(device); if (transcodeParameters != null) { playback.setTranscodingParameters(transcodeParameters); } if (playback != null) { playback.play(file, transcode != null); return new Response(HttpServer.HTTP_OK, "text/plain", "Ok"); } } catch (Exception e1) { Log.e(LOG_TAG, "playback", e1); } } else if (state != null) { try { if (playbackMap.get(device) == null) { DialServer dialServer = deviceFinder.getTrackedDialServers() .findDialServer(InetAddress.getByName(device)); if (dialServer != null) { RestPlaybackListener playbackListener = new RestPlaybackListener( device); playbackMap.put(device, new Playback(platform, appId, dialServer, playbackListener)); playbackListenerMap.put(device, playbackListener); } } Playback playback = playbackMap.get(device); if (playback != null) { // Handle case where current app wasn't started with caster playback.setDialServer(deviceFinder.getTrackedDialServers() .findDialServer(InetAddress.getByName(device))); // Change the playback state if (state.equals("play")) { playback.doPlay(); return new Response(HttpServer.HTTP_OK, "text/plain", "Ok"); } else if (state.equals("pause")) { playback.doPause(); return new Response(HttpServer.HTTP_OK, "text/plain", "Ok"); } else if (state.equals("stop")) { playback.doStop(); playbackMap.remove(device); playbackListenerMap.remove(device); return new Response(HttpServer.HTTP_OK, "text/plain", "Ok"); } else { Log.e(LOG_TAG, "playback invalid state: " + state); } } } catch (Exception e1) { Log.e(LOG_TAG, "playback", e1); } } } } } return new Response(HttpServer.HTTP_BADREQUEST, "text/plain", "Bad Request"); } @Override public String[] uriPrefixes() { return prefixes; } }); Log.d(LOG_TAG, "REST server ready"); // Run forever... while (true) { try { Thread.sleep(1000); } catch (InterruptedException e) { } } } // Print help if (line.hasOption("h")) { printHelp(options); } } catch (ParseException exp) { System.out.println("ERROR: " + exp.getMessage()); System.out.println(); printHelp(options); } }
From source file:agileinterop.AgileInterop.java
/** * @param args the command line arguments */// w w w .ja va 2s . co m public static void main(String[] args) { JSONObject obj; try { String username, password, agileUrl, operation, body; username = args[0]; password = args[1]; agileUrl = args[2]; operation = args[3]; body = args[4]; // Connect to Agile Agile.connect(username, password, agileUrl); switch (operation) { case "getPSRData": obj = getPSRData(body); break; case "getPSRList": obj = getPSRList(body); break; case "getPSRCellValues": obj = getPSRCellValues(body); break; case "getRelatedPSRs": obj = getRelatedPSRs(body); break; case "createRelatedPSRs": obj = createRelatedPSRs(body); break; case "writeNewDataToPSRs": obj = writeNewDataToPSRs(body); break; case "attachFileToPSR": obj = attachFileToPSR(body); break; case "crawlAgileByDateOriginated": obj = crawlAgileByDateOriginated(body); break; case "crawlAgileByPSRList": obj = crawlAgileByPSRList(body); break; default: throw new AssertionError(); } obj.put("status", "success"); } catch (APIException | ParseException | InterruptedException ex) { obj = new JSONObject(); obj.put("status", "error"); obj.put("data", ex.getMessage()); } catch (Exception ex) { obj = new JSONObject(); obj.put("status", "error"); obj.put("data", ex.getMessage()); } System.out.print(obj.toJSONString()); }
From source file:contractEditor.contractClients.java
public static void main(String[] args) { JSONObject obj = new JSONObject(); obj.put("name", "clientTemplate"); obj.put("context", "VM-deployment"); //obj.put("Context", new Integer); HashMap serviceRequirement = new HashMap(); HashMap serviceDescription = new HashMap(); serviceRequirement.put("VM1_volume", "18_GB"); serviceDescription.put("VM1_purpose", "dev"); serviceDescription.put("VM1_data", "private"); serviceDescription.put("VM1_application", "internal"); serviceRequirement.put("VM2_volume", "20_GB"); serviceDescription.put("VM2_purpose", "prod"); serviceDescription.put("VM2_data", "public"); serviceDescription.put("VM2_application", "business"); serviceRequirement.put("VM3_volume", "30_GB"); serviceDescription.put("VM3_purpose", "test"); serviceDescription.put("VM3_data", "public"); serviceDescription.put("VM3_application", "business"); serviceRequirement.put("VM4_volume", "20_GB"); serviceDescription.put("VM4_purpose", "prod"); serviceDescription.put("VM4_data", "public"); serviceDescription.put("VM4_application", "business"); obj.put("serviceRequirement", serviceRequirement); obj.put("serviceDescription", serviceDescription); HashMap gauranteeTerm = new HashMap(); gauranteeTerm.put("VM1_availability", "more_97_percentage"); gauranteeTerm.put("VM2_availability", "more_99_percentage"); gauranteeTerm.put("VM3_availability", "more_95_percentage"); gauranteeTerm.put("VM4_availability", "more_99_percentage"); obj.put("gauranteeTerm", gauranteeTerm); //Constraint1 HashMap host_rule1 = new HashMap(); HashMap VM_rule1 = new HashMap(); host_rule1.put("certificate", "true"); VM_rule1.put("purpose", "dev"); ArrayList rule1 = new ArrayList(); rule1.add("permission"); rule1.add(host_rule1);//from www . java 2s. c o m rule1.add(VM_rule1); HashMap host_rule1_2 = new HashMap(); HashMap VM_rule1_2 = new HashMap(); host_rule1_2.put("certificate", "true"); VM_rule1_2.put("purpose", "prod"); ArrayList rule1_2 = new ArrayList(); rule1_2.add("permission"); rule1_2.add(host_rule1_2); rule1_2.add(VM_rule1_2); HashMap host_rule1_3 = new HashMap(); HashMap VM_rule1_3 = new HashMap(); host_rule1_3.put("certificate", "true"); VM_rule1_3.put("purpose", "test"); ArrayList rule1_3 = new ArrayList(); rule1_3.add("permission"); rule1_3.add(host_rule1_3); rule1_3.add(VM_rule1_3); HashMap host_rule2 = new HashMap(); HashMap VM_rule2 = new HashMap(); host_rule2.put("location", "France"); VM_rule2.put("ID", "VM2"); ArrayList rule2 = new ArrayList(); rule2.add("permission"); rule2.add(host_rule2); rule2.add(VM_rule2); HashMap host_rule2_1 = new HashMap(); HashMap VM_rule2_1 = new HashMap(); host_rule2_1.put("location", "UK"); VM_rule2_1.put("ID", "VM2"); ArrayList rule2_1 = new ArrayList(); rule2_1.add("permission"); rule2_1.add(host_rule2_1); rule2_1.add(VM_rule2_1); HashMap host_rule3 = new HashMap(); HashMap VM_rule3 = new HashMap(); host_rule3.put("location", "France"); VM_rule3.put("application", "business"); ArrayList rule3 = new ArrayList(); rule3.add("permission"); rule3.add(host_rule3); rule3.add(VM_rule3); HashMap host_rule3_1 = new HashMap(); HashMap VM_rule3_1 = new HashMap(); host_rule3_1.put("location", "UK"); VM_rule3_1.put("application", "business"); ArrayList rule3_1 = new ArrayList(); rule3_1.add("permission"); rule3_1.add(host_rule3_1); rule3_1.add(VM_rule3_1); HashMap VMSeperation_rule_1_1 = new HashMap(); HashMap VMSeperation_rule_1_2 = new HashMap(); VMSeperation_rule_1_1.put("ID", "VM1"); VMSeperation_rule_1_2.put("ID", "VM3"); ArrayList rule4 = new ArrayList(); rule4.add("separation"); rule4.add(VMSeperation_rule_1_1); rule4.add(VMSeperation_rule_1_2); ArrayList policyInConstraint1 = new ArrayList(); policyInConstraint1.add(rule1); policyInConstraint1.add(rule1_2); policyInConstraint1.add(rule1_3); policyInConstraint1.add(rule2); policyInConstraint1.add(rule2_1); policyInConstraint1.add(rule3); policyInConstraint1.add(rule3_1); policyInConstraint1.add(rule4); ArrayList creationConstraint1 = new ArrayList(); creationConstraint1.add("RP4"); creationConstraint1.add("true"); creationConstraint1.add("true"); creationConstraint1.add(policyInConstraint1); ArrayList totalConstraint = new ArrayList(); totalConstraint.add(creationConstraint1); obj.put("creationConstraint", totalConstraint); try { FileWriter file = new FileWriter("confClient" + File.separator + "test3.json"); file.write(obj.toJSONString()); file.flush(); file.close(); } catch (IOException e) { e.printStackTrace(); } System.out.print(obj); /* JSONParser parser = new JSONParser(); try { Object obj2 = parser.parse(new FileReader("test2.json")); JSONObject jsonObject = (JSONObject) obj2; HashMap serviceDescription2=(HashMap) jsonObject.get("serviceDescription"); method.printHashMap(serviceDescription2); HashMap gauranteeTerm2=(HashMap) jsonObject.get("gauranteeTerm"); method.printHashMap(gauranteeTerm2); ArrayList creationConstraint=(ArrayList) jsonObject.get("creationConstraint"); method.printArrayList(creationConstraint); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (ParseException e) { e.printStackTrace(); } */ }
From source file:evaluation.evaluation1VMPolicyGeneration.java
public static void main(String[] args) { int VMNumber = 5; int attributeNumber = 20; JSONObject obj = new JSONObject(); obj.put("name", "clientTemplate"); obj.put("context", "VM-deployment"); //obj.put("Context", new Integer); HashMap serviceRequirement = new HashMap(); HashMap serviceDescription = new HashMap(); serviceRequirement.put("VM1_volume", "1_GB"); serviceDescription.put("VM1_purpose", "dev"); serviceDescription.put("VM1_data", "private"); serviceDescription.put("VM1_application", "internal"); for (int j = 5; j < attributeNumber; j++) { serviceDescription.put("VM1_other" + j, "other"); }//from w w w . j a v a 2 s .co m serviceRequirement.put("VM2_volume", "2_GB"); serviceDescription.put("VM2_purpose", "prod"); serviceDescription.put("VM2_data", "public"); serviceDescription.put("VM2_application", "business"); for (int j = 5; j < attributeNumber; j++) { serviceDescription.put("VM2_other" + j, "other"); } serviceRequirement.put("VM3_volume", "1_GB"); serviceDescription.put("VM3_purpose", "test"); serviceDescription.put("VM3_data", "public"); serviceDescription.put("VM3_application", "business"); for (int j = 5; j < attributeNumber; j++) { serviceDescription.put("VM3_other" + j, "other"); } serviceRequirement.put("VM4_volume", "12_GB"); serviceDescription.put("VM4_purpose", "prod"); serviceDescription.put("VM4_data", "public"); serviceDescription.put("VM4_application", "business"); for (int j = 5; j < attributeNumber; j++) { serviceDescription.put("VM4_other" + j, "other"); } for (int i = 5; i < VMNumber; i++) { serviceRequirement.put("VM" + i + "_volume", "20_GB"); serviceDescription.put("VM" + i + "_purpose", "prod"); serviceDescription.put("VM" + i + "_data", "public"); serviceDescription.put("VM" + i + "_application", "business"); for (int j = 5; j < attributeNumber; j++) { serviceDescription.put("VM" + i + "_other" + j, "other"); } } obj.put("serviceRequirement", serviceRequirement); obj.put("serviceDescription", serviceDescription); HashMap gauranteeTerm = new HashMap(); gauranteeTerm.put("VM1_availability", "more_97_percentage"); gauranteeTerm.put("VM2_availability", "more_99_percentage"); gauranteeTerm.put("VM3_availability", "more_95_percentage"); gauranteeTerm.put("VM4_availability", "more_99_percentage"); obj.put("gauranteeTerm", gauranteeTerm); //Constraint1 HashMap host_rule1 = new HashMap(); HashMap VM_rule1 = new HashMap(); host_rule1.put("certificate", "true"); VM_rule1.put("purpose", "dev"); ArrayList rule1 = new ArrayList(); rule1.add("permission"); rule1.add(host_rule1); rule1.add(VM_rule1); HashMap host_rule1_2 = new HashMap(); HashMap VM_rule1_2 = new HashMap(); host_rule1_2.put("certificate", "true"); VM_rule1_2.put("purpose", "prod"); ArrayList rule1_2 = new ArrayList(); rule1_2.add("permission"); rule1_2.add(host_rule1_2); rule1_2.add(VM_rule1_2); HashMap host_rule1_3 = new HashMap(); HashMap VM_rule1_3 = new HashMap(); host_rule1_3.put("certificate", "true"); VM_rule1_3.put("purpose", "test"); ArrayList rule1_3 = new ArrayList(); rule1_3.add("permission"); rule1_3.add(host_rule1_3); rule1_3.add(VM_rule1_3); HashMap host_rule2 = new HashMap(); HashMap VM_rule2 = new HashMap(); host_rule2.put("location", "France"); VM_rule2.put("ID", "VM2"); ArrayList rule2 = new ArrayList(); rule2.add("permission"); rule2.add(host_rule2); rule2.add(VM_rule2); HashMap host_rule2_1 = new HashMap(); HashMap VM_rule2_1 = new HashMap(); host_rule2_1.put("location", "UK"); VM_rule2_1.put("ID", "VM2"); ArrayList rule2_1 = new ArrayList(); rule2_1.add("permission"); rule2_1.add(host_rule2_1); rule2_1.add(VM_rule2_1); HashMap host_rule3 = new HashMap(); HashMap VM_rule3 = new HashMap(); host_rule3.put("location", "France"); VM_rule3.put("application", "business"); ArrayList rule3 = new ArrayList(); rule3.add("permission"); rule3.add(host_rule3); rule3.add(VM_rule3); HashMap host_rule3_1 = new HashMap(); HashMap VM_rule3_1 = new HashMap(); host_rule3_1.put("location", "UK"); VM_rule3_1.put("application", "business"); ArrayList rule3_1 = new ArrayList(); rule3_1.add("permission"); rule3_1.add(host_rule3_1); rule3_1.add(VM_rule3_1); HashMap VMSeperation_rule_1_1 = new HashMap(); HashMap VMSeperation_rule_1_2 = new HashMap(); VMSeperation_rule_1_1.put("ID", "VM1"); VMSeperation_rule_1_2.put("ID", "VM3"); ArrayList rule4 = new ArrayList(); rule4.add("separation"); rule4.add(VMSeperation_rule_1_1); rule4.add(VMSeperation_rule_1_2); ArrayList policyInConstraint1 = new ArrayList(); policyInConstraint1.add(rule1); policyInConstraint1.add(rule1_2); policyInConstraint1.add(rule1_3); policyInConstraint1.add(rule2); policyInConstraint1.add(rule2_1); policyInConstraint1.add(rule3); policyInConstraint1.add(rule3_1); policyInConstraint1.add(rule4); ArrayList creationConstraint1 = new ArrayList(); creationConstraint1.add("RP4"); creationConstraint1.add("true"); creationConstraint1.add("true"); creationConstraint1.add(policyInConstraint1); ArrayList totalConstraint = new ArrayList(); totalConstraint.add(creationConstraint1); obj.put("creationConstraint", totalConstraint); try { FileWriter file = new FileWriter("confClient" + File.separator + "test3.json"); file.write(obj.toJSONString()); file.flush(); file.close(); } catch (IOException e) { e.printStackTrace(); } System.out.print(obj); /* JSONParser parser = new JSONParser(); try { Object obj2 = parser.parse(new FileReader("test2.json")); JSONObject jsonObject = (JSONObject) obj2; HashMap serviceDescription2=(HashMap) jsonObject.get("serviceDescription"); method.printHashMap(serviceDescription2); HashMap gauranteeTerm2=(HashMap) jsonObject.get("gauranteeTerm"); method.printHashMap(gauranteeTerm2); ArrayList creationConstraint=(ArrayList) jsonObject.get("creationConstraint"); method.printArrayList(creationConstraint); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (ParseException e) { e.printStackTrace(); } */ }
From source file:msuresh.raftdistdb.JSONString.java
public static void ConvertJSON2File(JSONObject json, String floc) { try (FileWriter file = new FileWriter(floc)) { file.write(json.toJSONString()); } catch (Exception ex) { }/*from www . ja v a 2 s.c o m*/ }
From source file:de.tuttas.websockets.ChatServer.java
public static void send(JSONObject msg, Session myself) { Log.d("Sende " + msg.toJSONString()); msg.put("msg", StringUtil.escapeHtml((String) msg.get("msg"))); for (Session s : sessions) { if (s != myself) { try { s.getBasicRemote().sendText(msg.toJSONString()); } catch (IOException ex) { Logger.getLogger(ChatServer.class.getName()).log(Level.SEVERE, null, ex); ex.printStackTrace();//from ww w. jav a2 s.c o m } } } }