List of usage examples for org.json.simple JSONObject containsKey
boolean containsKey(Object key);
From source file:uk.ac.jorum.integration.matchers.MatchJSONSubObject.java
private boolean runMatch(JSONObject item) { isKeyPresent = item.containsKey(key); if (!isKeyPresent) { return false; }//w ww. j a va 2 s . c o m return matcher.matches((T) item.get(key)); }
From source file:uk.ac.susx.tag.method51.core.params.codec.generic.ParamsCodec.java
@Override public Params decode(JSONObject value) throws DecodeException { Params instance = Params.instance(paramsClass); JSONObject globals = (JSONObject) value.get(ParamsRegistry.GLOBALS_KEY); if (globals != null) { for (String key : (Set<String>) globals.keySet()) { Class globalClass = new ClassCodec().decodeString(key); ParamsCodec codec = new ParamsCodec(globalClass); Params global = codec.decode((JSONObject) globals.get(key)); instance.setGlobal(global);/*from w w w . j av a 2s . com*/ } } for (String fieldName : instance.getFieldNames()) { Params.Param param = instance.getParamByName(fieldName); if (value.containsKey(fieldName)) { try { IType type = param.getType(); Object result = type.decode(value.get(fieldName)); type.validate(result); param.set(result); } catch (InvalidParameterException e) { LOG.error("", e); throw new InvalidParameterException( "Bad value for field '" + fieldName + "':\n" + e.getMessage()); } catch (ClassCastException e) { try { IType type = param.getType(); Object result = type.decode(Long.toString((Long) value.get(fieldName))); type.validate(result); param.set(result); } catch (NumberFormatException | ClassCastException e1) { LOG.error("", e); throw new InvalidParameterException( "Bad type for field '" + fieldName + "':\n" + e.getMessage()); } } catch (Exception e) { LOG.error("", e); throw new InvalidParameterException( "Unknown error parsing field '" + fieldName + "' with value: " + value.get(fieldName)); } } } instance.validate(); return instance; }
From source file:uk.co.didz.hypersignsbukkit.HyperSignsBukkit.java
/** * Attempt to load signs. If the data file doesn't exist, create it. *///from www . j av a2 s . c o m protected void loadSignsData() { log.info("Loading signs:"); loadedSigns = new HashMap<Location, URL>(); if (!getDataFolder().exists()) { getDataFolder().mkdirs(); } File signsFile = new File(getDataFolder(), "signs.json"); try { if (signsFile.createNewFile() == true) { log.info("Created data file signs.json successfully."); return; } } catch (IOException e) { log.severe("Unable to create signs.json. Disabling plugin."); e.printStackTrace(); pm.disablePlugin(this); return; } if (signsFile.length() == 0) { log.info("No signs loaded. (signs.json is empty)"); return; } FileReader fileReader; try { fileReader = new FileReader(signsFile); } catch (FileNotFoundException e) { // Shouldn't happen cause the file was created up there ^ return; } JSONParser parser = new JSONParser(); Object array; try { array = parser.parse(fileReader); } catch (ParseException pe) { log.severe("Unable to parse signs.json! Disabling plugin."); log.severe(pe.toString()); pm.disablePlugin(this); return; } catch (IOException e) { log.severe("IOException while trying to parse signs.json! Disabling plugin."); e.printStackTrace(); pm.disablePlugin(this); return; } // Ensure that the root element is an array JSONArray arr; try { arr = (JSONArray) array; } catch (ClassCastException e) { log.severe("Error while loading signs.json, the root element isn't an array! Disabling plugin."); e.printStackTrace(); pm.disablePlugin(this); return; } int blockNum = 0; // For error messages for (Object object : arr) { JSONObject obj; try { obj = (JSONObject) object; } catch (ClassCastException e) { log.warning("Found a non-object in the blocks list while loading signs.json. Skipping."); continue; } blockNum++; if (!obj.containsKey("world") || !obj.containsKey("x") || !obj.containsKey("y") || !obj.containsKey("z") || !obj.containsKey("url")) { log.warning("Missing data for block #" + blockNum + " while loading signs.json. Skipping."); continue; } String worldName, urlString; int x, y, z; try { worldName = (String) obj.get("world"); x = ((Number) obj.get("x")).intValue(); y = ((Number) obj.get("y")).intValue(); z = ((Number) obj.get("z")).intValue(); urlString = (String) obj.get("url"); } catch (ClassCastException e) { log.warning("Found malformed data for a block while loading signs.json. Skipping."); continue; } assert (worldName != null && urlString != null); // Ensure world for this block exists World world = getServer().getWorld(worldName); if (world == null) { log.warning("The world '" + worldName + "' for block #" + blockNum + " doesn't exist on the server. Skipping."); continue; } Location location = new Location(world, x, y, z); // Make sure the URL is valid URL url = validateURL(urlString); if (url == null) { log.warning("The URL for block #" + blockNum + "is invalid. Skipping."); continue; } loadedSigns.put(location.clone(), url); } log.info(loadedSigns.size() + " signs loaded."); }
From source file:uk.codingbadgers.SurvivalPlus.backup.PlayerBackup.java
/** * Convert a json array into an itemstack array * * @param array The json array to convert * @return An itemstack array of the given json array *//*from www.j a va2 s. c o m*/ @SuppressWarnings("deprecation") private ItemStack[] JSONArrayToItemStackArray(JSONArray array) { List<ItemStack> items = new ArrayList<ItemStack>(array.size()); for (Object itemObject : array) { if (!(itemObject instanceof JSONObject)) { continue; } JSONObject jsonItem = (JSONObject) itemObject; // Parse item ItemStack item = new ItemStack(Material.valueOf((String) jsonItem.get("type"))); item.setAmount(Integer.valueOf((String) jsonItem.get("amount"))); item.setDurability(Short.valueOf((String) jsonItem.get("durability"))); item.getData().setData(Byte.valueOf((String) jsonItem.get("data"))); // Parse enchantments JSONArray enchantments = (JSONArray) jsonItem.get("enchantment"); for (Object enchantmentObject : enchantments) { if (!(enchantmentObject instanceof JSONObject)) { continue; } JSONObject jsonEnchantment = (JSONObject) enchantmentObject; Enchantment enchantment = Enchantment.getByName((String) jsonEnchantment.get("id")); int enchantmentLevel = Integer.valueOf((String) jsonEnchantment.get("level")); item.addUnsafeEnchantment(enchantment, enchantmentLevel); } // Parse metadata if (jsonItem.containsKey("metadata")) { JSONObject metaData = (JSONObject) jsonItem.get("metadata"); ItemMeta itemMeta = item.getItemMeta(); if (metaData.containsKey("displayname")) { itemMeta.setDisplayName((String) metaData.get("displayname")); } if (metaData.containsKey("lores")) { List<String> lores = new ArrayList<String>(); JSONArray jsonLores = (JSONArray) metaData.get("lores"); for (Object loreObject : jsonLores) { String lore = (String) loreObject; lores.add(lore); } itemMeta.setLore(lores); } item.setItemMeta(itemMeta); } items.add(item); } int itemIndex = 0; ItemStack[] itemArray = new ItemStack[items.size()]; for (ItemStack item : items) { itemArray[itemIndex] = item; itemIndex++; } return itemArray; }
From source file:utils.APIExporter.java
/** *write API documents in to the zip file * @param uuid APIId// ww w . j a va2s . c om * @param documentaionSummary resultant string from the getAPIDocuments *@param accessToken token with scope apim:api_view */ private static void exportAPIDocumentation(String uuid, String documentaionSummary, String accessToken, String archivePath) { System.out.println(" access token " + accessToken); OutputStream outputStream = null; ApiImportExportConfiguration config = ApiImportExportConfiguration.getInstance(); //create directory to hold API documents String documentFolderPath = archivePath.concat(File.separator + "docs"); ImportExportUtils.createDirectory(documentFolderPath); try { //writing API documents to the zip folder Object json = mapper.readValue(documentaionSummary, Object.class); String formattedJson = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(json); writeFile(documentFolderPath + File.separator + "docs.json", formattedJson); //convert documentation summary to json object JSONObject jsonObj = (JSONObject) parser.parse(documentaionSummary); if (jsonObj.containsKey("list")) { org.json.simple.JSONArray arr = (org.json.simple.JSONArray) jsonObj .get(ImportExportConstants.DOC_LIST); // traverse through each document for (Object anArr : arr) { JSONObject document = (JSONObject) anArr; //getting document source type (inline/url/file) String sourceType = (String) document.get(ImportExportConstants.SOURCE_TYPE); if (ImportExportConstants.FILE_DOC_TYPE.equalsIgnoreCase(sourceType) || ImportExportConstants.INLINE_DOC_TYPE.equalsIgnoreCase(sourceType)) { //getting documentId String documentId = (String) document.get(ImportExportConstants.DOC_ID); //REST API call to get document contents String url = config.getPublisherUrl() + "apis/" + uuid + "/documents/" + documentId + "/content"; CloseableHttpClient client = HttpClientGenerator .getHttpClient(config.getCheckSSLCertificate()); HttpGet request = new HttpGet(url); request.setHeader(HttpHeaders.AUTHORIZATION, ImportExportConstants.CONSUMER_KEY_SEGMENT + " " + accessToken); HttpResponse response = client.execute(request); HttpEntity entity = response.getEntity(); if (ImportExportConstants.FILE_DOC_TYPE.equalsIgnoreCase(sourceType)) { //creating directory to hold FILE type content String filetypeFolderPath = documentFolderPath .concat(File.separator + ImportExportConstants.FILE_DOCUMENT_DIRECTORY); ImportExportUtils.createDirectory(filetypeFolderPath); //writing file type content in to the zip folder String localFilePath = filetypeFolderPath + File.separator + document.get(ImportExportConstants.DOC_NAME); try { outputStream = new FileOutputStream(localFilePath); entity.writeTo(outputStream); } finally { try { assert outputStream != null; outputStream.close(); } catch (IOException e) { log.warn("Error occurred while closing the streams"); } } } else { //create directory to hold inline contents String inlineFolderPath = documentFolderPath .concat(File.separator + ImportExportConstants.INLINE_DOCUMENT_DIRECTORY); ImportExportUtils.createDirectory(inlineFolderPath); //writing inline content in to the zip folder InputStream inlineStream = null; try { String localFilePath = inlineFolderPath + File.separator + document.get(ImportExportConstants.DOC_NAME); outputStream = new FileOutputStream(localFilePath); entity.writeTo(outputStream); } finally { try { if (inlineStream != null) { inlineStream.close(); } if (outputStream != null) { outputStream.close(); } } catch (IOException e) { log.warn("Error occure while closing the streams"); } } } } } } } catch (ParseException e) { log.error("Error occurred while getting API documents"); } catch (IOException e) { log.error("Error occured while writing getting API documents"); } }
From source file:utils.APIExporter.java
/** * set the value been sent to the corresponding key * @param responseString response to the export rest call * @param key key//from w w w . jav a 2 s .co m * @param value value to be set */ private static void setJsonValues(String responseString, String key, String value) { try { JSONObject json = (JSONObject) parser.parse(responseString); if (json.containsKey(key)) { json.put(key, value); } } catch (ParseException e) { String errorMsg = "error occurred while setting API status"; log.error(errorMsg); } }
From source file:utils.ImportExportUtils.java
/** * retrieve the corresponding value of the requesting key from the response json string * * @param responseString json string retrived from rest call * @param key key of the element of required value * @return value correspond to the key//from w ww . j ava 2 s . c o m */ static String readJsonValues(String responseString, String key) { String value = null; JSONParser parser = new JSONParser(); try { JSONObject json = (JSONObject) parser.parse(responseString); if (json.containsKey(key)) { value = (String) json.get(key); } } catch (ParseException e) { String errorMsg = "Error occurred while parsing the json string to Json object"; log.error(errorMsg); } return value; }
From source file:youtube.YoutubeApiClient.java
public void getVideoClipIDs(String youtubeChannelName, List<YoutubeMetaData> resultContainer, List<YoutubeMetaData> lockedContainer) { String youtubeChannelId = getYoutubeChannelId(youtubeChannelName); GenericUrl url = new GenericUrl("https://www.googleapis.com/youtube/v3/playlistItems"); url.put("part", "snippet"); url.put("playlistId", youtubeChannelId); url.put("key", properties.get("API_KEY")); url.put("maxResults", "50"); JSONObject response = makeHttpRequest(url); System.out.println("response: " + response); JSONArray responseItems = (JSONArray) response.get("items"); for (int i = 0; i < responseItems.size(); ++i) { JSONObject responseItemsEntry = (JSONObject) responseItems.get(i); JSONObject responseItemsEntrySnippet = (JSONObject) responseItemsEntry.get("snippet"); JSONObject responseItemsEntrySnippetResourceid = (JSONObject) responseItemsEntrySnippet .get("resourceId"); String videoID = responseItemsEntrySnippetResourceid.get("videoId").toString(); boolean checkLockedInfo = getLockedInfo(videoID); YoutubeMetaData temp = new YoutubeMetaData(); if (checkLockedInfo) { temp.setYoutubeID(videoID);// ww w. j a va2 s .c om JSONObject detailedResults = genericYoutubeCall("snippet, contentDetails, statistics, status", videoID); processingDetailedResults(detailedResults, temp); resultContainer.add(temp); } else { temp.setYoutubeID(videoID); JSONObject detailedResults = genericYoutubeCall("snippet, contentDetails, statistics, status", videoID); processingDetailedResults(detailedResults, temp); lockedContainer.add(temp); } } if (response.containsKey("nextPageToken")) { String nextPageToken = response.get("nextPageToken").toString(); getNextPage(youtubeChannelId, nextPageToken, resultContainer, lockedContainer); } System.out.println("List of available Videos(" + resultContainer.size() + ")"); System.out.println("List of locked Videos (" + lockedContainer.size() + ")"); for (int i = 0; i < lockedContainer.size(); i++) { System.out.print(lockedContainer.get(i).getYoutubeID() + " "); } }
From source file:youtube.YoutubeApiClient.java
/** * //from www . ja v a 2s. c om * @param videoID * needs a Youtube videoID * @return true if the video is viewable in Germany, false if it is blocked * or if the service is currently unavailable * @throws IOException * @throws ParseException * * This method checks if a youtube video is available to view in * germany or regionLocked by GEMA */ // TODO: refactor program to remove this method, can be done with a single // request to youtube. Requires a lot of refactoring in the // processingSearchResults() private boolean getLockedInfo(String videoID) { // https://www.googleapis.com/youtube/v3/videos?part=contentDetails&id=91EAEKF2plE&key={YOUR_API_KEY} GenericUrl url = new GenericUrl("https://www.googleapis.com/youtube/v3/videos"); url.put("part", "contentDetails, status"); url.put("id", videoID); url.put("key", properties.get("API_KEY")); JSONObject response = makeHttpRequest(url); if (response == null) { return false; } JSONArray responseItems = (JSONArray) response.get("items"); JSONObject responseItemsEntry = (JSONObject) responseItems.get(0); JSONObject responseItemsEntryContentdetails = (JSONObject) responseItemsEntry.get("contentDetails"); JSONObject responseItemsEntryStatus = (JSONObject) responseItemsEntry.get("status"); Boolean responseItemsEntryStatusEmbeddable = (Boolean) responseItemsEntryStatus.get("embeddable"); if (responseItemsEntryContentdetails.containsKey("regionRestriction") || responseItemsEntryStatus.get("uploadStatus").toString() == "deleted" || responseItemsEntryStatus.get("uploadStatus").toString() == "failed" || responseItemsEntryStatus.get("uploadStatus").toString() == "rejected" || responseItemsEntryStatus.get("privacyStatus").toString() == "private" || !responseItemsEntryStatusEmbeddable) { return false; } else { return true; } }
From source file:youtube.YoutubeApiClient.java
/** * //from ww w.j a v a2 s . c o m * @param youtubeChannelId * requires a youtube channel id * @param nextPageToken * youtube marker that is used to navigate between search pages * @param resultContainer * List containing all videos from a channel * @param lockedList * containing all GEMA blocked videos from a channel * @throws IOException * @throws ParseException * * this is a submethod to the getVideoClipIDs(String * youtubeChannelId){} method to retrieve more than 50 video * results */ private void getNextPage(String youtubeChannelId, String nextPageToken, List<YoutubeMetaData> resultContainer, List<YoutubeMetaData> lockedContainer) { GenericUrl url = new GenericUrl("https://www.googleapis.com/youtube/v3/playlistItems"); url.put("part", "snippet"); url.put("playlistId", youtubeChannelId); url.put("key", properties.get("API_KEY")); url.put("maxResults", "50"); url.put("pageToken", nextPageToken); JSONObject response = makeHttpRequest(url); JSONArray responseItems = (JSONArray) response.get("items"); for (int i = 0; i < responseItems.size(); ++i) { JSONObject responseItemsEntry = (JSONObject) responseItems.get(i); JSONObject responseItemsEntrySnippet = (JSONObject) responseItemsEntry.get("snippet"); JSONObject responseItemsEntrySnippetResourceid = (JSONObject) responseItemsEntrySnippet .get("resourceId"); String videoID = responseItemsEntrySnippetResourceid.get("videoId").toString(); boolean checkRegionLock = getLockedInfo(videoID); YoutubeMetaData temp = new YoutubeMetaData(); if (checkRegionLock) { temp.setYoutubeID(videoID); resultContainer.add(temp); } else { temp.setYoutubeID(videoID); lockedContainer.add(temp); } } if (response.containsKey("nextPageToken")) { String newNextPageToken = response.get("nextPageToken").toString(); getNextPage(youtubeChannelId, newNextPageToken, resultContainer, lockedContainer); } }