private void parseFile(File file, List<Artifact> artifacts, List<HostConfig> hostConfigs) { try { JSONParser parser = new JSONParser(); JSONObject jsonObject = (JSONObject) parser.parse(new FileReader(file)); if (jsonObject.containsKey(JSON_TAG_ARTIFACTS)) { JSONArray jsonArray = (JSONArray) jsonObject.get(JSON_TAG_ARTIFACTS); Iterator<JSONObject> iterator = jsonArray.iterator(); while (iterator.hasNext()) { artifacts.add(new Artifact(iterator.next())); } } if (jsonObject.containsKey(JSON_TAG_HOST_CONFIGS)) { JSONArray jsonArray = (JSONArray) jsonObject.get(JSON_TAG_HOST_CONFIGS); Iterator<JSONObject> iterator = jsonArray.iterator(); while (iterator.hasNext()) { hostConfigs.add(new HostConfig(iterator.next())); } } } catch (IOException e) { throw new RuntimeException( MessageFormat.format( Main.bundle.getString("cli.error.cannot_read_file"), file.getAbsolutePath())); } catch (ParseException e) { throw new RuntimeException( MessageFormat.format(Main.bundle.getString("error.json.parse"), file.getAbsolutePath())); } }
public List<String> assemblePybossaTaskPublishForm(String inputData, ClientApp clientApp) throws Exception { List<String> outputFormatData = new ArrayList<String>(); JSONParser parser = new JSONParser(); Object obj = parser.parse(inputData); JSONArray jsonObject = (JSONArray) obj; Iterator itr = jsonObject.iterator(); while (itr.hasNext()) { JSONObject featureJsonObj = (JSONObject) itr.next(); JSONObject info = assemblePybossaInfoFormat(featureJsonObj, parser, clientApp); JSONObject tasks = new JSONObject(); tasks.put("info", info); tasks.put("n_answers", clientApp.getTaskRunsPerTask()); tasks.put("quorum", clientApp.getQuorum()); tasks.put("calibration", new Integer(0)); tasks.put("app_id", clientApp.getPlatformAppID()); tasks.put("priority_0", new Integer(0)); outputFormatData.add(tasks.toJSONString()); // System.out.println(featureJsonObj.toString()); } return outputFormatData; }
public static Crossword parseJsonCrossword(InputStreamReader reader) throws IOException, ParseException { Crossword cInfo = null; List<Word> wordList = new ArrayList<Word>(); JSONParser jsonParser = new JSONParser(); JSONObject jsonObject = (JSONObject) jsonParser.parse(reader); JSONObject crossword = (JSONObject) jsonObject.get("crossword"); JSONArray wordsJSON = (JSONArray) jsonObject.get("words"); Iterator i = wordsJSON.iterator(); while (i.hasNext()) { JSONArray innerObj = (JSONArray) i.next(); Word tempWord = new Word( (Long) innerObj.get(0), (Long) innerObj.get(1), (Long) innerObj.get(2), (String) innerObj.get(3), (String) innerObj.get(4)); wordList.add(tempWord); } Crossword info = new Crossword( (Long) crossword.get("width"), (Long) crossword.get("height"), (String) crossword.get("language"), (String) crossword.get("encoding"), (String) crossword.get("source"), wordList); cInfo = info; return cInfo; }
public int[] parser(String json) { int[] data = null; JSONParser parser = new JSONParser(); try { JSONArray jsow = (JSONArray) parser.parse(json); // JSONArray jsow = (JSONArray)job; Iterator<String> it = jsow.iterator(); data = new int[jsow.size()]; int i = 0; // System.out.println("jsow: "+jsow); while (it.hasNext()) { String tg = it.next(); if (tg.contains(":")) { String[] arrtg = tg.split(":"); data[i] = Integer.parseInt(arrtg[0]) * 3600 + Integer.parseInt(arrtg[1]) * 60; } else { // System.out.println("weight"); data[i] = Integer.parseInt(tg); } // System.out.println(data[i]); i++; } } catch (Exception e) { System.err.println("parse1: " + e.toString()); } return data; }
public static void newSensorData(String deviceName, String data) { Device found = null; for (Device device : Kernel.getInstance().getDevices()) { if (device.getName().equals(deviceName)) { found = device; } } if (found == null) { return; } JSONObject jsonObject = (JSONObject) JSONValue.parse(data); if (jsonObject == null || jsonObject.keySet() == null || jsonObject.keySet().iterator() == null) { // System.out.println("Erro json " + data); return; } JSONArray components = (JSONArray) jsonObject.get("components"); Iterator i = components.iterator(); while (i.hasNext()) { Object oo = i.next(); JSONObject joo = (JSONObject) oo; String thing = joo.get("name").toString(); String value = joo.get("value").toString(); found.getThings().get(thing).setLastValue(value); } }
@Override public void run() { try { ConcurrentLog.info("SMWLISTSYNC", "Importer run()"); Object obj = this.parser.parse(this.importFile); JSONObject jsonObject = (JSONObject) obj; JSONArray items = (JSONArray) jsonObject.get("items"); @SuppressWarnings("unchecked") Iterator<JSONObject> iterator = items.iterator(); while (iterator.hasNext()) { this.parseItem(iterator.next()); } } catch (final IOException e) { ConcurrentLog.logException(e); } catch (final ParseException e) { ConcurrentLog.logException(e); } finally { try { ConcurrentLog.info("SMWLISTSYNC", "Importer inserted poison pill in queue"); this.listEntries.put(SMWListRow.POISON); } catch (final InterruptedException e) { ConcurrentLog.logException(e); } } }
public void read_jsonFile(String fileName) { JSONParser parser = new JSONParser(); try { Object obj = parser.parse(new FileReader(fileName)); JSONObject jsonObject = (JSONObject) obj; String id = (String) jsonObject.get("Id"); String author = (String) jsonObject.get("Author"); JSONArray companyList = (JSONArray) jsonObject.get("Company List"); System.out.println("Name: " + id); System.out.println("Author: " + author); System.out.println("\nCompany List:"); Iterator<String> iterator = companyList.iterator(); while (iterator.hasNext()) { System.out.println(iterator.next()); } } catch (Exception e) { e.printStackTrace(); } }
public List<String> assemblePybossaTaskPublishFormWithIndex( String inputData, ClientApp clientApp, int indexStart, int indexEnd) throws Exception { List<String> outputFormatData = new ArrayList<String>(); JSONParser parser = new JSONParser(); Object obj = parser.parse(inputData); JSONArray jsonObject = (JSONArray) obj; Iterator itr = jsonObject.iterator(); for (int i = indexStart; i < indexEnd; i++) { JSONObject featureJsonObj = (JSONObject) jsonObject.get(i); JSONObject info = assemblePybossaInfoFormat(featureJsonObj, parser, clientApp); JSONObject tasks = new JSONObject(); tasks.put("info", info); tasks.put("n_answers", clientApp.getTaskRunsPerTask()); tasks.put("quorum", clientApp.getQuorum()); tasks.put("calibration", new Integer(0)); tasks.put("app_id", clientApp.getPlatformAppID()); tasks.put("priority_0", new Integer(0)); outputFormatData.add(tasks.toJSONString()); } return outputFormatData; }
public void doit() { try { filebw = new BufferedWriter( new OutputStreamWriter( new FileOutputStream( "C:\\Users\\sangha\\Dropbox\\KAIST\\진행중인 연구\\SentenceRDF\\data\\Wiki_training_set.txt"), "UTF8")); // "C:\\Users\\sangha\\Dropbox\\KAIST\\진행중인 연구\\SentenceRDF\\data\\Wiki_training_set.txt" // "D:\\KAIST\\Dropbox\\KAIST\\진행중인 // 연구\\SentenceRDF\\data\\relation\\NLQ_relation_training.txt" FileReader reader = new FileReader( "C:\\Users\\sangha\\Dropbox\\KAIST\\진행중인 연구\\SentenceRDF\\data\\Wiki_ETRI_training_set.json"); // "D:\\KAIST\\Dropbox\\KAIST\\진행중인 연구\\SentenceRDF\\data\\Wiki_ETRI_training_set.json" // "C:\\Users\\sangha\\Dropbox\\KAIST\\진행중인 // 연구\\SentenceRDF\\data\\Wiki_ETRI_training_set.json" JSONParser jsonParser = new JSONParser(); JSONObject jsonObject = (JSONObject) jsonParser.parse(reader); JSONArray jsonTraining = (JSONArray) jsonObject.get("training"); Iterator<?> t = jsonTraining.iterator(); while (t.hasNext()) { JSONObject sentence = (JSONObject) t.next(); JSONArray jsonSentence = (JSONArray) sentence.get("sentence"); Iterator<?> s = jsonSentence.iterator(); JSONObject text = (JSONObject) s.next(); JSONObject morp = (JSONObject) s.next(); filebw.write(text.toString().substring(9, text.toString().length() - 2) + "\n"); } filebw.close(); } catch (Exception e) { e.printStackTrace(); } }
public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { // read the last post id here ....................... String url = req.getRequestURI(); String urlprt[] = url.split("/"); int urlcount = urlprt.length - 1; JSONParser parserPost = new JSONParser(); JSONObject post = null; String id = urlprt[urlcount]; // read the post here ............................. try { if (id != null) { Object objPost = parserPost.parse(new FileReader("..\\webapps\\Blog\\post\\" + id + ".json")); post = (JSONObject) objPost; String postauthor = post.get("author").toString(); String posttitle = post.get("title").toString(); String postcontent = post.get("content").toString(); JSONArray arr = (JSONArray) post.get("comments"); List<String> list = new ArrayList<String>(); Iterator<String> iterator = arr.iterator(); while (iterator.hasNext()) { list.add(iterator.next()); } int listsz = list.size(); String[] comments = new String[listsz]; for (int i = 0; i < listsz; i++) { comments[i] = list.get(i); } req.setAttribute("title", posttitle); req.setAttribute("content", postcontent); req.setAttribute("author", postauthor); req.setAttribute("comments", comments); req.setAttribute("id", id); req.getRequestDispatcher("/view.jsp").forward(req, res); } } catch (Exception e) { res.setContentType("text/html"); PrintWriter out = res.getWriter(); out.println("get POST ......................"); out.println(e); out.println("......................"); } }
public String getAnswerResponse( ClientApp clientApp, String pybossaResult, JSONParser parser, ClientAppAnswer clientAppAnswer, Long taskQueueID) throws Exception { JSONObject responseJSON = new JSONObject(); String[] questions = getQuestion(clientAppAnswer, parser); int[] responses = new int[questions.length]; int translationResponses = 0; JSONArray array = (JSONArray) parser.parse(pybossaResult); Iterator itr = array.iterator(); String answer = null; int cutoffSize = getCutOffNumber(array.size(), clientApp.getTaskRunsPerTask(), clientAppAnswer); System.out.print("getAnswerResponse - cutoffSize :" + cutoffSize); while (itr.hasNext()) { JSONObject featureJsonObj = (JSONObject) itr.next(); JSONObject info = (JSONObject) featureJsonObj.get("info"); answer = this.getUserAnswer(featureJsonObj, clientApp); System.out.print("getAnswerResponse - answer :" + answer); translationResponses = 0; for (int i = 0; i < questions.length; i++) { if (questions[i].trim().equalsIgnoreCase(answer.trim())) { responses[i] = responses[i] + 1; } else { if (answer.equalsIgnoreCase(ANSWER_NOT_ENGLISH)) { translationResponses++; } } } if (answer.equalsIgnoreCase(ANSWER_NOT_ENGLISH)) { System.out.println("translationResponses: " + translationResponses); handleTranslationItem( taskQueueID, translationResponses, answer, info, clientAppAnswer, cutoffSize); } } String finalAnswer = null; for (int i = 0; i < questions.length; i++) { if (responses[i] >= cutoffSize) { finalAnswer = questions[i]; } } return finalAnswer; }
public Long getAppID(String jsonApp, JSONParser parser) throws Exception { Long appID = null; JSONArray array = (JSONArray) parser.parse(jsonApp); Iterator itr = array.iterator(); while (itr.hasNext()) { JSONObject featureJsonObj = (JSONObject) itr.next(); appID = (Long) featureJsonObj.get("id"); } return appID; }
public Long getDocumentID(String jsonApp, JSONParser parser) throws Exception { Long documentID = null; JSONArray array = (JSONArray) parser.parse(jsonApp); Iterator itr = array.iterator(); while (itr.hasNext()) { JSONObject featureJsonObj = (JSONObject) itr.next(); JSONObject info = (JSONObject) featureJsonObj.get("info"); documentID = (Long) info.get("documentID"); } return documentID; }
@Override public void populateData() { JSONArray jsonObject = null; try { jsonObject = (JSONArray) new JSONParser().parse(siteAdapter.select(null)); } catch (IOException e) { e.printStackTrace(); } catch (ParseException e) { e.printStackTrace(); } catalogList.clear(); Iterator<JSONObject> iterator = jsonObject.iterator(); while (iterator.hasNext()) { JSONObject o = iterator.next(); catalogList.add(new Site((int) (long) o.get("siteId"), (String) o.get("name"))); } }
public List<String> harvest() { String size = "5000"; // max size we can get. String params = "?q=*&size=" + size + "from=0"; List<String> records = null; HttpURLConnection urlConn = null; String json = null; boolean loop = true; int count = 0; String request = istexApiUrl + "/" + params; while (loop) { records = new ArrayList<String>(); try { URL url = new URL(request); logger.info(request); urlConn = (HttpURLConnection) url.openConnection(); if (urlConn != null) { urlConn.setDoInput(true); urlConn.setRequestMethod("GET"); InputStream in = urlConn.getInputStream(); json = Utilities.convertStreamToString(in); JSONParser jsonParser = new JSONParser(); JSONObject jsonObject = (JSONObject) jsonParser.parse(json); JSONArray hits = (JSONArray) jsonObject.get("hits"); request = (String) jsonObject.get("nextPageURI"); Iterator i = hits.iterator(); while (i.hasNext()) { JSONObject hit = (JSONObject) i.next(); records.add((String) hit.get("id")); } processRecords(records); if (request == null) { loop = false; } } } catch (Exception e) { e.printStackTrace(); } } logger.info(" count :" + count); return records; }
@Override public List<Country> getShipToCountryList(MerchantStore store, Language language) throws ServiceException { ShippingConfiguration shippingConfiguration = getShippingConfiguration(store); ShippingType shippingType = ShippingType.INTERNATIONAL; List<String> supportedCountries = new ArrayList<String>(); if (shippingConfiguration == null) { shippingConfiguration = new ShippingConfiguration(); } if (shippingConfiguration.getShippingType() != null) { shippingType = shippingConfiguration.getShippingType(); } if (shippingType.name().equals(ShippingType.NATIONAL.name())) { supportedCountries.add(store.getCountry().getIsoCode()); } else { MerchantConfiguration configuration = merchantConfigurationService.getMerchantConfiguration(SUPPORTED_COUNTRIES, store); if (configuration != null) { String countries = configuration.getValue(); if (!StringUtils.isBlank(countries)) { Object objRegions = JSONValue.parse(countries); JSONArray arrayRegions = (JSONArray) objRegions; @SuppressWarnings("rawtypes") Iterator i = arrayRegions.iterator(); while (i.hasNext()) { supportedCountries.add((String) i.next()); } } } } return countryService.getCountries(supportedCountries, language); }
public String[] parser(String json, boolean x) { String[] data = null; JSONParser parser = new JSONParser(); try { JSONArray jsow = (JSONArray) parser.parse(json); // JSONArray jsow = (JSONArray)job; Iterator<JSONObject> it = jsow.iterator(); data = new String[jsow.size()]; int i = 0; // System.out.println("jsow: "+jsow); while (it.hasNext()) { JSONObject jnxt = it.next(); data[i] = jnxt.toString(); i++; } } catch (Exception e) { System.err.println("parse2: " + e.toString()); } return data; }
@Override public boolean compare(JSONObject jsonObject, OWLClass owlClass, OWLOntology owlOntology) { Set<OWLClass> allClassesInAxiomsRelated = new HashSet<OWLClass>(); JSONArray jsonAnnotationsArray = (JSONArray) jsonObject.get("annotations"); Set<OWLAxiom> owlAxiomSet = owlClass.getReferencingAxioms(owlOntology); Iterator<OWLAxiom> owlAxiomSetIterator = owlAxiomSet.iterator(); while (owlAxiomSetIterator.hasNext()) { OWLAxiom owlAxiom = owlAxiomSetIterator.next(); Set<OWLClass> owlClassesInAxiom = owlAxiom.getClassesInSignature(); allClassesInAxiomsRelated.addAll(owlClassesInAxiom); } Set<String> owlClassesIds = new HashSet<String>(); Iterator<OWLClass> allClassesInAxiomsRelatedIterator = allClassesInAxiomsRelated.iterator(); while (allClassesInAxiomsRelatedIterator.hasNext()) { OWLClass currentClass = allClassesInAxiomsRelatedIterator.next(); owlClassesIds.add( OwlDataExtrators.getAttribute("id", currentClass, owlOntology).replace(":", "_")); } Set<String> jsonAnnotationsIdsSet = new HashSet<String>(); Iterator<JSONObject> jsonAnnotationsArrayIterator = jsonAnnotationsArray.iterator(); while (jsonAnnotationsArrayIterator.hasNext()) { JSONObject jsonAnnottation = jsonAnnotationsArrayIterator.next(); String jsonAnnotationIdentifier = (String) jsonAnnottation.get("identifier"); jsonAnnotationsIdsSet.add(jsonAnnotationIdentifier); } Set<Set<String>> jsonAnnotationsIdPowerSet = SetsOperations.powerSet(jsonAnnotationsIdsSet); Iterator<Set<String>> jsonAnnotationsIdPowerSetIterator = jsonAnnotationsIdPowerSet.iterator(); while (jsonAnnotationsIdPowerSetIterator.hasNext()) { Set<String> idsSet = jsonAnnotationsIdPowerSetIterator.next(); if (idsSet.containsAll(owlClassesIds)) { return true; } } return false; }
public boolean isTaskStatusCompleted(String data) throws Exception { /// will do later for importing process boolean isCompleted = false; if (DataFormatValidator.isValidateJson(data)) { JSONParser parser = new JSONParser(); Object obj = parser.parse(data); JSONArray jsonObject = (JSONArray) obj; Iterator itr = jsonObject.iterator(); while (itr.hasNext()) { JSONObject featureJsonObj = (JSONObject) itr.next(); // logger.debug("featureJsonObj : " + featureJsonObj); String status = (String) featureJsonObj.get("state"); // logger.debug("status : " + status); if (status.equalsIgnoreCase("completed")) { isCompleted = true; } } } return isCompleted; }
public void initialize() { base64Hash = new String(Base64.encodeBase64((user + ":" + password).getBytes())); JSONArray processes = invoke(webResource().path(API_PROCESS)); JSONObject json = (JSONObject) processes.iterator().next(); id = (String) json.get("id"); String name = (String) json.get("name"); if (acefIndex.containsKey(name)) { degree = Degree.readBySigla(acefIndex.get(name)); JSONArray forms = invoke(webResource().path(API_FORM).queryParam("processId", id)); for (Object object : forms) { JSONObject form = (JSONObject) object; if ("Guião para a auto-avaliação".equals(form.get("name"))) { formId = (String) form.get("id"); } } if (formId == null) { throw new DomainException("Process " + name + " has no auto-evaluation form."); } } else { throw new DomainException("Not recognized ACEF code: " + name); } }
@Override public List<String> getSupportedCountries(MerchantStore store) throws ServiceException { List<String> supportedCountries = new ArrayList<String>(); MerchantConfiguration configuration = merchantConfigurationService.getMerchantConfiguration(SUPPORTED_COUNTRIES, store); if (configuration != null) { String countries = configuration.getValue(); if (!StringUtils.isBlank(countries)) { Object objRegions = JSONValue.parse(countries); JSONArray arrayRegions = (JSONArray) objRegions; @SuppressWarnings("rawtypes") Iterator i = arrayRegions.iterator(); while (i.hasNext()) { supportedCountries.add((String) i.next()); } } } return supportedCountries; }
static void readQALDfile() { DocumentBuilderFactory qaldFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder qaldBuilder; JSONParser parser = new JSONParser(); String anno = ""; String unanno = ""; int failcount = 0; try { qaldBuilder = qaldFactory.newDocumentBuilder(); Document doc = qaldBuilder.newDocument(); Element mainRootElement = doc.createElementNS("http://github.com/AKSW/AskNow", "NQSforQALD"); doc.appendChild(mainRootElement); Object obj = parser.parse( new FileReader("/Users/mohnish/git2/sandbox/src/main/resources/qald6test.json")); JSONObject jsonObject = (JSONObject) obj; // JSONArray questions = (JSONArray) jsonObject.get("questions"); // String output = null; JSONArray quald = (JSONArray) jsonObject.get("questions"); Iterator<JSONObject> questions = quald.iterator(); while (questions.hasNext()) { JSONObject quesObj = questions.next(); Object ids = quesObj.get("id"); // int idi = Integer.parseInt(ids); // if (idi<=300){ // continue; // } String ques = null; // ystem.out.println(id ); JSONArray alllang = (JSONArray) quesObj.get("question"); Iterator<JSONObject> onelang = alllang.iterator(); while (onelang.hasNext()) { JSONObject engques = onelang.next(); ques = (String) engques.get("string"); break; } anno = Fox.annotate(ques); if (anno == "") { anno = Spotlight.getDBpLookup(ques); } // mainRootElement.appendChild(getNQSxml(doc, ids.toString() , ques, // getNQS(ques),nertags.toString())); if (anno != "") System.out.println("Id is " + ids.toString() + " " + anno); else { unanno = unanno + ids.toString() + " " + ques + "\n"; failcount++; } } System.out.println("Fail count for fox is" + failcount + "\n" + unanno); // System.out.println(output); // try{ // out.println( output); // Transformer transformer = TransformerFactory.newInstance().newTransformer(); // transformer.setOutputProperty(OutputKeys.INDENT, "yes"); // DOMSource source = new DOMSource(doc); // StreamResult result = new StreamResult(new // File("/Users/mohnish/git2/AskNow/src/main/resources/qald6test-nqs.xml")); // StreamResult console = new StreamResult(System.out); // transformer.transform(source, result); // out.println( console); // System.out.println("\nXML DOM Created Successfully.."); // } catch (TransformerConfigurationException e) { // TODO Auto-generated catch block // e.printStackTrace(); // } catch (TransformerFactoryConfigurationError e) { // TODO Auto-generated catch block // e.printStackTrace(); // } catch (TransformerException e) { // TODO Auto-generated catch block // e.printStackTrace(); // } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (ParseException e) { e.printStackTrace(); } catch (ParserConfigurationException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } }
public String updateApp( ClientApp clientApp, JSONObject attribute, JSONArray labelModel, Long categoryID) throws Exception { InputStream templateIS = Thread.currentThread().getContextClassLoader().getResourceAsStream("html/template.html"); String templateString = StreamConverter.convertStreamToString(templateIS); templateString = templateString.replace("TEMPLATE:SHORTNAME", clientApp.getShortName()); // templateString = templateString.replace("TEMPLATE:NAME", clientApp.getName()); // TEMPLATEFORATTRIBUTEAIDR String attributeDisplay = (String) attribute.get("name"); // String attributeCode = (String)attribute.get("code"); attributeDisplay = attributeDisplay + " " + (String) attribute.get("description"); templateString = templateString.replace("TEMPLATE:FORATTRIBUTEAIDR", attributeDisplay); JSONArray sortedLabelModel = JsonSorter.sortJsonByKey(labelModel, "norminalLabelCode"); StringBuffer displayLabel = new StringBuffer(); Iterator itr = sortedLabelModel.iterator(); // logger.debug("sortedLabelModel : " + sortedLabelModel); while (itr.hasNext()) { JSONObject featureJsonObj = (JSONObject) itr.next(); String labelName = (String) featureJsonObj.get("name"); String lableCode = (String) featureJsonObj.get("norminalLabelCode"); String description = (String) featureJsonObj.get("description"); Long norminalLabelID = (Long) featureJsonObj.get("norminalLabelID"); displayLabel.append("<label class='radio' name='nominalLabel'><strong>"); displayLabel.append("<input name='nominalLabel' type='radio' value='"); displayLabel.append(lableCode); displayLabel.append("'>"); displayLabel.append(labelName); displayLabel.append("</strong>"); if (!description.isEmpty()) { displayLabel.append(" "); displayLabel.append("<font color='#999999' size=-1>"); displayLabel.append(description); displayLabel.append("</font>"); } displayLabel.append("</label>"); } // logger.debug("displayLabel : " + displayLabel.toString()); templateString = templateString.replace("TEMPLATE:FORLABELSFROMAIDR", displayLabel.toString()); InputStream tutorialIS = Thread.currentThread().getContextClassLoader().getResourceAsStream("html/tutorial.html"); String tutorialString = StreamConverter.convertStreamToString(tutorialIS); tutorialString = tutorialString.replace("TEMPLATE:SHORTNAME", clientApp.getShortName()); tutorialString = tutorialString.replace("TEMPLATE:NAME", clientApp.getName()); InputStream longDescIS = Thread.currentThread() .getContextClassLoader() .getResourceAsStream("html/long_description.html"); String longDescString = StreamConverter.convertStreamToString(longDescIS); JSONObject app = new JSONObject(); app.put("task_presenter", templateString); app.put("tutorial", tutorialString); app.put("thumbnail", "http://i.imgur.com/lgZAWIc.png"); JSONObject app2 = new JSONObject(); app2.put("info", app); app2.put("long_description", longDescString); app2.put("name", clientApp.getName()); app2.put("short_name", clientApp.getShortName()); app2.put("description", clientApp.getShortName()); app2.put("id", clientApp.getPlatformAppID()); app2.put("time_limit", 0); app2.put("long_tasks", 0); app2.put("created", "" + new Date().toString() + ""); app2.put("calibration_frac", 0); app2.put("bolt_course_id", 0); app2.put("link", "<link rel='self' title='app' href='http://localhost:5000/api/app/2'/>"); app2.put("allow_anonymous_contributors", true); app2.put("time_estimate", 0); app2.put("hidden", 0); // app2.put("category_id", categoryID); // app2.put("owner_id", 1); // long_description return app2.toJSONString(); }
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { logger.debug("Login Post Action!"); try { Properties globalProps = (Properties) getServletContext().getAttribute("globalProps"); Map<String, Object> templateParam = new HashMap<>(); HttpSession session = request.getSession(true); session.setMaxInactiveInterval(Integer.valueOf(globalProps.getProperty("sessionTimeout"))); // TODO: Implement custom authentication logic if required. String username = request.getParameter("username"); String password = request.getParameter("password"); String role = null; Boolean authenticated = false; // if ldap is provided then it overrides roleset. if (globalProps.getProperty("ldapAuth").equals("true")) { authenticated = new LdapAuth() .authenticateUser( globalProps.getProperty("ldapUrl"), username, password, globalProps.getProperty("ldapDomain")); if (authenticated) { JSONArray jsonRoleSet = (JSONArray) ((JSONObject) new JSONParser().parse(globalProps.getProperty("ldapRoleSet"))) .get("users"); for (Iterator it = jsonRoleSet.iterator(); it.hasNext(); ) { JSONObject jsonUser = (JSONObject) it.next(); if (jsonUser.get("username") != null && jsonUser.get("username").equals("*")) { role = (String) jsonUser.get("role"); } if (jsonUser.get("username") != null && jsonUser.get("username").equals(username)) { role = (String) jsonUser.get("role"); } } if (role == null) { role = ZooKeeperUtil.ROLE_USER; } } } else { JSONArray jsonRoleSet = (JSONArray) ((JSONObject) new JSONParser().parse(globalProps.getProperty("userSet"))) .get("users"); for (Iterator it = jsonRoleSet.iterator(); it.hasNext(); ) { JSONObject jsonUser = (JSONObject) it.next(); if (jsonUser.get("username").equals(username) && jsonUser.get("password").equals(password)) { authenticated = true; role = (String) jsonUser.get("role"); } } } if (authenticated) { logger.info("Login successfull: " + username); session.setAttribute("authName", username); session.setAttribute("authRole", role); response.sendRedirect("/home"); } else { session.setAttribute("flashMsg", "Invalid Login"); ServletUtil.INSTANCE.renderHtml(request, response, templateParam, "login.ftl.html"); } } catch (ParseException | TemplateException ex) { logger.error(Arrays.toString(ex.getStackTrace())); ServletUtil.INSTANCE.renderError(request, response, ex.getMessage()); } }
// ----This function gets the raw json from raw_data collection---- // ---------the function separate the tweets and inserts it to all_tweets collection and calling // all other data processing methods----------- // ---------------------------------------------------------------------------------------- public void update_all_tweets(final double num_of_slots, final double max_time_frame_hours) throws MongoException, ParseException { log4j.info("starting update_all_tweets function"); String res = new String(); Integer countelements = 0; while (true) { // DBCursor cursor = this.collrd.find(); while (this.collrd.count() < 1) { // no documents to process try { log4j.info("there is no raw data at the moment, going to sleep for 10 seconds"); Thread.currentThread(); Thread.sleep(1000 * 10); log4j.info("woke up, continues"); // cursor = this.collrd.find(); } catch (InterruptedException e) { log4j.error("InterruptedException caught, at update_all_tweets"); log4j.error(e); } } DBCursor cursor = this.collrd.find(); // get all documents from raw_data collection try { while (cursor.hasNext()) { DBObject currdoc = cursor.next(); log4j.info("getting a document from the raw data db"); Object results = currdoc.get("results"); // result - json array of tweets try { res = results.toString(); } catch (NullPointerException e) { res = ""; } Object obj = JSONValue.parse(res); log4j.info("making an array from the jsons tweets"); JSONArray array = (JSONArray) obj; // make an array of tweets // JSONParser parser = new JSONParser(); try { if (res != "") { // if there are tweets @SuppressWarnings("rawtypes") Iterator iterArray = array.iterator(); log4j.info("iterating over array tweets"); try { while (iterArray.hasNext()) { Object current = iterArray.next(); final DBObject dbObject = (DBObject) JSON.parse(current.toString()); // parse all tweet data to json countelements++; // System.out.println("element number" + countelements.toString()); dbObject.put("max_id", currdoc.get("max_id")); // add max_id to tweet data dbObject.put("query", currdoc.get("query")); // add query word to tweet data dbObject.put( "query_time", currdoc.get("query_time")); // add query time to tweet data dbObject.put("query_time_string", currdoc.get("query_time_string")); dbObject.put( "text", "@" + dbObject.get("from_user").toString() + ": " + dbObject.get("text").toString()); // add user_name to beginning of text dbObject.put("count", 1L); // add appearance counter to tweet data log4j.info("inserting tweet id: " + dbObject.get("id").toString()); try { DBObject object = new BasicDBObject(); object.put( "id", Long.parseLong(dbObject.get("id").toString())); // object to search DBObject newobject = collat.findOne(object); if (newobject != null) { newobject.put( "count", Long.parseLong(newobject.get("count").toString()) + 1); // update counter if id already exists collat.update(object, newobject); } } catch (NullPointerException e) { } collat.insert(dbObject); // collrd.findAndRemove(currdoc); // log4j.info("calling function update_search_terms"); // final String text = "@" + dbObject.get("from_user").toString() + ": " + // dbObject.get("text").toString(); /*Thread t10=new Thread(new Runnable(){ public void run(){ UpdateTweetCounterId(Long.parseLong(dbObject.get("id").toString())); } });*/ Thread t11 = new Thread( new Runnable() { public void run() { update_search_terms( dbObject.get("text").toString(), num_of_slots, max_time_frame_hours, dbObject.get("query").toString()); } }); Thread t12 = new Thread( new Runnable() { public void run() { rate_user( Long.parseLong(dbObject.get("from_user_id").toString()), dbObject.get("from_user").toString(), max_time_frame_hours); // UpdateUserRate((long)num_of_slots,slot_time_millis,Long.parseLong(dbObject.get("from_user_id").toString()) , dbObject.get("from_user").toString() ,(long)0); } }); Thread t13 = new Thread( new Runnable() { public void run() { String quer = dbObject.get("query").toString(); quer = quer.replaceAll("%40", "@"); quer = quer.replaceAll("%23", "#"); long id = (long) (Double.parseDouble(dbObject.get("query_time").toString()) * 1000); String idplus = dbObject.get("id").toString() + "," + id; SearchResultId(quer, idplus); } }); // t10.start(); t11.start(); t12.start(); t13.start(); try { log4j.info("Waiting for threads to finish."); // t10.join(); t11.join(); t12.join(); t13.join(); } catch (InterruptedException e) { log4j.error("Main thread (update_all_tweets) Interrupted"); } } } catch (Exception e) { log4j.error(e); e.printStackTrace(); } } } catch (NullPointerException e) { log4j.error(e); log4j.info("NullPointerException caught, at update_all_tweets"); } log4j.info("removing processed document from raw_data collection"); try { this.collrd.remove(currdoc); } catch (Exception e) { log4j.debug(e); } } } catch (MongoException e) { log4j.error(e); } } }
public TaskQueueResponse getTaskQueueResponse( ClientApp clientApp, String pybossaResult, JSONParser parser, Long taskQueueID, ClientAppAnswer clientAppAnswer, ReportTemplateService rtpService) throws Exception { if (clientAppAnswer == null) { return null; } JSONObject responseJSON = new JSONObject(); String[] questions = getQuestion(clientAppAnswer, parser); int[] responses = new int[questions.length]; JSONArray array = (JSONArray) parser.parse(pybossaResult); int cutOffSize = getCutOffNumber(array.size(), clientApp.getTaskRunsPerTask(), clientAppAnswer); System.out.println("cutOffSize :" + cutOffSize); Iterator itr = array.iterator(); String answer = null; boolean foundCutoffItem = false; while (itr.hasNext()) { JSONObject featureJsonObj = (JSONObject) itr.next(); JSONObject info = (JSONObject) featureJsonObj.get("info"); Long taskID = (Long) featureJsonObj.get("id"); answer = this.getUserAnswer(featureJsonObj, clientApp); System.out.println("answer :" + answer); if (answer != null && !clientApp.getAppType().equals(StatusCodeType.APP_MAP)) { for (int i = 0; i < questions.length; i++) { if (questions[i].trim().equalsIgnoreCase(answer.trim())) { responses[i] = responses[i] + 1; foundCutoffItem = handleItemAboveCutOff( taskQueueID, responses[i], answer, info, clientAppAnswer, rtpService, cutOffSize); } } } } String taskInfo = ""; String responseJsonString = ""; for (int i = 0; i < questions.length; i++) { responseJSON.put(questions[i], responses[i]); } responseJsonString = responseJSON.toJSONString(); TaskQueueResponse taskQueueResponse = new TaskQueueResponse(taskQueueID, responseJsonString, taskInfo); return taskQueueResponse; }
/** JSON */ public void readJSON(String message) { /* création des objets JSONObject et JSONParser */ JSONParser parser = new JSONParser(); JSONObject jsonObject = null; try { jsonObject = (JSONObject) parser.parse(message); /* Creation d'une nouvelle areas */ // this.areas = new HashMap<String, Areas>(); // for (JSONObject o: (ArrayList<JSONObject>) jsonObject.get("areas")){ // this.areas.put((String)o.get("name"), new Areas()); // } /* création d'une liste d'objet JSON contenant les paramètres de la trame JSON ("areas") */ JSONArray areas = (JSONArray) jsonObject.get("areas"); Iterator ite_areas = areas.iterator(); /* Name */ while (ite_areas.hasNext()) { JSONObject obj1 = (JSONObject) ite_areas.next(); /* Map */ JSONObject map = (JSONObject) obj1.get("map"); System.out.println(map); /* Weight */ JSONObject weight = (JSONObject) map.get("weight"); /* Obtient les valeurs de w et h */ Collection col_weight = weight.values(); Iterator i = col_weight.iterator(); System.out.println(i.next()); // for( Object obj: col_weight) { // /* création d'une liste d'objets JSON contenant les objets de la // collection */ // ArrayList<JSONObject> keyl = (ArrayList<JSONObject>) obj; //// System.out.println(keyl.get(0)); // } /* Vertices */ JSONArray vertices = (JSONArray) map.get("vertices"); // System.out.println(vertices); // Iterator ite_vertices = vertices.iterator(); // JSONObject obj2 = (JSONObject) ite_vertices.next(); // // /* recupere le X et le Y des differents points */ // for(int i=0 ;i<vertices.size() ;i++){ // for(int j=0; j<vertices.size();j++){ // tab[i][j] = (double) obj2.get("x"); // j++; // tab[i][j] = (double) obj2.get("y"); // } // } /* Streets */ // JSONArray streets = (JSONArray) jsonObject.get("streets"); // Iterator ite_streets = streets.iterator(); // /* Bridges */ // JSONArray bridges = (JSONArray) jsonObject.get("bridges"); // Iterator ite_bridges = bridges.iterator(); /* Weight, Vertices, Streets and Bridges */ // Iterator ite_map = map.iterator(); // while (ite_map.hasNext()){ // JSONObject Obj2 = (JSONObject) ite_map.next(); // JSONArray weight = (JSONArray) Obj2.get("weight"); // JSONArray vertices = (JSONArray) Obj2.get("vertices"); // JSONArray streets = (JSONArray) Obj2.get("streets"); // JSONArray bridges = (JSONArray) Obj2.get("bridges"); } /** *************VERSION FONCTIONNELLE******************* */ // for(JSONObject a: liste){ // /* on "isole" le contenu des objets dans une collection */ // Collection names = a.values(); // System.out.println("names: " + names + "\n"); // // get an array from the JSON object // // } // System.out.println("liste: " + liste + "\n"); // for(JSONObject a: liste){ // /* on "isole" le contenu des objets dans une collection */ // Collection names = a.values(); // System.out.println("names: " + names + "\n"); // /* pour tous les objets de la collection */ // for(Object obj: names) { // Iterator itNames = names.iterator(); // } // } /** ***************************************************** */ } catch (org.json.simple.parser.ParseException e) { e.printStackTrace(); System.out.println(e.getMessage()); } }
public static void main(String[] args) { JSONParser parser = new JSONParser(); ArrayList<Player> playerList = new ArrayList<>(); Player[] playerArray; ArrayList<Player> mvpList = new ArrayList<>(); try { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); String inputPath = reader.readLine(); FileReader fileReader = new FileReader(inputPath); Object inputObject = parser.parse(fileReader); JSONObject jsonObject = (JSONObject) inputObject; JSONArray jsonArray = (JSONArray) jsonObject.get("players"); Iterator<JSONObject> playerIterator = jsonArray.iterator(); while (playerIterator.hasNext()) { JSONObject playerObject = (JSONObject) playerIterator.next(); Player player = new Player(); player.setId((String) playerObject.get("id")); player.setFirstname((String) playerObject.get("firstname")); player.setLastname((String) playerObject.get("lastname")); player.setTeam((String) playerObject.get("team")); player.setGp((int) (long) playerObject.get("gp")); player.setMin((int) (long) playerObject.get("min")); player.setPts((int) (long) playerObject.get("pts")); player.setOreb((int) (long) playerObject.get("oreb")); player.setDreb((int) (long) playerObject.get("dreb")); player.setAsts((int) (long) playerObject.get("asts")); player.setStl((int) (long) playerObject.get("stl")); player.setBlk((int) (long) playerObject.get("blk")); player.setTo((int) (long) playerObject.get("to")); player.setPf((int) (long) playerObject.get("pf")); player.setFga((int) (long) playerObject.get("fga")); player.setFgm((int) (long) playerObject.get("fgm")); player.setFta((int) (long) playerObject.get("fta")); player.setFtm((int) (long) playerObject.get("ftm")); player.setTpa((int) (long) playerObject.get("tpa")); player.setTpm((int) (long) playerObject.get("tpm")); JSONArray jsonPosArray = (JSONArray) playerObject.get("pos"); Iterator<String> posIterator = jsonPosArray.iterator(); ArrayList<String> posArray = new ArrayList<>(); while (posIterator.hasNext()) { posArray.add((String) posIterator.next()); } player.setPos(posArray); int result = player.getPts() + player.getOreb() + player.getDreb() + player.getAsts() + player.getStl() + player.getBlk() - player.getFga() + player.getFgm() - player.getFta() + player.getFtm() - player.getTo(); player.setResult(result); playerList.add(player); } playerArray = new Player[playerList.size()]; playerArray = playerList.toArray(playerArray); Player swapTemp; for (int i = 0; i < playerArray.length; i++) { for (int j = i; j < playerArray.length; j++) { if (playerArray[i].getResult() < playerArray[j].getResult()) { swapTemp = playerArray[i]; playerArray[i] = playerArray[j]; playerArray[j] = swapTemp; } } } int brojMvp = 0; Player mvp = playerArray[0]; boolean bool = false; boolean bool1 = false; for (int i = 0; i < playerArray.length; i++) { if (playerArray[i] == null) { continue; } for (int j = 0; j < playerArray[i].getPos().size(); j++) { if (playerArray[i].getPos().contains("SG")) { out: for (int j2 = 0; j2 < mvpList.size(); j2++) { for (int k = j2 + 1; k < mvpList.size(); k++) { if (playerArray[i].getTeam().equals(mvpList.indexOf(j2)) && playerArray[i].getTeam().equals(mvpList.indexOf(k))) { bool1 = true; break out; } } } mvpList.add(playerArray[i]); brojMvp++; playerArray[i] = null; bool = true; break; } } if (bool) { bool = false; break; } } for (int i = 0; i < playerArray.length; i++) { if (playerArray[i] == null) { continue; } for (int j = 0; j < playerArray[i].getPos().size(); j++) { if (playerArray[i].getPos().contains("PG")) { mvpList.add(playerArray[i]); brojMvp++; playerArray[i] = null; bool = true; break; } } if (bool) { bool = false; break; } } for (int i = 0; i < playerArray.length; i++) { if (playerArray[i] == null) { continue; } for (int j = 0; j < playerArray[i].getPos().size(); j++) { if (playerArray[i].getPos().contains("SF")) { mvpList.add(playerArray[i]); brojMvp++; playerArray[i] = null; bool = true; break; } } if (bool) { bool = false; break; } } for (int i = 0; i < playerArray.length; i++) { if (playerArray[i] == null) { continue; } for (int j = 0; j < playerArray[i].getPos().size(); j++) { if (playerArray[i].getPos().contains("PF")) { mvpList.add(playerArray[i]); brojMvp++; playerArray[i] = null; bool = true; break; } } if (bool) { bool = false; break; } } for (int i = 0; i < playerArray.length; i++) { if (playerArray[i] == null) { continue; } for (int j = 0; j < playerArray[i].getPos().size(); j++) { if (playerArray[i].getPos().contains("C")) { mvpList.add(playerArray[i]); brojMvp++; playerArray[i] = null; bool = true; break; } } if (bool) { bool = false; break; } } if (brojMvp < 5) { System.out.println("Broj igraca u dream team-u je nedovoljan(" + brojMvp + ")"); System.exit(0); } JSONObject outputObject = new JSONObject(); JSONObject outputMvpObject = new JSONObject(); Iterator<Player> mvpIterator = mvpList.iterator(); FileWriter writer = new FileWriter("autputdzejson.json"); outputMvpObject.put("id", mvp.getId()); outputMvpObject.put("firstname", mvp.getFirstname()); outputMvpObject.put("lastname", mvp.getLastname()); outputMvpObject.put("team", mvp.getTeam()); JSONArray mvpPosArray = new JSONArray(); Iterator<String> mvpPosIterator = mvp.getPos().iterator(); while (mvpPosIterator.hasNext()) { mvpPosArray.add(mvpPosIterator.next()); } outputMvpObject.put("pos", mvpPosArray); outputObject.put("MVP", outputMvpObject); JSONArray outputDreamTeamArray = new JSONArray(); while (mvpIterator.hasNext()) { JSONObject outputDreamTeamObject = new JSONObject(); Player innerPlayer = mvpIterator.next(); outputDreamTeamObject.put("id", innerPlayer.getId()); outputDreamTeamObject.put("firstname", innerPlayer.getFirstname()); outputDreamTeamObject.put("lastname", innerPlayer.getLastname()); outputDreamTeamObject.put("team", innerPlayer.getTeam()); JSONArray dreamTeamPosArray = new JSONArray(); Iterator<String> dreamTeamPosIterator = innerPlayer.getPos().iterator(); while (dreamTeamPosIterator.hasNext()) { dreamTeamPosArray.add(dreamTeamPosIterator.next()); } outputDreamTeamObject.put("pos", dreamTeamPosArray); outputDreamTeamArray.add(outputDreamTeamObject); } outputObject.put("dreamTeam", outputDreamTeamArray); writer.write(outputObject.toJSONString()); writer.flush(); writer.close(); } catch (FileNotFoundException e) { System.out.println("Pogresna putanja za ulazni fajl."); } catch (IOException e) { System.out.println("Greska pri unosu putanje."); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
/*ClientResponse responseObj JSONObject responseObj*/ public static ArrayList<String> getAuthor(String responseObj) throws JsonParseException, JsonMappingException, IOException, ParseException { // public static void main(String[] args) { List<String> authorOrcidListist = new ArrayList<String>(); String arrayLabell = new String(); Author ag = new Author(); JSONParser parser = new JSONParser(); // Map<String, String> agrovocsUri = new HashMap<String, String>(); Object context = new Object(); Object obj = new Object(); JSONObject cntx = new JSONObject(); JSONObject jsonObject = new JSONObject(); float personConfid = 0; String aartaClassRef[]; String tmpConfFloat = null; String taClassRef = null; String locationConf = null; String orcid = null; String[] location = null; String[] person = null; String authorName = null; String entityValue = null; String str = "Person"; boolean blnFound = false; // authorOrcidListist = null; try { System.out.println("*********getAuthor()**************** "); // FILE Object obj = parser.parse(new // FileReader("C:\\Users\\papou_000\\Desktop\\agroknow\\rest\\responseOK.json")); // FILE JSONObject jsonObject = (JSONObject) obj; obj = parser.parse(responseObj); jsonObject = (JSONObject) obj; // loop array JSONArray graph = (JSONArray) jsonObject.get("@graph"); // jsonObject Iterator<String> iterator = graph.iterator(); while (iterator.hasNext()) { context = iterator.next(); cntx = (JSONObject) context; taClassRef = (String) cntx.get("taClassRef"); // aartaClassRef = taClassRef.split("#"); // System.out.print("testttt:"); ///// ok System.out.print("\""+ taClassRef+"\":"); // blnFound = taClassRef.contains(taClassRef.toString()); // bad System.out.print(""+ taClassRef.toLowerCase().contains(str.toLowerCase()) + " "); // System.out.print(""+ cntx.get("taClassRef")+" :"); if (cntx.get("taIdentRef") != null) { // && personConfid > 0.4 orcid = (String) cntx.get("taIdentRef"); tmpConfFloat = cntx.get("itsrdf:taConfidence").toString(); System.out.print( "taIdentRef" + orcid + " "); // print "http://orcid.org/0000-0003-3347-8265":null entityValue = cntx.get("nif:anchorOf").toString(); authorOrcidListist.add( taClassRef + " " + orcid.trim() + " " + entityValue.trim() + tmpConfFloat); System.out.println("authorName" + entityValue + "hngdh"); } // taIdentRef // if(taClassRef.toLowerCase().contains(str.toLowerCase())){ // //tmpFloat = (String) cntx.get("itsrdf:taConfidence"); // //personConfid = Float.parseFloat(tmpFloat); // // System.out.print(" "+ cntx.get("itsrdf:taConfidence")+" :"); // if(cntx.get("taIdentRef")!= null ){//&& personConfid > 0.4 // orcid = (String) cntx.get("taIdentRef"); // System.out.print("taIdentRef"+ orcid+" "); //print // "http://orcid.org/0000-0003-3347-8265":null // authorName = cntx.get("nif:anchorOf").toString(); // authorOrcidListist.add(orcid.trim() + " " + authorName.trim() + " "); // System.out.println("authorName" + authorName + "hngdh" ); // } //taIdentRef // }else if (taClassRef.contains("Location")){//is location? // System.out.print("\"orcid"+ orcid+"\":"); // // }else if (taClassRef.contains("Organization")){ // System.out.print("in Organisation"); // }else{ // System.out.print("no at any case"); // // } cntx = null; aartaClassRef = null; taClassRef = null; authorName = null; } // end of while // authorOrcidListist.add("akstemLabels"); // get label } catch (ParseException e) { e.printStackTrace(); } authorOrcidListist.removeAll(Collections.singleton(null)); return (ArrayList<String>) authorOrcidListist; }
/** @param args */ public static void main(String[] args) { DTO dtoHolder = new DTO(); JSONArray freeList = GPIO.freeGPIOs(); if (args.length > 0) { // these'll all be outputs for (String arg : args) { Iterator freeListIterator = freeList.iterator(); while (freeListIterator.hasNext()) { JSONObject freePin = (JSONObject) freeListIterator.next(); String key = (String) freePin.get("key"); if (key.equalsIgnoreCase(arg)) { if (dtoHolder.addGPIO(arg, DTO.OUTPUT) == false) { System.out.println("Couldn't find " + arg); System.exit(1); } } else { if (freePin.containsKey("options")) { JSONArray options = (JSONArray) freePin.get("options"); for (int i = 0; i < options.size(); i++) { String option = (String) options.get(i); if (option.equalsIgnoreCase(arg)) { if (dtoHolder.addGPIO(arg, DTO.OUTPUT) == false) { System.out.println("Couldn't find " + arg); System.exit(1); } } } } else { System.out.println(arg + " is not a free pin"); } } } } String fileContents = dtoHolder.createFileContents(); FileWriter dtoOutput; try { dtoOutput = new FileWriter("jgpio-00A0.dto"); dtoOutput.write(fileContents); dtoOutput.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else { Iterator<JSONObject> freeIterator = freeList.iterator(); while (freeIterator.hasNext()) { JSONObject current = freeIterator.next(); System.out.print(" " + (String) current.get("key")); } System.out.println(""); } }