List of usage examples for org.json.simple JSONObject containsKey
boolean containsKey(Object key);
From source file:dependencies.DependencyResolving.java
/** * @param args the command line arguments *//* www . 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:fr.bmartel.protocol.google.main.LaunchOauthApiServer.java
/** * The main method.//from w w w . ja v a2 s . com * * @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:net.jakobnielsen.imagga.convert.ConverterTools.java
public static String getString(String key, Object o) { if (key == null || o == null) { return null; } else if (o instanceof JSONArray) { return null; // Maybe throw exception in the future. } else if (o instanceof JSONObject) { JSONObject jo = (JSONObject) o; if (jo.containsKey(key)) { return jo.get(key) == null ? null : jo.get(key).toString(); }//w w w .ja v a 2 s .co m } return null; }
From source file:de.keyle.mypet.npc.util.UpdateCheck.java
public static Optional<String> checkForUpdate() { try {/*from ww w .ja v a 2s. c o m*/ String parameter = ""; parameter += "build=" + MyPetNpcVersion.getBuild(); // no data will be saved on the server String content = Util.readUrlContent("http://update.mypet-plugin.de/MyPet-NPC?" + parameter); JSONParser parser = new JSONParser(); JSONObject result = (JSONObject) parser.parse(content); if (result.containsKey("latest")) { return Optional.of(result.get("latest").toString()); } } catch (Exception ignored) { } return Optional.absent(); }
From source file:mml.DocType.java
public static DocType classifyObj(JSONObject jObj) { String format = (String) jObj.get(JSONKeys.FORMAT); boolean hasBody = jObj.containsKey(JSONKeys.BODY); if (!jObj.containsKey(JSONKeys.DOCID)) return DocType.UNKNOWN; else {// www .j a v a 2 s . c o m if (format != null && (format.equals(Formats.TEXT) || format.equals(Formats.MVD_TEXT)) && hasBody) return DocType.CORTEX; if (hasBody && format != null && (format.equals(Formats.MVD_STIL) || format.equals(Formats.STIL))) return DocType.CORCODE; if (jObj.containsKey(JSONKeys.OFFSET) && jObj.containsKey(JSONKeys.LEN) && jObj.containsKey(JSONKeys.USER) && jObj.containsKey(JSONKeys.CONTENT)) return DocType.ANNOTATION; else return DocType.UNKNOWN; } }
From source file:com.memetix.gun4j.expand.UrlExpander.java
private static Map<String, String> parseResponse(final JSONObject json) { Map<String, String> expandedResults = new HashMap<String, String>(); final JSONObject data = (JSONObject) json.get("data"); if (data.containsKey("expand")) { final JSONArray expand = (JSONArray) data.get("expand"); for (Object result : expand) { final JSONObject expandedResult = (JSONObject) result; expandedResults.put((String) expandedResult.get("shortUrl"), (String) expandedResult.get("fullUrl")); }/*w w w .java2s . c o m*/ } return expandedResults; }
From source file:net.amigocraft.mpt.command.InfoCommand.java
@SuppressWarnings("unchecked") public static String[] getPackageInfo(String id) throws MPTException { id = id.toLowerCase();/*from w w w . j a v a 2 s .co m*/ if (Main.packageStore.containsKey("packages")) { JSONObject packs = (JSONObject) Main.packageStore.get("packages"); Object pack = packs.get(id); if (pack != null) { JSONObject jPack = (JSONObject) pack; if (jPack.containsKey("name") && jPack.containsKey("description") && jPack.containsKey("version") && jPack.containsKey("url") && jPack.containsKey("repo")) { return new String[] { jPack.get("name").toString(), jPack.get("description").toString(), jPack.get("version").toString(), jPack.get("url").toString(), jPack.get("repo").toString(), jPack.containsKey("sha1") ? jPack.get("sha1").toString() : null, jPack.containsKey("installed") ? jPack.get("installed").toString() : null, }; } else throw new MPTException(ERROR_COLOR + "Package definition for " + ID_COLOR + id + ERROR_COLOR + " is malformed! Running " + COMMAND_COLOR + "/mpt update" + ERROR_COLOR + " may correct" + "this."); } else throw new MPTException(ERROR_COLOR + "Cannot find package " + ID_COLOR + id + ERROR_COLOR + "!"); } else throw new MPTException("Package store is malformed!"); }
From source file:biomine.bmvis2.pipeline.GraphOperationSerializer.java
private static boolean isOperation(JSONObject o) { return o.containsKey("class"); }
From source file:net.amigocraft.mpt.command.RemoveRepositoryCommand.java
public static void removeRepository(String id) throws MPTException { id = id.toLowerCase();/* w w w .j a v a 2 s . c om*/ JSONObject repos = (JSONObject) Main.repoStore.get("repositories"); if (repos.containsKey(id)) { lockStores(); repos.remove(id); // remove it from memory File store = new File(Main.plugin.getDataFolder(), "repositories.json"); // get the store file if (!store.exists()) // avoid dumb errors Main.initializeRepoStore(store); try { writeRepositoryStore(); } catch (IOException ex) { ex.printStackTrace(); unlockStores(); throw new MPTException(ERROR_COLOR + "Failed to remove repository from local store!"); } unlockStores(); } else // repo doesn't exist in local store throw new MPTException(ERROR_COLOR + "Cannot find repo with given ID!"); }
From source file:br.net.fabiozumbi12.RedProtect.hooks.MojangUUIDs.java
public static String getName(String UUID) { try {/*from ww w . j av a2s . c o m*/ URL url = new URL("https://api.mojang.com/user/profiles/" + UUID.replaceAll("-", "") + "/names"); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String line = in.readLine(); if (line == null) { return null; } JSONArray array = (JSONArray) new JSONParser().parse(line); HashMap<Long, String> names = new HashMap<Long, String>(); String name = ""; for (Object profile : array) { JSONObject jsonProfile = (JSONObject) profile; if (jsonProfile.containsKey("changedToAt")) { names.put((long) jsonProfile.get("changedToAt"), (String) jsonProfile.get("name")); continue; } name = (String) jsonProfile.get("name"); } if (!names.isEmpty()) { Long key = Collections.max(names.keySet()); return names.get(key); } else { return name; } } catch (Exception ex) { ex.printStackTrace(); } return null; }