List of usage examples for org.json.simple JSONObject clear
void clear();
From source file:net.modsec.ms.connector.ConnRequestHandler.java
/** * Parses the json, extracts the rules and deploy those rules into modsecurity. It takes the rule * string from the json and creates a rule file then copy it to modsecurity rule file folder. It alsp * restarts the modsecurity after deploying the rule * @param json reponses whether the rule is successfully deployed or not. *///from www . j a va 2 s. co m @SuppressWarnings("unchecked") public static void onDeployMSRules(JSONObject json) { log.info("onDeployMSRules called.. : " + json.toJSONString()); MSConfig serviceCfg = MSConfig.getInstance(); JSONObject jsonResp = new JSONObject(); String ruleDirPath = serviceCfg.getConfigMap().get("RuleFileDir"); String ruleFileString = (String) json.get("ruleString"); String ruleFileName = ""; InputStream ins = null; FileOutputStream out = null; BufferedReader br = null; if (json.containsKey("groupName")) { ruleFileName += ((String) json.get("groupName")).toLowerCase() + ".conf"; } else { UUID randomName = UUID.randomUUID(); ruleFileName += randomName.toString() + ".conf"; } try { //modified string writing to modsecurity configurations log.info("Writing a rule to File :" + ruleFileName); File file = new File(ruleDirPath + "/" + ruleFileName); file.createNewFile(); out = new FileOutputStream(file); out.write(ruleFileString.getBytes()); out.close(); log.info("ModSecurity Rules Written ... "); //For Restarting modsecurity so that modified configuration can be applied JSONObject restartJson = new JSONObject(); restartJson.put("action", "restart"); String cmd = serviceCfg.getConfigMap().get("MSRestart"); String status = (String) executeShScript(cmd, restartJson).get("status"); //if rule file is giving syntax error while deploying rules on server end if (status.equals("1")) { if (file.delete()) { log.info("Successfully deleted conflicting file : " + file.getName()); executeShScript(cmd, restartJson); } else { log.info("unable to delete file : " + file.getName()); } jsonResp.put("action", "deployRules"); jsonResp.put("status", "1"); jsonResp.put("message", "Unable to deploy specified Rules. They either" + "conflicting to the already deployed rules"); } else { jsonResp.put("action", "deployRules"); jsonResp.put("status", "0"); jsonResp.put("message", "Rules Deployed!"); } } catch (FileNotFoundException e1) { jsonResp.put("action", "deployRules"); jsonResp.put("status", "1"); jsonResp.put("message", "Internal Service is down!"); e1.printStackTrace(); } catch (IOException | NullPointerException e) { jsonResp.put("action", "deployRules"); jsonResp.put("status", "0"); jsonResp.put("message", "Unable to create rule file on Server."); e.printStackTrace(); } log.info("Sending Json :" + jsonResp.toJSONString()); ConnectorService.getConnectorProducer().send(jsonResp.toJSONString()); jsonResp.clear(); }
From source file:com.caspida.plugins.graph.EntityGraphNeo4jPlugin.java
/** * request = {"start" : {"type":"User", "value":"userId"}, * "end" : {"type":"Device",/*from w w w . java 2s. c o m*/ * "values": ["deviceId1", "deviceId2", "deviceId3"]}, * "relationship" : "ConnectsTo", * "propertyName" : "<some property name>"} * * response = {"edges": {"deviceId1": ["<property value>", "<nodeId>"], * "deviceId2": ["<property value>", "<nodeId>"], * "deviceId3": ["<property value>", "<nodeId>"] * } * } * * @param graphDb * @param json * @return */ @Name(EntityGraphConstants.API_GET_NEIGHBORHOOD_PROPERTY) @Description("Get properties of the connected node and the edge if it exists") @PluginTarget(GraphDatabaseService.class) public String getNeighborNodeAndEdgeProperty(@Source GraphDatabaseService graphDb, @Description("Request JSON") @Parameter(name = "data", optional = true) String json) { JSONObject response = new JSONObject(); try { JSONParser parser = new JSONParser(); JSONObject request = (JSONObject) parser.parse(json); Object tmp = request.get(EntityGraphConstants.REQ_EDGE_PROPS_START_KEY); if (tmp == null) { return response.toJSONString(); } JSONObject start = (JSONObject) tmp; tmp = request.get(EntityGraphConstants.REQ_EDGE_PROPS_END_KEY); if (tmp == null) { return response.toJSONString(); } JSONObject end = (JSONObject) tmp; tmp = start.get(EntityGraphConstants.REQ_EDGE_PROPS_START_VALUE_KEY); if (tmp == null) { return response.toJSONString(); } String startNodeId = tmp.toString(); tmp = end.get(EntityGraphConstants.REQ_EDGE_PROPS_END_VALUES_KEY); if (tmp == null) { return response.toJSONString(); } JSONArray endValues = (JSONArray) tmp; if (endValues.size() == 0) { return response.toJSONString(); } Set<String> endNodeIds = new HashSet<>(); for (Object endValue : endValues) { endNodeIds.add(endValue.toString()); } tmp = request.get(EntityGraphConstants.REQ_EDGE_PROPS_RELNAME_KEY); if (tmp == null) { return response.toJSONString(); } DynamicRelationshipType relName = DynamicRelationshipType.withName(tmp.toString()); tmp = request.get(EntityGraphConstants.REQ_EDGE_PROPS_PROPNAME_KEY); if (tmp == null) { return response.toJSONString(); } String propertyName = tmp.toString(); response.clear(); JSONObject responseEdges = new JSONObject(); // get all thr relationships try (Transaction txn = graphDb.beginTx()) { Index<Node> nodeIndex = graphDb.index().forNodes(EntityGraphConstants.EVENT_CLASS); Node node = findNode(graphDb, startNodeId, nodeIndex); if (logger.isDebugEnabled()) { logger.debug("Found node with id {} => node id", startNodeId, (node != null) ? node.getId() : "-1"); } if (node != null) { Iterable<Relationship> rels = node.getRelationships(relName); for (Relationship rel : rels) { Node otherNode = (rel.getStartNode().getId() == node.getId()) ? rel.getEndNode() : rel.getStartNode(); Object value = null; Object otherNodeId = null; try { otherNodeId = otherNode.getProperty(EntityGraphConstants.NODE_ID); } catch (Exception e) { } if (otherNodeId == null) { logger.error("Node without a ID property {}", otherNode.getId()); continue; } // if the JSONArray contains this node if (!endNodeIds.remove(otherNodeId.toString())) { // not interested all edges continue; } value = null; try { value = rel.getProperty(propertyName); } catch (Exception e) { } JSONArray dat = new JSONArray(); dat.add(0, (value != null) ? value.toString() : "1.0"); dat.add(1, otherNode.getId()); responseEdges.put(otherNodeId, dat); } } // for the remaining end nodes that were not part of the // relationships find the node id and return for (String endNodeId : endNodeIds) { Node endNode = findNode(graphDb, endNodeId, nodeIndex); JSONArray dat = new JSONArray(); dat.add(0, ""); dat.add(1, (endNode != null) ? endNode.getId() : "-1"); responseEdges.put(endNodeId, dat); } response.put(EntityGraphConstants.RES_EDGE_PROPS_EDGES_KEY, responseEdges); } } catch (Throwable e) { logger.error("Failed to create entity graph : " + json, e); createErrorResponse(response, EntityGraphConstants.API_GET_NEIGHBORHOOD_PROPERTY, "Failed to create entity graph", e); } if (logger.isDebugEnabled()) { logger.debug("Response : {}", response.toJSONString()); } return response.toJSONString(); }
From source file:net.modsec.ms.connector.ConnRequestHandler.java
/** * Writes the modified modsecurity configurations to configuration file. * @param json contains modsecurity configurations as json object. *///from w ww.j av a 2 s .c o m @SuppressWarnings("unchecked") public static void onWriteMSConfig(JSONObject json) { log.info("onWriteMSConfig called.. : " + json.toJSONString()); MSConfig serviceCfg = MSConfig.getInstance(); JSONObject jsonResp = new JSONObject(); String fileName = serviceCfg.getConfigMap().get("MSConfigFile"); String modifiedStr = ""; InputStream ins = null; FileOutputStream out = null; BufferedReader br = null; try { File file = new File(fileName); DataInputStream in; @SuppressWarnings("resource") FileChannel channel = new RandomAccessFile(file, "rw").getChannel(); FileLock lock = channel.lock(); try { ins = new FileInputStream(file); in = new DataInputStream(ins); br = new BufferedReader(new InputStreamReader(in)); String line = ""; boolean check; while ((line = br.readLine()) != null) { check = true; //log.info("Line :" + line); for (ModSecConfigFields field : ModSecConfigFields.values()) { if (line.startsWith(field.toString())) { if (line.trim().split(" ")[0].equals(field.toString())) { if (json.containsKey(field.toString())) { if (((String) json.get(field.toString())).equals("") || json.get(field.toString()) == null) { log.info("---------- Log Empty value ----:" + (String) json.get(field.toString())); json.remove(field.toString()); check = false; continue; } else { modifiedStr += field.toString() + " " + json.remove(field.toString()) + "\n"; check = false; } } } } } if (check) { modifiedStr += line + "\n"; } } for (ModSecConfigFields field : ModSecConfigFields.values()) { if (json.containsKey(field.toString())) { if (json.get(field.toString()) == null || ((String) json.get(field.toString())).equals("")) { log.info("---------- Log Empty value ----:" + (String) json.get(field.toString())); json.remove(field.toString()); check = false; continue; } else { modifiedStr += field.toString() + " " + json.remove(field.toString()) + "\n"; } } } //modified string writing to modsecurity configurations log.info("Writing File :" + modifiedStr); out = new FileOutputStream(fileName); out.write(modifiedStr.getBytes()); log.info("ModSecurity Configurations configurations Written ... "); } finally { lock.release(); } br.close(); in.close(); ins.close(); out.close(); //For Restarting modsecurity so that modified configuration can be applied JSONObject restartJson = new JSONObject(); restartJson.put("action", "restart"); String cmd = serviceCfg.getConfigMap().get("MSRestart"); executeShScript(cmd, restartJson); jsonResp.put("action", "writeMSConfig"); jsonResp.put("status", "0"); jsonResp.put("message", "Configurations updated!"); } catch (FileNotFoundException e1) { jsonResp.put("action", "writeMSConfig"); jsonResp.put("status", "1"); jsonResp.put("message", "Internal Service is down!"); e1.printStackTrace(); } catch (IOException | NullPointerException e) { jsonResp.put("action", "writeMSConfig"); jsonResp.put("status", "0"); jsonResp.put("message", "Unable to modify configurations. Sorry of inconvenience"); e.printStackTrace(); } log.info("Sending Json :" + jsonResp.toJSONString()); ConnectorService.getConnectorProducer().send(jsonResp.toJSONString()); jsonResp.clear(); }
From source file:com.ntua.cosmos.hackathonplanneraas.Planner.java
@Deprecated public JSONObject searchEventSolution(JSONObject obj) { StoredPaths pan = new StoredPaths(); JSONObject returned = new JSONObject(); long since = 0; long ts = 0;/* w w w. j ava2 s . c o m*/ ArrayList<String> names = new ArrayList<>(); ArrayList<String> values = new ArrayList<>(); String originalString = ""; double similarity = 0.0, current = 0.0; if (!obj.isEmpty()) { Set keys = obj.keySet(); Iterator iter = keys.iterator(); for (; iter.hasNext();) { String temporary = String.valueOf(iter.next()); if (temporary.startsWith("has")) names.add(temporary); } names.stream().forEach((name) -> { values.add(String.valueOf(obj.get(name))); }); } originalString = values.stream().map((value) -> value).reduce(originalString, String::concat); //Begin the initialisation process. OntModelSpec s = new OntModelSpec(PelletReasonerFactory.THE_SPEC); OntDocumentManager dm = OntDocumentManager.getInstance(); dm.setFileManager(FileManager.get()); s.setDocumentManager(dm); OntModel m = ModelFactory.createOntologyModel(s, null); InputStream in = FileManager.get().open(StoredPaths.casebasepath); if (in == null) { throw new IllegalArgumentException("File: " + StoredPaths.casebasepath + " not found"); } // read the file m.read(in, null); //begin building query string. String queryString = pan.prefixrdf + pan.prefixowl + pan.prefixxsd + pan.prefixrdfs + pan.prefixCasePath; queryString += "\nSELECT DISTINCT "; for (int i = 0; i < names.size(); i++) { queryString += "?param" + i + " "; } queryString += "?message ?handle ?URI WHERE {"; for (int i = 0; i < names.size(); i++) { queryString += "?event base:" + names.get(i) + " ?param" + i + " . "; } queryString += "?event base:isSolvedBy ?solution . ?solution base:exposesMessage ?message . ?solution base:eventHandledBy ?handle . ?solution base:URI ?URI}"; try { String testString = ""; Query query = QueryFactory.create(queryString); QueryExecution qe = QueryExecutionFactory.create(query, m); ResultSet results = qe.execSelect(); for (; results.hasNext();) { QuerySolution soln = results.nextSolution(); // Access variables: soln.get("x"); Literal lit; for (int i = 0; i < names.size(); i++) { lit = soln.getLiteral("param" + i);// Get a result variable by name. String temporary = String.valueOf(lit).substring(0, String.valueOf(lit).indexOf("^^")); testString += temporary; } String longer = testString, shorter = originalString; if (testString.length() < originalString.length()) { // longer should always have greater length longer = originalString; shorter = testString; } int longerLength = longer.length(); System.out.println("Similarity between:" + originalString + " and " + testString + " is:"); current = (longerLength - StringUtils.getLevenshteinDistance(longer, shorter)) / (double) longerLength; System.out.println(current + " out of 1.0."); if (similarity < current) { similarity = current; returned.clear(); returned.put("message", soln.getLiteral("message").getString()); returned.put("URI", soln.getLiteral("URI").getString()); returned.put("handle", soln.getLiteral("handle").getString()); } } } catch (Exception e) { System.out.println("Search is interrupted by an error."); } m.close(); return returned; }
From source file:com.ntua.cosmos.hackathonplanneraas.Planner.java
@Deprecated private String getPOSTBody(JSONObject obj) { String body = "{}"; StoredPaths pan = new StoredPaths(); JSONObject returned = new JSONObject(); ArrayList<String> names = new ArrayList<>(); ArrayList<String> values = new ArrayList<>(); String originalString = ""; double similarity = 0.0, current = 0.0; if (!obj.isEmpty()) { Set keys = obj.keySet();/*from w ww. j av a 2 s . c om*/ Iterator iter = keys.iterator(); for (; iter.hasNext();) { String temporary = String.valueOf(iter.next()); if (temporary.startsWith("has")) names.add(temporary); } names.stream().forEach((name) -> { values.add(String.valueOf(obj.get(name))); }); } originalString = values.stream().map((value) -> value).reduce(originalString, String::concat); //Begin the initialisation process. OntModelSpec s = new OntModelSpec(PelletReasonerFactory.THE_SPEC); //s.setReasoner(PelletReasonerFactory.theInstance().create()); OntDocumentManager dm = OntDocumentManager.getInstance(); dm.setFileManager(FileManager.get()); s.setDocumentManager(dm); OntModel m = ModelFactory.createOntologyModel(s, null); //OntModel m = ModelFactory.createOntologyModel( PelletReasonerFactory.THE_SPEC ); InputStream in = FileManager.get().open(StoredPaths.casebasepath); if (in == null) { throw new IllegalArgumentException("File: " + StoredPaths.casebasepath + " not found"); } // read the file m.read(in, null); //begin building query string. String queryString = pan.prefixrdf + pan.prefixowl + pan.prefixxsd + pan.prefixrdfs + pan.prefixCasePath; queryString += "\nSELECT DISTINCT "; for (int i = 0; i < names.size(); i++) { queryString += "?param" + i + " "; } queryString += "?message ?handle ?URI ?body WHERE {"; for (int i = 0; i < names.size(); i++) { queryString += "?event base:" + names.get(i) + " ?param" + i + " . "; } queryString += "?event base:isSolvedBy ?solution . ?solution base:exposesMessage ?message . ?solution base:eventHandledBy ?handle . ?solution base:URI ?URI . ?solution base:hasPOSTBody ?body}"; try { String testString = ""; Query query = QueryFactory.create(queryString); //System.out.println(String.valueOf(query)); QueryExecution qe = QueryExecutionFactory.create(query, m); ResultSet results = qe.execSelect(); for (; results.hasNext();) { QuerySolution soln = results.nextSolution(); // Access variables: soln.get("x"); Literal lit; for (int i = 0; i < names.size(); i++) { lit = soln.getLiteral("param" + i);// Get a result variable by name. String temporary = String.valueOf(lit).substring(0, String.valueOf(lit).indexOf("^^")); testString += temporary; } String longer = testString, shorter = originalString; if (testString.length() < originalString.length()) { // longer should always have greater length longer = originalString; shorter = testString; } int longerLength = longer.length(); current = (longerLength - StringUtils.getLevenshteinDistance(longer, shorter)) / (double) longerLength; if (similarity < current) { similarity = current; returned.clear(); returned.put("message", soln.getLiteral("message").getString()); returned.put("URI", soln.getLiteral("URI").getString()); returned.put("handle", soln.getLiteral("handle").getString()); body = soln.getLiteral("body").getString(); } } } catch (Exception e) { System.out.println("Search is interrupted by an error."); } m.close(); return body; }
From source file:replicatedstackjgroups.ReplSet.java
private void eventLoop() { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); Scanner input = new Scanner(System.in); JSONObject json_obj = new JSONObject(); while (true) { try {// w w w . j ava 2 s. co m System.out.print("> "); System.out.flush(); // String line = in.readLine().toLowerCase(); String line = input.next().toLowerCase(); if (line.startsWith("quit") || line.startsWith("exit")) break; else if (line.startsWith("set_add")) { T packet = (T) input.nextLine(); json_obj.put("mode", "set_add"); json_obj.put("body", packet); } else if (line.startsWith("set_contains")) { T packet = (T) input.nextLine(); json_obj.put("mode", "set_contains"); json_obj.put("body", packet); } else if (line.startsWith("set_remove")) { T packet = (T) input.nextLine(); json_obj.put("mode", "set_remove"); json_obj.put("body", packet); } else if (line.startsWith("set_print")) { printSet(); json_obj.put("mode", "print"); json_obj.put("body", ""); } Message msg = new Message(null, null, json_obj); channel.send(msg); json_obj.clear(); } catch (Exception e) { } } }
From source file:replicatedstackjgroups.ReplStack.java
private void eventLoop() { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); Scanner input = new Scanner(System.in); JSONObject json_obj = new JSONObject(); while (true) { try {// w ww . j a v a 2 s . c o m System.out.print("> "); System.out.flush(); // String line = in.readLine().toLowerCase(); String line = input.next().toLowerCase(); if (line.startsWith("quit") || line.startsWith("exit")) break; else if (line.startsWith("stack_push")) { T object = (T) input.nextLine(); json_obj.put("mode", "stack_push"); json_obj.put("body", object); } else if (line.startsWith("stack_pop")) { json_obj.put("mode", "stack_pop"); json_obj.put("body", ""); } else if (line.startsWith("stack_top")) { json_obj.put("mode", "stack_top"); json_obj.put("body", ""); } Message msg = new Message(null, null, json_obj); channel.send(msg); json_obj.clear(); } catch (Exception e) { } } }
From source file:test.BuildComplexKnowledgeBase.java
/** * //from ww w.j a va 2 s . c o m */ public BuildComplexKnowledgeBase() { environment = new JSONDocStoreEnvironment(); model = environment.getModel(); IResult rx = null; JSONObject jo = new JSONObject(); //Build a root object jo.put(BuildComplexKnowledgeBase.LOCATOR, BuildComplexKnowledgeBase.ROOTID); jo.put(NAMESTRING, "KnowledgeBase Tree Root"); rx = model.putDocument(ROOTID, INDEX, TYPE, jo, false); displayErrorMessage(1, rx); //Build the types //AssociationType jo.clear(); jo.put(LOCATOR, ASSOCIATIONTYPEID); jo.put(SUBOF, ROOTID); jo.put(NAMESTRING, "Association Type"); rx = model.putDocument(ASSOCIATIONTYPEID, INDEX, TYPE, jo, false); displayErrorMessage(2, rx); //Causal AssociationType jo.clear(); jo.put(LOCATOR, CAUSALID); jo.put(SUBOF, ASSOCIATIONTYPEID); jo.put(NAMESTRING, "Causal Association Type"); rx = model.putDocument(CAUSALID, INDEX, TYPE, jo, false); displayErrorMessage(3, rx); //MoleculeType jo.clear(); jo.put(LOCATOR, MOLECULETYPEID); jo.put(SUBOF, ROOTID); jo.put(NAMESTRING, "Molecule Type"); rx = model.putDocument(MOLECULETYPEID, INDEX, TYPE, jo, false); displayErrorMessage(4, rx); //ProcessType jo.clear(); jo.put(LOCATOR, PROCESSTYPEID); jo.put(SUBOF, ROOTID); jo.put(NAMESTRING, "Process Type"); rx = model.putDocument(PROCESSTYPEID, INDEX, TYPE, jo, false); displayErrorMessage(5, rx); //ProcessType jo.clear(); jo.put(LOCATOR, ATMOSPROCESSID); jo.put(SUBOF, PROCESSTYPEID); jo.put(NAMESTRING, "Atmospheric Process"); rx = model.putDocument(ATMOSPROCESSID, INDEX, TYPE, jo, false); displayErrorMessage(6, rx); //CO2 JSONObject cox = new JSONObject(); cox.put(LOCATOR, CO2ID); cox.put(SUBOF, MOLECULETYPEID); cox.put(NAMESTRING, "Carbon Dioxide"); rx = model.putDocument(CO2ID, INDEX, TYPE, cox, false); displayErrorMessage(7, rx); //Climate Change JSONObject ccx = new JSONObject(); ccx.put(LOCATOR, CLIMATECHANGEID); ccx.put(SUBOF, ATMOSPROCESSID); ccx.put(NAMESTRING, "Climate Change"); rx = model.putDocument(CLIMATECHANGEID, INDEX, TYPE, ccx, false); displayErrorMessage(8, rx); //Create an association: co2 cause climate change String ASSOCIATION_ID = CO2ID + "." + CAUSALID + "." + CLIMATECHANGEID; jo.clear(); jo.put(LOCATOR, ASSOCIATION_ID); jo.put(INSTANCEOF, ASSOCIATIONTYPEID); jo.put(SOURCETOPIC, CO2ID); jo.put(TARGETTOPIC, CLIMATECHANGEID); jo.put(NAMESTRING, "CO2 causes Climate Change"); rx = model.putDocument(ASSOCIATION_ID, INDEX, TYPE, jo, false); displayErrorMessage(9, rx); //now wire the association cox.put(ASSOCIATIONS, ASSOCIATION_ID); rx = model.putDocument(CO2ID, INDEX, TYPE, cox, false); displayErrorMessage(10, rx); ccx.put(ASSOCIATIONS, ASSOCIATION_ID); rx = model.putDocument(CLIMATECHANGEID, INDEX, TYPE, ccx, false); displayErrorMessage(11, rx); rx = model.getDocument(INDEX, TYPE, ASSOCIATION_ID); //now fetch something displayErrorMessage(10, rx); System.out.println(rx.getResultObject()); environment.shutDown(); }
From source file:test.FirstBigQueryTest.java
/** * /*from w w w . j av a2 s . c o m*/ */ public FirstBigQueryTest() { environment = new JSONDocStoreEnvironment(); model = environment.getModel(); JSONObject jo = new JSONObject(); jo.put("id", ID); jo.put("subOf", ID2); IResult rx = model.putDocument(ID, INDEX, TYPE, jo, false); System.out.println("AAA " + rx.getErrorString()); jo.clear(); jo.put("id", ID2); model.putDocument(ID2, INDEX, TYPE, jo, false); System.out.println("BBB " + rx.getErrorString()); jo.clear(); jo.put("id", ID3); jo.put("subOf", ID2); model.putDocument(ID3, INDEX, TYPE, jo, false); System.out.println("CCC " + rx.getErrorString()); //{ // "term" : { // "subOf" : "AnimalType" // } //QueryBuilder queryBuilder = QueryBuilders.termQuery("subOf", ID2); // "match" and "term" fail No search type for [foo] // String query = "{\"query\": {\"term\": {\"subOf\": \""+ID2+"\"}}}"; // String query = "{\"query\": {\"match\": {\"subOf\": \""+ID2+"\"}}}"; String query = "{\"match\": {\"subOf\": \"" + ID2 + "\"}}"; rx = model.runQuery(INDEX, query, 0, -1, TYPE); //AbstractBaseElasticSearchModel.runQuery- {"size": 12,"query": {"match": {"subOf": "AnimalType"}}} System.out.println(rx.hasError() + " " + rx.getResultObject()); if (rx.hasError()) System.out.println("ERR " + rx.getErrorString()); rx = model.getDocument(INDEX, null, ID); System.out.println(rx.hasError() + " " + rx.getResultObject()); environment.shutDown(); }
From source file:test.FirstCountTest.java
/** * //from www.j av a 2 s . co m */ public FirstCountTest() { environment = new JSONDocStoreEnvironment(); model = environment.getModel(); JSONObject jo = new JSONObject(); jo.put("id", ID); jo.put("subOf", ID2); IResult rx = model.putDocument(ID, INDEX, TYPE1, jo, false); System.out.println("AAA " + rx.getErrorString()); jo.clear(); jo.put("id", ID2); model.putDocument(ID2, INDEX, TYPE1, jo, false); System.out.println("BBB " + rx.getErrorString()); jo.clear(); jo.put("id", ID3); JSONArray array = new JSONArray(); array.add(ID2); // array.add(ID4); jo.put("subOf", array); model.putDocument(ID3, INDEX, TYPE2, jo, false); //Curiosity test of multiple types String query = "{\"match\": {\"subOf\": \"" + ID2 + "\"}}"; rx = model.runQuery(INDEX, query, 0, -1, TYPE1, TYPE2); System.out.println(rx.hasError() + " " + rx.getResultObject()); if (rx.hasError()) System.out.println("ERR " + rx.getErrorString()); //Count type rx = model.countDocuments(INDEX); System.out.println(rx.hasError() + " " + rx.getResultObject()); if (rx.hasError()) System.out.println("ERR " + rx.getErrorString()); rx = model.getDocument(INDEX, null, ID); System.out.println(rx.hasError() + " " + rx.getResultObject()); if (rx.hasError()) System.out.println("ERR " + rx.getErrorString()); //all important environment.shutDown(); }