List of usage examples for org.json.simple JSONArray remove
public E remove(int index)
From source file:com.gti.redirects.Redirects.RedirectStorage.java
@Override public boolean delete(int index) { try {// ww w.j av a 2 s. co m JSONArray jsonArray = parseFile(); jsonArray.remove(index); writeJsonArray(jsonArray); } catch (IOException e) { e.printStackTrace(); } catch (ParseException e) { e.printStackTrace(); } return false; }
From source file:cc.pinel.mangue.storage.MangaStorage.java
public void removeManga(Manga manga) throws IOException { JSONObject json = null;// w w w .j av a 2 s . c om try { json = readJSON(); } catch (Exception e) { // ignored } if (json == null) json = new JSONObject(); JSONArray jsonMangas = (JSONArray) json.get("mangas"); if (jsonMangas != null) { JSONObject jsonManga = findManga(jsonMangas, manga.getId()); if (jsonManga != null) { jsonMangas.remove(jsonManga); writeJSON(json); } } }
From source file:com.hortonworks.amstore.view.TaskManagerService.java
/** * Handles: DELETE /taskmanager/postinstalltasks Removes a task from the * list of tasks This is done because of BUG: a call to * viewContext.putInstanceData inside the servlet returns ERROR 500 after a * while./*w ww . j a va2 s . c om*/ * * @param headers * http headers * @param ui * uri info * * @return the response */ @DELETE @Path("/postinstalltasks/{uri}") @Produces({ "text/html" }) public Response delPostInstallTasks(@PathParam("uri") String uri, @Context HttpHeaders headers, @Context UriInfo ui) throws IOException { String response = ""; try { String current = viewContext.getInstanceData("post-install-tasks"); if (current == null) current = "[]"; JSONArray array = (JSONArray) JSONValue.parse(current); array.remove(URLDecoder.decode(uri)); viewContext.putInstanceData("post-install-tasks", array.toString()); /* * } catch( ParseException pe){ System.out.println("position: " + * pe.getPosition()); System.out.println(pe); } */ } catch (Exception e) { response += "Failed to remove: current=" + uri + "<br>"; response += "Error in service: " + e.toString(); return Response.ok(response).type("text/html").build(); } String entity = "{ \"status\": \"ok\" }"; return Response.ok(entity).type("text/html").build(); }
From source file:com.hortonworks.amstore.view.TaskManagerService.java
/** * Handles: DELETE /taskmanager/postupdatetasks Removes a task from the * list of tasks This is done because of BUG: a call to * viewContext.putInstanceData inside the servlet returns ERROR 500 after a * while./*from ww w. ja v a 2s . c o m*/ * * @param headers * http headers * @param ui * uri info * * @return the response */ @DELETE @Path("/postupdatetasks/{uri}") @Produces({ "text/html" }) public Response delPostUpdateTasks(@PathParam("uri") String uri, @Context HttpHeaders headers, @Context UriInfo ui) throws IOException { String response = ""; try { String current = viewContext.getInstanceData("post-update-tasks"); if (current == null) current = "[]"; JSONArray array = (JSONArray) JSONValue.parse(current); array.remove(URLDecoder.decode(uri)); viewContext.putInstanceData("post-update-tasks", array.toString()); /* * } catch( ParseException pe){ System.out.println("position: " + * pe.getPosition()); System.out.println(pe); } */ } catch (Exception e) { response += "Failed to remove: current=" + uri + "<br>"; response += "Error in service: " + e.toString(); return Response.ok(response).type("text/html").build(); } String entity = "{ \"status\": \"ok\" }"; return Response.ok(entity).type("text/html").build(); }
From source file:com.des.paperbase.ManageData.java
public void delete(String Tablename, Map<String, Object> value, String FilterType) throws ParseException, IOException { String data = g.readFileToString(PATH_FILE + "\\" + Tablename + ".json"); List<Integer> ListDelete = new LinkedList<Integer>(); if (!data.equalsIgnoreCase("{\"data\":[]}")) { JSONObject json = (JSONObject) new JSONParser().parse(data); JSONArray OldValue = (JSONArray) json.get("data"); for (int s = 0; s < OldValue.size(); s++) { JSONObject record = (JSONObject) OldValue.get(s); if (MappingRecordAndKey(value, record, FilterType)) { ListDelete.add(s);/*from w ww . ja v a 2s. c o m*/ } } for (int i = ListDelete.size() - 1; i >= 0; i--) { System.out.print(ListDelete.get(i) + " "); OldValue.remove(ListDelete.get(i).intValue()); } JSONObject table = new JSONObject(); table.put("data", OldValue); g.writefile(table.toJSONString(), PATH_FILE + "\\" + Tablename + ".json"); } }
From source file:at.ac.tuwien.dsg.quelle.sesConfigurationsRecommendationService.control.RequirementsManagementController.java
private void processRemoveRequirementsJSONCommand(String json) { //use META DATA FIELDs for rest of details for adding/removing shit //TODO: To actually get the names from somwehere and conditions and etc. I need to do a bit more management //JSON looks like { "command" : "add", "type": "' + type+ '" "trace" : [{"name" : "ServiceReqs_overall_elasticity_multi", "type" : "SERVICE"}]}; Object command = JSONValue.parse(json); JSONObject jSONcommandObject = (JSONObject) command; String whatToRemove = jSONcommandObject.get("type").toString(); JSONArray trace = (JSONArray) jSONcommandObject.get("trace"); JSONObject jSONRootObject = (JSONObject) trace.remove(0); String namejSONRootObject = jSONRootObject.get("name").toString(); String typejSONRootObject = jSONRootObject.get("type").toString(); //in order we traverse from root if (!requirements.getName().equals(namejSONRootObject) || !requirements.getLevel().toString().equals(typejSONRootObject)) { throw new RuntimeException("Something bad, as The requirements root does not match"); }//ww w . j av a 2 s . c om //we go one by one with JSON and get corect requirements children //first we get through the multi level requirements MultiLevelRequirements previousReqs = null; MultiLevelRequirements currentReqs = requirements; while (!currentReqs.getContainedElements().isEmpty() && !trace.isEmpty()) { { Object obj = trace.get(0); JSONObject jSONObject = (JSONObject) obj; String name = jSONObject.get("name").toString(); String type = jSONObject.get("type").toString(); boolean somethingMatched = false; for (MultiLevelRequirements r : currentReqs.getContainedElements()) { if (r.getName().equals(name) && r.getLevel().toString().equals(type)) { previousReqs = currentReqs; currentReqs = r; //if we matched, remove it from trace, else leave it for future matching trace.remove(0); somethingMatched = true; break; } } //need to break, as I might add strategies/requirements to any level (i.e. service) // so no need to traverse everything if (!somethingMatched) { break; } } } //here we are at a point in which we need to start looking in individual requirements blocks, then individual requirements, then conditions //only if we add Requirements or Conditions. Otherwise all work on multi level reqs switch (whatToRemove) { case "Strategy": { Object obj = trace.remove(0); JSONObject jSONObject = (JSONObject) obj; String name = jSONObject.get("name").toString(); String type = jSONObject.get("type").toString(); Strategy s = new Strategy().withCategoryString(name); for (Strategy strategy : currentReqs.getOptimizationStrategies()) { if (strategy.getStrategyCategory().equals(s.getStrategyCategory())) { currentReqs.removeStrategy(s); break; } } } break; case "Topology": { if (previousReqs.getContainedElements().contains(currentReqs)) { previousReqs.removeMultiLevelRequirements(currentReqs); } } break; case "Unit": { if (previousReqs.getContainedElements().contains(currentReqs)) { previousReqs.removeMultiLevelRequirements(currentReqs); } } break; case "Requirements": { Object obj = trace.remove(0); JSONObject jSONObject = (JSONObject) obj; String name = jSONObject.get("name").toString(); Requirements requirements = new Requirements(); requirements.setName(name); if (currentReqs.getUnitRequirements().contains(requirements)) { currentReqs.removeRequirements(requirements); } } break; case "Requirement": //here we need to continue to get the targeted Requirements block { Object obj = trace.remove(0); JSONObject jSONObject = (JSONObject) obj; String name = jSONObject.get("name").toString(); String type = jSONObject.get("type").toString(); for (Requirements r : currentReqs.getUnitRequirements()) { if (r.getName().equals(name)) { Object reqO = trace.remove(0); JSONObject jSONObjectReqo = (JSONObject) reqO; String nameReqo = jSONObjectReqo.get("name").toString(); Requirement requirement = new Requirement(); requirement.setName(nameReqo); for (Requirement req : r.getRequirements()) { if (req.getName().equals(nameReqo)) { r.getRequirements().remove(req); break; } } break; } } } break; case "Condition": //here we also need to get the requirement { Object obj = trace.remove(0); JSONObject jSONObject = (JSONObject) obj; String name = jSONObject.get("name").toString(); String type = jSONObject.get("type").toString(); for (Requirements r : currentReqs.getUnitRequirements()) { if (r.getName().equals(name)) { Object reqObj = trace.remove(0); JSONObject reqjSONObject = (JSONObject) reqObj; String reqname = reqjSONObject.get("name").toString(); String reqtype = reqjSONObject.get("type").toString(); for (Requirement req : r.getRequirements()) { if (req.getName().equals(reqname)) { Object rcondO = trace.remove(0); JSONObject jSONObjectCondo = (JSONObject) rcondO; String nameCondo = jSONObjectCondo.get("name").toString(); Condition condition = new Condition(); switch (nameCondo) { case "ENUMERATION": condition.setType(Condition.Type.ENUMERATION); break; case "EQUAL": condition.setType(Condition.Type.EQUAL); break; case "GREATER_EQUAL": condition.setType(Condition.Type.GREATER_EQUAL); break; case "LESS_EQUAL": condition.setType(Condition.Type.LESS_EQUAL); break; case "LESS_THAN": condition.setType(Condition.Type.LESS_THAN); break; case "RANGE": condition.setType(Condition.Type.RANGE); break; } for (Condition c : req.getConditions()) { if (c.getType().equals(condition.getType())) { req.getConditions().remove(c); break; } } break; } } break; } } } } }
From source file:at.ac.tuwien.dsg.quelle.sesConfigurationsRecommendationService.control.RequirementsManagementController.java
private void processAddToRequirementsJSONCommand(String json) { //TODO: To actually get the names from somwehere and conditions and etc. I need to do a bit more management //JSON looks like { "command" : "add", "type": "' + type+ '" "trace" : [{"name" : "ServiceReqs_overall_elasticity_multi", "type" : "SERVICE"}]}; Object command = JSONValue.parse(json); JSONObject jSONcommandObject = (JSONObject) command; JSONObject metaInfo = (JSONObject) jSONcommandObject.get("meta"); String whatToAdd = jSONcommandObject.get("type").toString(); JSONArray trace = (JSONArray) jSONcommandObject.get("trace"); JSONObject jSONRootObject = (JSONObject) trace.remove(0); String namejSONRootObject = jSONRootObject.get("name").toString(); String typejSONRootObject = jSONRootObject.get("type").toString(); //in order we traverse from root if (!requirements.getName().equals(namejSONRootObject) || !requirements.getLevel().toString().equals(typejSONRootObject)) { throw new RuntimeException("Something bad, as The requirements root does not match"); }/*ww w. j a v a 2 s. co m*/ //we go one by one with JSON and get corect requirements children //first we get through the multi level requirements MultiLevelRequirements currentReqs = requirements; while (!currentReqs.getContainedElements().isEmpty() && !trace.isEmpty()) { { Object obj = trace.get(0); boolean discovered = false; JSONObject jSONObject = (JSONObject) obj; String name = jSONObject.get("name").toString(); String type = jSONObject.get("type").toString(); for (MultiLevelRequirements r : currentReqs.getContainedElements()) { if (r.getName().equals(name) && r.getLevel().toString().equals(type)) { currentReqs = r; discovered = true; break; } } //so If for example I want to add Requirement on Requirements from Service, it will not be found in the MultiLevelRequirements (topology) //so, i need to keep it if (discovered) { trace.remove(0); } else { //if not discovered after a run, break while loop break; } } } //here we are at a point in which we need to start looking in individual requirements blocks, then individual requirements, then conditions //only if we add Requirements or Conditions. Otherwise all work on multi level reqs switch (whatToAdd) { case "Strategy": { String strategyType = metaInfo.get("strategy").toString(); Strategy s = new Strategy().withCategoryString(strategyType); if (!currentReqs.getOptimizationStrategies().contains(s)) { currentReqs.addStrategy(s); } break; } case "Topology": { MultiLevelRequirements levelRequirements = new MultiLevelRequirements( MonitoredElement.MonitoredElementLevel.SERVICE_TOPOLOGY); String topologyName = metaInfo.get("name").toString(); levelRequirements.setName(topologyName); if (!currentReqs.getContainedElements().contains(levelRequirements)) { currentReqs.addMultiLevelRequirements(levelRequirements); } } break; case "Unit": { MultiLevelRequirements levelRequirements = new MultiLevelRequirements( MonitoredElement.MonitoredElementLevel.SERVICE_UNIT); String unitName = metaInfo.get("name").toString(); levelRequirements.setName(unitName); if (!currentReqs.getContainedElements().contains(levelRequirements)) { currentReqs.addMultiLevelRequirements(levelRequirements); } } break; case "Requirements": { Requirements requirements = new Requirements(); String name = metaInfo.get("name").toString(); requirements.setName(name); if (!currentReqs.getUnitRequirements().contains(requirements)) { currentReqs.addRequirements(requirements); } } break; case "Requirement": //here we need to continue to get the targeted Requirements block { Object obj = trace.remove(0); JSONObject jSONObject = (JSONObject) obj; String name = jSONObject.get("name").toString(); String type = jSONObject.get("type").toString(); for (Requirements r : currentReqs.getUnitRequirements()) { if (r.getName().equals(name)) { Requirement requirement = new Requirement(); JSONObject metricInfo = (JSONObject) metaInfo.get("metric"); Metric metric = new Metric(metricInfo.get("name").toString(), metricInfo.get("unit").toString()); switch (metricInfo.get("type").toString()) { case "COST": metric.setType(Metric.MetricType.COST); break; case "RESOURCE": metric.setType(Metric.MetricType.RESOURCE); break; case "QUALITY": metric.setType(Metric.MetricType.QUALITY); break; } // + ', "unit": "' + selectedMetric.unit + '", "type":"' + selectedMetric.type + '"}'; requirement.setName(metricInfo.get("name").toString()); requirement.setMetric(metric); r.addRequirement(requirement); break; } } } break; case "Condition": //here we also need to get the requirement { Object obj = trace.remove(0); JSONObject jSONObject = (JSONObject) obj; String name = jSONObject.get("name").toString(); String type = jSONObject.get("type").toString(); for (Requirements r : currentReqs.getUnitRequirements()) { if (r.getName().equals(name)) { Object reqObj = trace.remove(0); JSONObject reqjSONObject = (JSONObject) reqObj; String reqname = reqjSONObject.get("name").toString(); String reqtype = reqjSONObject.get("type").toString(); for (Requirement req : r.getRequirements()) { if (req.getName().equals(reqname)) { Condition condition = new Condition(); // var selectedConditionType = conditionTypeSelect.options[conditionTypeSelect.selectedIndex]; // var conditionData = '{ "type":"' + selectedConditionType.text + '"' // + ', "value": "' + f.conditionValue.text + '"}'; // data = '{' + data + ', "meta" : { "condition":' + conditionData + ' } ' + '}'; JSONObject conditionJSON = (JSONObject) metaInfo.get("condition"); switch (conditionJSON.get("type").toString()) { case "LESS_THAN": condition.setType(Condition.Type.LESS_THAN); break; case "LESS_EQUAL": condition.setType(Condition.Type.LESS_EQUAL); break; case "GREATER_THAN": condition.setType(Condition.Type.GREATER_THAN); break; case "GREATER_EQUAL": condition.setType(Condition.Type.GREATER_EQUAL); break; case "EQUAL": condition.setType(Condition.Type.EQUAL); break; case "RANGE": condition.setType(Condition.Type.RANGE); break; case "ENUMERATION": condition.setType(Condition.Type.ENUMERATION); break; } List<MetricValue> metricValues = new ArrayList<>(); metricValues.add(new MetricValue(conditionJSON.get("value").toString())); condition.setValue(metricValues); req.addCondition(condition); break; } } break; } } } } }
From source file:com.googlecode.fascinator.portal.process.EmailNotifier.java
public String getCollectionValues(JsonSimple emailConfig, JsonSimple tfPackage, String varField) { String formattedCollectionValues = ""; JSONArray subKeys = emailConfig.getArray("collections", varField, "subKeys"); String tfPackageField = emailConfig.getString("", "collections", varField, "payloadKey"); if (StringUtils.isNotBlank(tfPackageField) && subKeys instanceof JSONArray) { List<JsonObject> jsonList = new StorageDataUtil().getJavaList(tfPackage, tfPackageField); log.debug("Collating collection values for email template..."); JSONArray fieldSeparators = emailConfig.getArray("collections", varField, "fieldSeparators"); String recordSeparator = emailConfig.getString(IOUtils.LINE_SEPARATOR, "collections", varField, "recordSeparator"); String nextDelimiter = " "; for (JsonObject collectionRow : jsonList) { if (fieldSeparators instanceof JSONArray && fieldSeparators.size() > 0) { // if no more delimiters, continue to use the last one specified Object nextFieldSeparator = fieldSeparators.remove(0); if (nextFieldSeparator instanceof String) { nextDelimiter = (String) nextFieldSeparator; } else { log.warn("Unable to retrieve String value from fieldSeparator: " + fieldSeparators.toString()); }//from w ww . j ava 2s .c o m } List<String> collectionValuesList = new ArrayList<String>(); for (Object requiredKey : subKeys) { Object rawKeyValue = collectionRow.get(requiredKey); if (rawKeyValue instanceof String) { String keyValue = StringUtils.trim((String) rawKeyValue); if (StringUtils.isNotBlank(keyValue)) { collectionValuesList.add(keyValue); } else if (!isVariableNameHiddenIfEmpty) { collectionValuesList.add("$" + requiredKey); } else { log.info("blank variable name will be hidden: " + keyValue); } } else { log.warn("No string value returned from: " + requiredKey); } } formattedCollectionValues += StringUtils.join(collectionValuesList, nextDelimiter) + recordSeparator; } formattedCollectionValues = StringUtils.chomp(formattedCollectionValues, recordSeparator); log.debug("email formatted collection values: " + formattedCollectionValues); } return formattedCollectionValues; }
From source file:io.github.casnix.mcdropshop.util.configsys.Shops.java
public final Shops delIndex(String shopName, String index, Player player) { if (!shops.containsKey(shopName)) { player.sendMessage("\u00a7eThat shop does not exist!"); return this; }/*from ww w .ja v a2 s . co m*/ try { String configTable = new String(Files.readAllBytes(Paths.get("./plugins/mcDropShop/Shops.json"))); JSONParser parser = new JSONParser(); Object obj = parser.parse(configTable); JSONObject jsonObj = (JSONObject) obj; JSONObject shopObj = (JSONObject) jsonObj.get(shopName); JSONArray shopItems = (JSONArray) shopObj.get("ShopItems"); if (shopItems.size() <= Integer.parseInt(index)) { player.sendMessage("\u00a7eThat shop doesn't have an item at index (" + index + ")!"); return this; } String itemName = (String) shopItems.get(Integer.parseInt(index)); shopItems.remove(Integer.parseInt(index)); shopObj.put("ShopItems", shopItems); shopObj.remove(itemName); jsonObj.put(shopName, shopObj); // Update Shops.json FileWriter shopsJSON = new FileWriter("./plugins/mcDropShop/Shops.json"); shopsJSON.write(jsonObj.toJSONString()); shopsJSON.flush(); shopsJSON.close(); player.sendMessage("\u00a7aShop updated!"); return this; } catch (ParseException e) { Bukkit.getLogger().warning("[mcDropShop] Caught ParseException in delIndex()"); e.printStackTrace(); } catch (FileNotFoundException e) { Bukkit.getLogger().warning("[mcDropShop] Could not find ./plugins/mcDropShop/Shops.json"); e.printStackTrace(); } catch (IOException e) { Bukkit.getLogger().warning("[mcDropShop] Caught IOException in delIndex()"); e.printStackTrace(); } return this; }
From source file:io.github.casnix.mcdropshop.util.configsys.Shops.java
public final Shops repBuy(String shopName, String cost, String index, Player player) { if (!shops.containsKey(shopName)) { player.sendMessage("\u00a7eThat shop does not exist!"); return this; }//from w ww .j ava2s . c o m try { String configTable = new String(Files.readAllBytes(Paths.get("./plugins/mcDropShop/Shops.json"))); JSONParser parser = new JSONParser(); Object obj = parser.parse(configTable); JSONObject jsonObj = (JSONObject) obj; JSONObject shopObj = (JSONObject) jsonObj.get(shopName); JSONArray shopItems = (JSONArray) shopObj.get("ShopItems"); if (shopItems.size() <= Integer.parseInt(index)) { player.sendMessage("\u00a7eThat shop doesn't have an item at index (" + index + ")!"); return this; } String itemName = (String) shopItems.get(Integer.parseInt(index)); shopObj.remove(itemName); shopItems.remove(Integer.parseInt(index)); String newItem = player.getItemInHand().getType().name(); Bukkit.getLogger() .info("Player \"" + player.getDisplayName() + "\" added " + newItem + " to shop " + shopName); shopItems.add(Integer.parseInt(index), newItem + ":buy:" + player.getItemInHand().getDurability()); shopObj.put("ShopItems", shopItems); JSONObject itemStub = new JSONObject(); itemStub.put("amount", Integer.toString(player.getItemInHand().getAmount())); itemStub.put("price", cost); itemStub.put("type", "buy"); itemStub.put("durability", "" + player.getItemInHand().getDurability()); shopObj.put(newItem + ":buy:" + player.getItemInHand().getDurability(), itemStub); shopObj.put("ShopItems", shopItems); jsonObj.put(shopName, shopObj); // Update Shops.json FileWriter shopsJSON = new FileWriter("./plugins/mcDropShop/Shops.json"); shopsJSON.write(jsonObj.toJSONString()); shopsJSON.flush(); shopsJSON.close(); player.sendMessage("\u00a7aShop updated!"); return this; } catch (ParseException e) { Bukkit.getLogger().warning("[mcDropShop] Caught ParseException in repBuy()"); e.printStackTrace(); } catch (FileNotFoundException e) { Bukkit.getLogger().warning("[mcDropShop] Could not find ./plugins/mcDropShop/Shops.json"); e.printStackTrace(); } catch (IOException e) { Bukkit.getLogger().warning("[mcDropShop] Caught IOException in repBuy()"); e.printStackTrace(); } return this; }