List of usage examples for org.json.simple JSONArray iterator
public Iterator<E> iterator()
From source file:com.modeln.batam.connector.wrapper.BuildEntry.java
@SuppressWarnings("unchecked") public static BuildEntry fromJSON(JSONObject obj) { String id = (String) obj.get("id"); String name = (String) obj.get("name"); String startDate = (String) obj.get("start_date"); String endDate = (String) obj.get("end_date"); String status = (String) obj.get("status"); String description = (String) obj.get("description"); boolean override = (Boolean) obj.get("override") == null ? false : (Boolean) obj.get("override"); List<Pair> criterias = new ArrayList<Pair>(); JSONArray criteriasArray = (JSONArray) obj.get("criterias"); if (criteriasArray != null) { for (Iterator<JSONObject> it = criteriasArray.iterator(); it.hasNext();) { JSONObject criteria = it.next(); criterias.add(Pair.fromJSON(criteria)); }/*from w ww.j a va 2 s. c om*/ } List<Pair> infos = new ArrayList<Pair>(); JSONArray infosArray = (JSONArray) obj.get("infos"); if (infosArray != null) { for (Iterator<JSONObject> it = infosArray.iterator(); it.hasNext();) { JSONObject info = it.next(); infos.add(Pair.fromJSON(info)); } } List<Pair> reports = new ArrayList<Pair>(); JSONArray reportsArray = (JSONArray) obj.get("reports"); if (reportsArray != null) { for (Iterator<JSONObject> it = reportsArray.iterator(); it.hasNext();) { JSONObject report = it.next(); reports.add(Pair.fromJSON(report)); } } List<Step> steps = new ArrayList<Step>(); JSONArray stepsArray = (JSONArray) obj.get("steps"); if (stepsArray != null) { for (Iterator<JSONObject> it = stepsArray.iterator(); it.hasNext();) { JSONObject step = it.next(); steps.add(Step.fromJSON(step)); } } List<Commit> commits = new ArrayList<Commit>(); JSONArray commitsArray = (JSONArray) obj.get("commits"); if (commitsArray != null) { for (Iterator<JSONObject> it = commitsArray.iterator(); it.hasNext();) { JSONObject commit = it.next(); commits.add(Commit.fromJSON(commit)); } } boolean isCustomFormatEnabled = (Boolean) obj.get("isCustomFormatEnabled") == null ? false : (Boolean) obj.get("isCustomFormatEnabled"); String customFormat = (String) obj.get("customFormat"); String customEntry = (String) obj.get("customEntry"); return new BuildEntry(id, name, startDate == null ? null : new Date(Long.valueOf(startDate)), endDate == null ? null : new Date(Long.valueOf(endDate)), status, description, criterias, infos, reports, steps, commits, override, isCustomFormatEnabled, customFormat, customEntry); }
From source file:com.modeln.batam.connector.wrapper.TestEntry.java
@SuppressWarnings("unchecked") public static TestEntry fromJSON(JSONObject obj) { String id = (String) obj.get("id"); String buildId = (String) obj.get("build_id"); String buildName = (String) obj.get("build_name"); String reportId = (String) obj.get("report_id"); String reportName = (String) obj.get("report_name"); String name = (String) obj.get("name"); String description = (String) obj.get("description"); String startDate = (String) obj.get("start_date"); String endDate = (String) obj.get("end_date"); String status = (String) obj.get("status"); boolean override = (Boolean) obj.get("override"); List<Pair> criterias = new ArrayList<Pair>(); JSONArray criteriasArray = (JSONArray) obj.get("criterias"); if (criteriasArray != null) { for (Iterator<JSONObject> it = criteriasArray.iterator(); it.hasNext();) { JSONObject criteria = it.next(); criterias.add(Pair.fromJSON(criteria)); }/*from ww w .j ava 2 s.c om*/ } List<String> tags = new ArrayList<String>(); JSONArray tagsArray = (JSONArray) obj.get("tags"); if (tagsArray != null) { for (Iterator<String> it = tagsArray.iterator(); it.hasNext();) { String tag = it.next(); tags.add(tag); } } List<Step> steps = new ArrayList<Step>(); JSONArray stepsArray = (JSONArray) obj.get("steps"); if (stepsArray != null) { for (Iterator<JSONObject> it = stepsArray.iterator(); it.hasNext();) { JSONObject step = it.next(); steps.add(Step.fromJSON(step)); } } String log = (String) obj.get("log"); boolean isCustomFormatEnabled = (Boolean) obj.get("isCustomFormatEnabled") == null ? false : (Boolean) obj.get("isCustomFormatEnabled"); String customFormat = (String) obj.get("customFormat"); String customEntry = (String) obj.get("customEntry"); return new TestEntry(id, buildId, buildName, reportId, reportName, name, description, startDate == null ? null : new Date(Long.valueOf(startDate)), endDate == null ? null : new Date(Long.valueOf(endDate)), status, criterias, tags, steps, log, override, isCustomFormatEnabled, customFormat, customEntry); }
From source file:com.storageroomapp.client.field.Fields.java
static public Fields parseJsonFieldArray(Collection parent, JSONArray jsonObj) { if ((parent == null) || (jsonObj == null)) { return null; }/*from w w w .j a v a 2 s. c o m*/ Fields fields = new Fields(parent); // parse and build the DATA fields (the ones unique to this Collection) @SuppressWarnings("unchecked") Iterator<JSONObject> iter = jsonObj.iterator(); while (iter.hasNext()) { JSONObject fieldObj = iter.next(); GenericField<?> field = parseJsonFieldObject(parent, fieldObj); if (field != null) { fields.add(field); fields.dataFieldsOnlyList.add(field); } } // build the METADATA fields (common to all Collections) for (GenericField<?> field : metadataFields) { fields.add(field.cloneAsMetadataField(parent)); } return fields; }
From source file:com.jts.rest.profileservice.utils.RestServiceHelper.java
/** * Uses MemberChallenge service to get all the associated challenge information for a user * Sorts the challenge information with end date * Returns all the active challenges and 3 most recent past challenge * @param sessionId//from w w w . j a v a 2 s. c om * @param username * @return * @throws MalformedURLException * @throws IOException */ @SuppressWarnings("unchecked") public static JSONObject getProcessedChallengesM1(String sessionId, String username) throws MalformedURLException, IOException { //get all challenges JSONArray challenges = getChallenges(sessionId, username); JSONArray activeChallenges = new JSONArray(); JSONArray pastChallenges = new JSONArray(); SortedMap<Long, JSONObject> pastChallengesByDate = new TreeMap<Long, JSONObject>(); Iterator<JSONObject> iterator = challenges.iterator(); DateFormat dateFormat = new SimpleDateFormat("yyyy-mm-ddhh:mm:ss"); while (iterator.hasNext()) { JSONObject challenge = iterator.next(); //identify active challenge with status if (challenge.get("Status__c").equals(PSContants.STATUS_CREATED)) { activeChallenges.add(challenge); } else { String endDateStr = ((String) challenge.get("End_Date__c")).replace("T", ""); Date date = new Date(); try { date = dateFormat.parse(endDateStr); } catch (ParseException pe) { logger.log(Level.SEVERE, "Error occurent while parsing date " + endDateStr); } pastChallengesByDate.put(date.getTime(), challenge); } } //from the sorted map extract the recent challenge int pastChallengeSize = pastChallengesByDate.size(); if (pastChallengeSize > 0) { Object[] challengeArr = (Object[]) pastChallengesByDate.values().toArray(); int startIndex = pastChallengeSize > 3 ? pastChallengeSize - 3 : 0; for (int i = startIndex; i < pastChallengeSize; i++) { pastChallenges.add(challengeArr[i]); } } JSONObject resultChallenges = new JSONObject(); resultChallenges.put("activeChallenges", activeChallenges); resultChallenges.put("pastChallenges", pastChallenges); resultChallenges.put("totalChallenges", challenges.size()); return resultChallenges; }
From source file:com.twosigma.beaker.core.rest.UtilRest.java
private static Set<String> mergeListSetting(String settingsListName, JSONObject configs, JSONObject prefs) { Set<String> settings = new LinkedHashSet<>(); Set<String> settingsToRemove = new HashSet<>(); { // settings from config JSONArray s = (JSONArray) configs.get(settingsListName); if (s != null) { @SuppressWarnings("unchecked") Iterator<String> iterator = s.iterator(); while (iterator.hasNext()) { settings.add(iterator.next()); }/*from w ww.j a va 2 s. c o m*/ } } { // settings from preference JSONArray s = (JSONArray) prefs.get(settingsListName); if (s != null) { @SuppressWarnings("unchecked") Iterator<String> iterator = s.iterator(); while (iterator.hasNext()) { settings.add(iterator.next()); } } } { // to-remove settings from preference JSONArray s = (JSONArray) prefs.get(TO_REMOVE_PREFIX + settingsListName); if (s != null) { @SuppressWarnings("unchecked") Iterator<String> iterator = s.iterator(); while (iterator.hasNext()) { settingsToRemove.add(iterator.next()); } } } settings.removeAll(settingsToRemove); return settings; }
From source file:com.github.lgi2p.obirs.utils.JSONConverter.java
/** * {"log": "", "annotations" : [{ "text": "uranium", "startpos": 723, * "endpos":730, "uris":["http://www.cea.fr/ontotoxnuc#Uranium"] },{ "text": * "protein", "startpos": 1837, "endpos":1845, * "uris":["http://www.cea.fr/ontotoxnuc#Proteine"] },{ "text": "plant", * "startpos": 4661, "endpos":4666,// www. j a v a 2 s . c o m * "uris":["http://www.cea.fr/ontotoxnuc#Plante"] }]} * * @param jsonQuery * @return * @throws ParseException * @throws Exception */ protected static String toJSONindexFormat(int id, String title, String content, String href) throws ParseException, Exception { URIFactory f = URIFactoryMemory.getSingleton(); content = content.replace("\n", "").replace("\r", ""); Object obj = new JSONParser().parse(content); JSONObject jsonObject = (JSONObject) obj; JSONArray annotations = (JSONArray) jsonObject.get("annotations"); Set<URI> concepts = new HashSet<URI>(); if (annotations != null) { Iterator<JSONObject> iterator = annotations.iterator(); while (iterator.hasNext()) { JSONObject concept = iterator.next(); JSONArray uris = (JSONArray) concept.get("uris"); for (int i = 0; i < uris.size(); i++) { concepts.add(f.getURI((String) uris.get(i))); } } } String urisAsString = ""; for (URI u : concepts) { if (!urisAsString.isEmpty()) { urisAsString += ","; } urisAsString += "\"" + u.stringValue() + "\""; } return "{\"id\":\"" + id + "\",\"title\":\"" + title + "\",\"conceptIds\":[" + urisAsString + "],\"href\":\"" + href + "\"}"; }
From source file:FactFind.PersonalDetails.java
public static boolean CustomerPersonalDetails() { int MaxCustomerreached = 0; JSONArray CustomerInformation_Array = (JSONArray) TestExecution.JSONTestData.get("Customerinformation"); Iterator<JSONObject> CustomerInformationArray = CustomerInformation_Array.iterator(); String FirstCustomerFlag = "Yes"; try {/*w ww . ja va 2s . co m*/ WebDriverWait wait = new WebDriverWait(driver, 30); wait.until(ExpectedConditions.elementToBeClickable(NextButtonTopofthePage)); while (CustomerInformationArray.hasNext()) { if (MaxCustomerreached >= 2) { break; } JSONObject CustomerInformation = CustomerInformationArray.next(); if ((FirstCustomerFlag.equals("Yes") || CustomerInformation.get("IsApplicant").equals("Yes")) && CustomerInformation.get("CustomerType").equals("Individual")) { if (FirstCustomerFlag.equals("Yes")) { Applicant1.click(); Thread.sleep(3000); MaxCustomerreached++; } else if (CustomerInformation.get("IsApplicant").equals("Yes")) { Applicant2.click(); Thread.sleep(3000); MaxCustomerreached++; } if (JSON.GetTestData(CustomerInformation, "CustomerNames").get("Title") != null && Integer.parseInt(JSON.GetTestData(CustomerInformation, "CustomerNames").get("Title") .toString()) >= 1) { Title.click(); Helper.Keystrokeup(9); Helper.Keystrokedown(Integer.parseInt( JSON.GetTestData(CustomerInformation, "CustomerNames").get("Title").toString())); } if (JSON.GetTestData(CustomerInformation, "CustomerNames").get("MiddleName") != null) { MiddleName.click(); MiddleName.clear(); MiddleName.sendKeys(JSON.GetTestData(CustomerInformation, "CustomerNames").get("MiddleName") .toString()); } if (CustomerInformation.get("Gender") != null) { if (CustomerInformation.get("Gender").equals("Male") || CustomerInformation.get("Gender").equals("Female")) { Gender.click(); Gender.sendKeys(CustomerInformation.get("Gender").toString()); Helper.Keystrokeenter(1); } else { Gender.click(); Gender.sendKeys("Unspecified"); Helper.Keystrokeenter(1); } } if (CustomerInformation.get("DOB") != null) { if (FirstCustomerFlag.equals("Yes")) { DateOfbirth.click(); DateOfbirth.clear(); DateOfbirth.sendKeys(CustomerInformation.get("DOB").toString()); } else if (CustomerInformation.get("IsApplicant").equals("Yes")) { DateOfbirthSpouse.click(); DateOfbirthSpouse.clear(); DateOfbirthSpouse.sendKeys(CustomerInformation.get("DOB").toString()); } } if (CustomerInformation.get("ResidentialStatus") != null && Integer.parseInt(CustomerInformation.get("ResidentialStatus").toString()) >= 1) { if (Integer.parseInt(CustomerInformation.get("ResidentialStatus").toString()) == 1 || Integer.parseInt(CustomerInformation.get("ResidentialStatus").toString()) == 2 || Integer.parseInt(CustomerInformation.get("ResidentialStatus").toString()) == 3) { ResidencyStatus.click(); Helper.Keystrokeup(3); Helper.Keystrokedown(2); Helper.Keystrokeenter(1); } else if (Integer.parseInt(CustomerInformation.get("ResidentialStatus").toString()) == 4) { ResidencyStatus.click(); Helper.Keystrokeup(3); Helper.Keystrokedown(1); Helper.Keystrokeenter(1); } else if (Integer.parseInt(CustomerInformation.get("ResidentialStatus").toString()) == 5) { ResidencyStatus.click(); Helper.Keystrokeup(3); Helper.Keystrokedown(3); Helper.Keystrokeenter(1); } } if (JSON.GetTestData(CustomerInformation, "CustomerContactDetails").get("Mobile") != null) { Mobile.click(); Mobile.clear(); Mobile.sendKeys(JSON.GetTestData(CustomerInformation, "CustomerContactDetails") .get("Mobile").toString()); } if (JSON.GetTestData(CustomerInformation, "CustomerContactDetails").get("HomePhone") != null) { HomePhone.click(); HomePhone.clear(); HomePhone.sendKeys(JSON.GetTestData(CustomerInformation, "CustomerContactDetails") .get("HomePhone").toString()); } if (JSON.GetTestData(CustomerInformation, "CustomerContactDetails") .get("BusinessPhone") != null) { BusinessPhone.click(); BusinessPhone.clear(); BusinessPhone.sendKeys(JSON.GetTestData(CustomerInformation, "CustomerContactDetails") .get("BusinessPhone").toString()); } JSONObject FactFind = JSON.GetTestData(CustomerInformation, "FactFind"); if (JSON.GetTestData(FactFind, "DriversLicense").get("DriversLicenceNumber") != null) { DriversLicenceNumber.click(); DriversLicenceNumber.clear(); DriversLicenceNumber.sendKeys(JSON.GetTestData(FactFind, "DriversLicense") .get("DriversLicenceNumber").toString()); } if (JSON.GetTestData(FactFind, "DriversLicense").get("LicenseState") != null) { LicenceState.click(); LicenceState.sendKeys( JSON.GetTestData(FactFind, "DriversLicense").get("LicenseState").toString()); Helper.Keystrokeenter(1); } if (JSON.GetTestData(FactFind, "DriversLicense").get("LicenceIssued") != null) { if (FirstCustomerFlag.equals("Yes")) { LicenceIssued.click(); LicenceIssued.clear(); LicenceIssued.sendKeys( JSON.GetTestData(FactFind, "DriversLicense").get("LicenceIssued").toString()); } else if (CustomerInformation.get("IsApplicant").equals("Yes")) { LicenceIssuedSpouse.click(); LicenceIssuedSpouse.clear(); LicenceIssuedSpouse.sendKeys( JSON.GetTestData(FactFind, "DriversLicense").get("LicenceIssued").toString()); } } if (JSON.GetTestData(FactFind, "DriversLicense").get("LicenceExpires") != null) { if (FirstCustomerFlag.equals("Yes")) { LicenceExpiry.click(); LicenceExpiry.clear(); LicenceExpiry.sendKeys( JSON.GetTestData(FactFind, "DriversLicense").get("LicenceExpires").toString()); } else if (CustomerInformation.get("IsApplicant").equals("Yes")) { LicenceExpirySpouse.click(); LicenceExpirySpouse.clear(); LicenceExpirySpouse.sendKeys( JSON.GetTestData(FactFind, "DriversLicense").get("LicenceExpires").toString()); } } Thread.sleep(3000); if (JSON.GetTestData(CustomerInformation, "CustomerDependents") .get("NumberOfDependents") != null) { JSONArray DependantDOBArray = (JSONArray) JSON .GetTestData(CustomerInformation, "CustomerDependents").get("DependentsDOB"); Iterator<String> DOBArray = DependantDOBArray.iterator(); while (DOBArray.hasNext()) { Helper.ScroolToView(driver, AddDependant); AddDependant.click(); Thread.sleep(2000); AgeofDependant.sendKeys(CalculateAge(DOBArray.next().toString())); Helper.ScroolToView(driver, SaveDependent); SaveDependent.click(); } } FirstCustomerFlag = "No"; } } Applicant1.click(); Thread.sleep(5000); Helper.ScroolToView(driver, SaveMyDetails); SaveMyDetails.click(); Thread.sleep(5000); Helper.ScroolToView(driver, NextButtonBottomofthePage); NextButtonBottomofthePage.click(); Helper.ScreenDump(TestExecution.TestExecutionFolder, "FactFindPersonalDetails"); logger.info("FactFind Customer personal details entered successfully"); return true; } catch (InterruptedException e) { e.printStackTrace(); logger.error(e.toString()); Helper.ScreenDump(TestExecution.TestExecutionFolder, "Error"); return false; } }
From source file:com.aerospike.load.Parser.java
/** * Process column definitions in JSON formated file and create two lists for metadata and bindata and one list for metadataLoader * @param file Config file name/* w w w .j a v a 2 s.c o m*/ * @param metadataLoader Map of metadata for loader to use, given in config file * @param metadataColumnDefs List of column definitions for metadata of bins like key,set * @param binColumnDefs List of column definitions for bins * @param params User given parameters * @throws ParseException * @throws IOException */ public static boolean processJSONColumnDefinitions(File file, HashMap<String, String> metadataConfigs, List<ColumnDefinition> metadataColumnDefs, List<ColumnDefinition> binColumnDefs, Parameters params) { boolean processConfig = false; if (params.verbose) { log.setLevel(Level.DEBUG); } try { // Create parser object JSONParser jsonParser = new JSONParser(); // Read the json config file Object obj; obj = jsonParser.parse(new FileReader(file)); JSONObject jobj; // Check config file contains metadata for datafile if (obj == null) { log.error("Empty config File"); return processConfig; } else { jobj = (JSONObject) obj; log.debug("Config file contents:" + jobj.toJSONString()); } // Get meta data of loader // Search for input_type if ((obj = getJsonObject(jobj, Constants.VERSION)) != null) { metadataConfigs.put(Constants.VERSION, obj.toString()); } else { log.error("\"" + Constants.VERSION + "\" Key is missing in config file"); return processConfig; } if ((obj = getJsonObject(jobj, Constants.INPUT_TYPE)) != null) { // Found input_type, check for csv if (obj instanceof String && obj.toString().equals(Constants.CSV_FILE)) { // Found csv format metadataConfigs.put(Constants.INPUT_TYPE, obj.toString()); // Search for csv_style if ((obj = getJsonObject(jobj, Constants.CSV_STYLE)) != null) { // Found csv_style JSONObject cobj = (JSONObject) obj; // Number_Of_Columns in data file if ((obj = getJsonObject(cobj, Constants.COLUMNS)) != null) { metadataConfigs.put(Constants.COLUMNS, obj.toString()); } else { log.error("\"" + Constants.COLUMNS + "\" Key is missing in config file"); return processConfig; } // Delimiter for parsing data file if ((obj = getJsonObject(cobj, Constants.DELIMITER)) != null) metadataConfigs.put(Constants.DELIMITER, obj.toString()); // Skip first row of data file if it contains column names if ((obj = getJsonObject(cobj, Constants.IGNORE_FIRST_LINE)) != null) metadataConfigs.put(Constants.IGNORE_FIRST_LINE, obj.toString()); } else { log.error("\"" + Constants.CSV_STYLE + "\" Key is missing in config file"); return processConfig; } } else { log.error("\"" + obj.toString() + "\" file format is not supported in config file"); return processConfig; } } else { log.error("\"" + Constants.INPUT_TYPE + "\" Key is missing in config file"); return processConfig; } // Get metadata of records // Get key definition of records if ((obj = getJsonObject(jobj, Constants.KEY)) != null) { metadataColumnDefs.add(getColumnDefs((JSONObject) obj, Constants.KEY)); } else { log.error("\"" + Constants.KEY + "\" Key is missing in config file"); return processConfig; } // Get set definition of records. Optional because we can get "set" name from user. if ((obj = getJsonObject(jobj, Constants.SET)) != null) { if (obj instanceof String) { metadataColumnDefs.add(new ColumnDefinition(Constants.SET, obj.toString(), true, true, "string", "string", null, -1, -1, null, null)); } else { metadataColumnDefs.add(getColumnDefs((JSONObject) obj, Constants.SET)); } } // Get bin column definitions JSONArray binList; if ((obj = getJsonObject(jobj, Constants.BINLIST)) != null) { // iterator for bins binList = (JSONArray) obj; Iterator<?> i = binList.iterator(); // take each bin from the JSON array separately while (i.hasNext()) { JSONObject binObj = (JSONObject) i.next(); binColumnDefs.add(getColumnDefs(binObj, Constants.BINLIST)); } } else { return processConfig; } log.info(String.format("Number of columns: %d(metadata) + %d(bins)", (metadataColumnDefs.size()), binColumnDefs.size())); processConfig = true; } catch (IOException ie) { log.error("File:" + Utils.getFileName(file.getName()) + " Config i/o Error: " + ie.toString()); if (log.isDebugEnabled()) { ie.printStackTrace(); } } catch (ParseException pe) { log.error("File:" + Utils.getFileName(file.getName()) + " Config parsing Error: " + pe.toString()); if (log.isDebugEnabled()) { pe.printStackTrace(); } } catch (Exception e) { log.error("File:" + Utils.getFileName(file.getName()) + " Config unknown Error: " + e.toString()); if (log.isDebugEnabled()) { e.printStackTrace(); } } return processConfig; }
From source file:luceneindexdemo.LuceneIndexDemo.java
public static void searchIndex(String s) throws IOException, ParseException, SQLException, FileNotFoundException, org.json.simple.parser.ParseException { Directory directory = FSDirectory.getDirectory(INDEX_DIRECTORY); IndexReader reader = IndexReader.open(directory); IndexSearcher search = new IndexSearcher(reader); Analyzer analyzer = new StandardAnalyzer(); QueryParser queryparser = new QueryParser(FIELD_CONTENTS, analyzer); Query query = queryparser.parse(s); Hits hits = search.search(query);//from ww w. jav a 2s . c o m Iterator<Hit> it = hits.iterator(); //System.out.println("hits:"+hits.length()); float f_score; List<String> names = new ArrayList<>(); while (it.hasNext()) { Hit hit = it.next(); f_score = hit.getScore(); //System.out.println(f_score); Document document = hit.getDocument(); Field f = document.getField(FIELD_PATH); //System.out.println(f.readerValue()); //System.out.println(document.getValues(FIELD_PATH)); String path = document.get(FIELD_PATH); System.out.println(document.getValues(path)); Field con = document.getField(FIELD_PATH); //System.out.println("hit:"+path+" "+hit.getId()+" "+con); names.add(new File(path).getName()); } //ProcessBuilder pb=new ProcessBuilder(); FileReader fReader = new FileReader("/home/rishav12/NetBeansProjects/LuceneIndexDemo/inntell.json"); JSONParser jsParser = new JSONParser(); //System.out.println("This is an assumption that you belong to US"); FileReader freReader = new FileReader("/home/rishav12/NetBeansProjects/LuceneIndexDemo/location.json"); Connection con = DriverManager.getConnection("jdbc:neo4j://localhost:7474/"); System.out.println(names); if (names.get(0).equals("miss")) { System.out.println(s); StringTokenizer stringTokenizer = new StringTokenizer(s); Connection con1 = DriverManager.getConnection("jdbc:neo4j://localhost:7474/"); String querySearch = "match ()-[r:KNOWS]-() where has(r.relType) return distinct r.relType"; ResultSet rSet = con.createStatement().executeQuery(querySearch); List<String> allRels = new ArrayList<>(); while (rSet.next()) { System.out.println(); allRels.add(rSet.getString("r.relType")); } //System.out.println(rSet); while (stringTokenizer.hasMoreTokens()) { String next = stringTokenizer.nextToken(); if (allRels.contains(next)) { missOperation(next); } //System.out.println(resSet.getString("r.relType")); } System.out.println(names.get(1)); //missOperation(names.get(1)); } else { try { JSONObject jsonObj = (JSONObject) jsParser.parse(fReader); System.out.println(names.get(0)); JSONObject jsObj = (JSONObject) jsonObj.get(names.get(0)); JSONObject results = new JSONObject(); System.out.println(jsObj.get("explaination")); results.put("explaination", jsObj.get("explaination")); JSONArray reqmts = (JSONArray) jsObj.get("true"); System.out.println("Let me look out for the places that contains "); List<String> lis = new ArrayList<>(); JSONObject locObj = (JSONObject) jsParser.parse(freReader); JSONArray jsArray = (JSONArray) locObj.get("CHENNAI"); Iterator<JSONArray> ite = reqmts.iterator(); int k = 0; String resQuery = "START n=node:restaurant('withinDistance:[" + jsArray.get(0) + "," + jsArray.get(1) + ",7.5]') where"; Iterator<JSONArray> ite1 = reqmts.iterator(); while (ite1.hasNext()) System.out.println(ite1.next()); while (ite.hasNext()) { lis.add("n.type=" + "'" + ite.next() + "'"); if (k == 0) resQuery += " " + lis.get(k); else resQuery += " or " + lis.get(k); //System.out.println(attrib); k++; } resQuery += " return n.name,n.place,n.type"; File writeTo = new File( "/home/rishav12/NetBeansProjects/LuceneIndexDemo/filestoIndex1/" + names.get(0)); FileOutputStream fop = new FileOutputStream(writeTo, true); String writeTOFile = s + "\n"; fop.write(writeTOFile.getBytes()); //System.out.println(resQuery); ResultSet res = con.createStatement().executeQuery(resQuery); JSONArray resSet = new JSONArray(); while (res.next()) { System.out.println(" name:" + res.getString("n.name") + " located:" + res.getString("n.place") + " type:" + res.getString("n.type")); JSONObject jsPart = new JSONObject(); jsPart.put("name", res.getString("n.name")); jsPart.put("located", res.getString("n.place")); jsPart.put("type", res.getString("n.type")); resSet.add(jsPart); } results.put("results", resSet); File resultFile = new File("result.json"); FileOutputStream fop1 = new FileOutputStream(resultFile); System.out.println(results); fop1.write(results.toJSONString().getBytes()); //String resQuery="START n=node:restaurant('withinDistance:[40.7305991, -73.9865812,10.0]') where n.coffee=true return n.name,n.address;"; //System.out.println("Sir these results are for some coffee shops nearby NEW YORK"); //ResultSet res=con.createStatement().executeQuery(resQuery); //while(res.next()) //System.out.println("name: "+res.getString("n.name")+" address: "+res.getString("n.address")); } catch (org.json.simple.parser.ParseException ex) { Logger.getLogger(LuceneIndexDemo.class.getName()).log(Level.SEVERE, null, ex); } } }
From source file:com.worldline.easycukes.commons.helpers.JSONHelper.java
/** * Returns a particular property from a JSONArray * * @param jsonArray JSONArray you want to parse * @param simpleProp property you're searching for * @return An Object matching the required property *///from w w w.j a v a2 s . c om private static Object getProperty(@NonNull JSONArray jsonArray, @NonNull String simpleProp) { if (simpleProp.startsWith("[")) { final int idx2 = simpleProp.indexOf("]"); if (idx2 > 0) { final String exp = simpleProp.substring(1, idx2); if (exp.contains("=")) { final String[] expParams = exp.split("="); for (final Iterator<JSONObject> iterator = jsonArray.iterator(); iterator.hasNext();) { final JSONObject jsonObject = iterator.next(); if (getValue(jsonObject, expParams[0]).equals(expParams[1])) return jsonObject; } } else if (StringUtils.isNumeric(exp) && jsonArray.size() > Integer.parseInt(exp)) return jsonArray.get(Integer.parseInt(exp)); } } return null; }