List of usage examples for org.json.simple JSONArray JSONArray
JSONArray
From source file:com.mysql.servlet.NewClass.java
public static void main(String[] args) { JSONObject headerFile = new JSONObject(); JSONArray listOfAttrs = new JSONArray(); listOfAttrs.add("id" + ""); listOfAttrs.add("name" + ""); listOfAttrs.add("age" + ""); listOfAttrs.add("salary" + ""); listOfAttrs.add("grade" + ""); headerFile.put("Employee", listOfAttrs); try {// w w w . jav a 2 s .c o m // Writing to a file File file = new File("D:\\Employees.json"); file.createNewFile(); FileWriter fileWriter = new FileWriter(file); System.out.println("Writing JSON object to file"); System.out.println("-----------------------"); System.out.print(headerFile); fileWriter.write(headerFile.toJSONString()); fileWriter.flush(); fileWriter.close(); } catch (IOException e) { e.printStackTrace(); } }
From source file:jsonpractice.Jsonpractice.java
public static void main(String[] args) throws IOException { JSONObject countryObj = new JSONObject(); countryObj.put("Name", "India"); countryObj.put("Population", 1000000); JSONArray listOfStates = new JSONArray(); listOfStates.add("Madhya Pradesh"); listOfStates.add("Maharastra"); listOfStates.add("Tamil Nadu"); countryObj.put("States", listOfStates); try {// w w w . ja v a2 s. c om File file = new File("C:\\Users\\user\\Documents\\CountryJSONFile.json"); file.createNewFile(); try (FileWriter fileWriter = new FileWriter(file)) { System.out.println("Writing JSON OBJECT to file"); System.out.println("-----------------------------"); System.out.println(countryObj); fileWriter.write(countryObj.toJSONString()); fileWriter.flush(); } catch (IOException e) { } } catch (IOException e) { } }
From source file:json.WriteToFile.java
public static void main(String[] args) { JSONObject countryObj = new JSONObject(); countryObj.put("Name", "Kenya"); countryObj.put("Population", new Integer(430000000)); JSONArray listOfCounties = new JSONArray(); listOfCounties.add("Nairobi"); listOfCounties.add("Kiambu"); listOfCounties.add("Murang'a"); countryObj.put("Counties", listOfCounties); try {// ww w . ja v a 2 s. co m //writing to file File file = new File("/home/mars/Desktop/JsonExample1.json"); file.createNewFile(); FileWriter fw = new FileWriter(file); System.out.println("Writing JSON object to file"); System.out.println("---------------------------"); System.out.println(countryObj); fw.write(countryObj + ""); fw.flush(); fw.close(); } catch (IOException e) { e.printStackTrace(); } }
From source file:cat.tv3.eng.rec.recomana.lupa.visualization.TextsResumeToJson.java
public static void main(String[] args) throws IOException { String host = args[0];/* www . ja va 2 s. co m*/ int port = Integer.parseInt(args[1]); Jedis jedis = new Jedis(host, port, 20000); String[] text_keys = jedis.keys("hash_id_*").toArray(new String[0]); for (int i = 0; i < text_keys.length; ++i) { JSONArray resume = new JSONArray(); String[] split_resume_name = text_keys[i].split("_"); String id = split_resume_name[split_resume_name.length - 1]; JSONObject text = new JSONObject(); text.put("id", id); text.put("tittle", jedis.hget(text_keys[i], "tittle")); text.put("text", jedis.hget(text_keys[i], "text")); resume.add(text); saveResults(resume, id); } jedis.disconnect(); }
From source file:com.intuit.utils.PopulateUsers.java
public static void main(String[] args) { Date now = new Date(); System.out.println("Current date is: " + now.toString()); MongoClient mongo = new MongoClient("localhost", 27017); DB db = mongo.getDB("tweetsdb"); DBCollection collection = db.getCollection("userscollection"); WriteResult result = collection.remove(new BasicDBObject()); int userIndex = 1; for (int i = 1; i <= 10; i++) { JSONObject userDocument = new JSONObject(); String user = "user" + userIndex; userDocument.put("user", user); JSONArray followerList = new JSONArray(); Random randomGenerator = new Random(); for (int j = 0; j < 3; j++) { int followerId = randomGenerator.nextInt(10) + 1; // Assumption here is, a user will not be a follower on himself while (followerId == userIndex) { followerId = randomGenerator.nextInt(10) + 1; }/* ww w . ja va 2 s . com*/ String follower = "user" + followerId; if (!followerList.contains(follower)) { followerList.add(follower); } } userDocument.put("followers", followerList); JSONArray followingList = new JSONArray(); for (int k = 0; k < 3; k++) { int followingId = randomGenerator.nextInt(10) + 1; // Assumption here is, a user will not be following his own tweets while (followingId == userIndex) { followingId = randomGenerator.nextInt(10) + 1; } String followingUser = "user" + followingId; if (!followingList.contains(followingUser)) { followingList.add(followingUser); } } userDocument.put("following", followingList); System.out.println("Json string is: " + userDocument.toString()); DBObject userDBObject = (DBObject) JSON.parse(userDocument.toString()); collection.insert(userDBObject); userIndex++; } // try { // FileWriter file = new FileWriter("/Users/dmurty/Documents/MongoData/usersCollection.js"); // file.write(usersArray.toJSONString()); // file.flush(); // file.close(); // } catch (IOException ex) { // Logger.getLogger(PopulateUsers.class.getName()).log(Level.SEVERE, null, ex); // } }
From source file:cat.tv3.eng.rec.recomana.lupa.visualization.RecommendationToJson.java
public static void main(String[] args) throws IOException { final int TOTAL_WORDS = 20; String host = args[0];//from ww w .j a va2s . c o m int port = Integer.parseInt(args[1]); Jedis jedis = new Jedis(host, port, 20000); String[] recommendation_keys = jedis.keys("recommendations_*").toArray(new String[0]); for (int i = 0; i < recommendation_keys.length; ++i) { JSONArray recommendations = new JSONArray(); String[] split_reco_name = recommendation_keys[i].split("_"); String id = split_reco_name[split_reco_name.length - 1]; Set<Tuple> recos = jedis.zrangeWithScores(recommendation_keys[i], 0, -1); Iterator<Tuple> it = recos.iterator(); while (it.hasNext()) { Tuple t = it.next(); JSONObject new_reco = new JSONObject(); new_reco.put("id", t.getElement()); new_reco.put("distance", (double) Math.round(t.getScore() * 10000) / 10000); recommendations.add(new_reco); } saveResults(recommendations, id); } jedis.disconnect(); }
From source file:br.unicamp.ft.priva.aas.client.RESTUsageExample.java
public static void main(String[] args) { Object policyJSON, dataJSON;//from ww w . j a va 2 s. co m //Example Data: String policyFile = "../priva-poc/input/example-mock-data/mock_data.policy.json"; String dataFile = "../priva-poc/input/example-mock-data/mock_data.json"; // Load Example Data: JSONParser parser = new JSONParser(); try { FileReader policyReader = new FileReader(policyFile); policyJSON = parser.parse(policyReader); FileReader dataReader = new FileReader(dataFile); dataJSON = parser.parse(dataReader); } catch (IOException | ParseException e) { System.out.println("IOException | ParseException = " + e); return; } System.out.println("policyJSON = " + policyJSON.toString().length()); System.out.println("dataJSON = " + dataJSON.toString().length()); JSONArray payload = new JSONArray(); payload.add(policyJSON); payload.add(dataJSON); // POST data to server Client client = ClientBuilder.newClient(); WebTarget statistics = client.target(ENDPOINT); String content = statistics.request(MediaType.APPLICATION_JSON) .post(Entity.entity(payload, MediaType.APPLICATION_JSON), String.class); System.out.println("result = " + content); }
From source file:gr.demokritos.iit.cru.creativity.reasoning.diagrammatic.Test.java
public static void main(String[] args) throws IOException, SQLException, ClassNotFoundException, InstantiationException, IllegalAccessException, FileNotFoundException, UnsupportedEncodingException, URISyntaxException, ParserConfigurationException, SAXException, XPathExpressionException, Exception { /* Connect c = new Connect("en"); DiagrammaticComputationalTools d = new DiagrammaticComputationalTools(c); ArrayList<String> s = new ArrayList<String>(); s.add("george");/*from w w w .ja v a 2 s . c om*/ s.add("thing"); s.add("loves"); // System.out.println(d.FindConcepts("friend", 4, "supersumption")); System.out.println(d.FindRelations(s,4, "supersumption")); /* String text = "white"; String src = "en"; String trg = "el"; int id = 1; String response = Translator.bingTranslate(text, src, trg, "general"); System.out.println(response); */ JSONArray a = new JSONArray(); JSONObject obj1 = new JSONObject(); obj1.put("c1", "cat"); obj1.put("rel", "isA"); obj1.put("c2", "animal"); a.add(obj1); JSONObject obj2 = new JSONObject(); obj2.put("c1", "animal"); obj2.put("rel", "likes"); obj2.put("c2", "animal"); a.add(obj2); JSONObject obj3 = new JSONObject(); obj3.put("c1", "dog"); obj3.put("rel", "isA"); obj3.put("c2", "animal"); a.add(obj3); JSONObject obj4 = new JSONObject(); obj4.put("c1", "wolf"); obj4.put("rel", "isA"); obj4.put("c2", "animal"); a.add(obj4); System.out.println(a); /* JSONArray b = new JSONArray(); obj1 = new JSONObject(); obj1.put("c1", "cat"); obj1.put("rel", "isA"); obj1.put("c2", "animal"); b.add(obj1); obj2 = new JSONObject(); obj2.put("c1", "cat"); obj2.put("rel", "likes"); obj2.put("c2", "fish"); b.add(obj2); obj3 = new JSONObject(); obj3.put("c1", "dog"); obj3.put("rel", "isA"); obj3.put("c2", "animal"); b.add(obj3); obj4 = new JSONObject(); obj4.put("c1", "wolf"); obj4.put("rel", "isA"); obj4.put("c2", "animal"); b.add(obj4); JSONObject obj5 = new JSONObject(); obj5.put("c1", "wolf"); obj5.put("rel", "likes"); obj5.put("c2", "meat"); b.add(obj5); FileWriter file = new FileWriter("C:\\Users\\George\\Desktop\\animals.json"); file.write(b.toJSONString()); file.flush(); file.close();*/ // System.out.println(a); // System.out.println(b); /* d.Graphs(a, b); List<String> urls = new ArrayList<String>(); List<String> urls_temp = new ArrayList<String>(); */ // String bingAppId = "a1Q3b3YdomwYyknyDHIykZx0A5Xc5n445mYiXoCfXC8="; // BingCrawler bc = new BingCrawler(bingAppId, "en"); // List<String> urls = bc.crawlImages(phrase); /* urls_temp = HTMLUtilities.linkExtractor("http://www.dmoz.org/search?q=" + phrase + "&cat=Kids_and_Teens&all=yes", "UTF-8", 1); for (String url : urls_temp) { urls.add(StringEscapeUtils.unescapeHtml4(url)); }*/ // HashSet<String> p=d.FactRetriever("haswikipediaurl","relation"); // HashSet<String> kl = d.FindConcepts("love",2, "concept");//.Relations(s, 2, "relation"); // System.out.println(kl.size());*/ // System.out.println(list.toString()); /* HashSet<String> p=d.Relations(s, 3, "equivalence");//.Facts("haswikipediaurl","relation");//.Concepts("vouzon",3,"relation");//.ConceptFinder("love",3, "supersumption");//FactRetriever("vouzon","subject"); // //ConceptGraphAbstraction("love");//.FactRetriever("vouzon", "subject");//.ConceptGraphPolymerismEngine("automobile"); for(String j:p){ System.out.println(j); } for (String g : urls) { System.out.println(g); }*/ }
From source file:com.github.fhuss.kafka.streams.cep.demo.CEPStockKStreamsDemo.java
public static void main(String[] args) { Properties props = new Properties(); props.put(StreamsConfig.APPLICATION_ID_CONFIG, "streams-cep"); props.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092"); props.put(StreamsConfig.ZOOKEEPER_CONNECT_CONFIG, "localhost:2181"); props.put(StreamsConfig.KEY_SERDE_CLASS_CONFIG, StockEventSerDe.class); props.put(StreamsConfig.VALUE_SERDE_CLASS_CONFIG, StockEventSerDe.class); // setting offset reset to earliest so that we can re-run the demo code with the same pre-loaded data props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest"); // build query final Pattern<Object, StockEvent> pattern = new QueryBuilder<Object, StockEvent>().select() .where((k, v, ts, store) -> v.volume > 1000).<Long>fold("avg", (k, v, curr) -> v.price).then() .select().zeroOrMore().skipTillNextMatch() .where((k, v, ts, state) -> v.price > (long) state.get("avg")) .<Long>fold("avg", (k, v, curr) -> (curr + v.price) / 2) .<Long>fold("volume", (k, v, curr) -> v.volume).then().select().skipTillNextMatch() .where((k, v, ts, state) -> v.volume < 0.8 * state.getOrElse("volume", 0L)) .within(1, TimeUnit.HOURS).build(); KStreamBuilder builder = new KStreamBuilder(); CEPStream<Object, StockEvent> stream = new CEPStream<>(builder.stream("StockEvents")); KStream<Object, Sequence<Object, StockEvent>> stocks = stream.query("Stocks", pattern); stocks.mapValues(seq -> {/*from ww w. j av a2 s .c o m*/ JSONObject json = new JSONObject(); seq.asMap().forEach((k, v) -> { JSONArray events = new JSONArray(); json.put(k, events); List<String> collect = v.stream().map(e -> e.value.name).collect(Collectors.toList()); Collections.reverse(collect); collect.forEach(e -> events.add(e)); }); return json.toJSONString(); }).through(null, Serdes.String(), "Matches").print(); //Use the topologyBuilder and streamingConfig to start the kafka streams process KafkaStreams streaming = new KafkaStreams(builder, props); //streaming.cleanUp(); streaming.start(); }
From source file:com.thesmartweb.vivliocrawlermaven.VivlioCrawlerMavenMain.java
/** * @param args the command line arguments *///from www . ja v a2s.co m public static void main(String[] args) { // TODO code application logic here try { OaiPmhServer server = new OaiPmhServer("http://vivliothmmy.ee.auth.gr/cgi/oai2"); RecordsList listRecords = server.listRecords("oai_dc");//we capture all the records in oai dc format List<VivlioCrawlerMavenMain> listtotal = new ArrayList<VivlioCrawlerMavenMain>(); //we capture all the names of the professors and former professor of ECE of AUTH from a txt file //change the directory to yours List<String> profs = Files.readAllLines(Paths.get( "/home/themis/NetBeansProjects/VivlioCrawlerMaven/src/main/java/com/thesmartweb/vivliocrawlermaven/profs.txt")); boolean more = true;//it is a flag used if we encounter more entries than the initial capture JSONArray array = new JSONArray();//it is going to be our final total json array JSONObject jsonObject = new JSONObject();//it is going to be our final total json object while (more) { for (Record rec : listRecords.asList()) { VivlioCrawlerMavenMain vc = new VivlioCrawlerMavenMain(); Element metadata = rec.getMetadata(); if (metadata != null) { //System.out.println(rec.getMetadataAsString()); List<Element> elements = metadata.elements(); //System.out.println(metadata.getStringValue()); for (Element element : elements) { String name = element.getName(); //we get the title, remove \r, \n and beginning and trailing whitespace if (name.equalsIgnoreCase("title")) { vc.title = element.getStringValue(); vc.title = vc.title.trim(); vc.title = vc.title.replaceAll("(\\r|\\n)", ""); if (!(vc.title.endsWith("."))) { vc.title = vc.title + ".";//we also add dot in the end for the titles to be uniformed } } if (name.equalsIgnoreCase("creator")) { vc.creators.add(element.getStringValue());//we capture the students' names } if (name.equalsIgnoreCase("subject")) { vc.subjects.add(element.getStringValue());//we capture the subjects } if (name.equalsIgnoreCase("description")) { vc.description = element.getStringValue();//we capture the abstract } if (name.equalsIgnoreCase("date")) { vc.datestring = element.getStringValue(); } if (name.equalsIgnoreCase("identifier")) { if (element.getStringValue().contains("http://")) { vc.thesisFiles.add(element.getStringValue());//we capture the url of the thesis whole file if (vc.thesisURL == null) { vc.thesisURL = element.getStringValue().substring(0, 32); } } //if the identifier contains the title then it must be the citation //out of the citation we need to extract the supevisor's name if (element.getStringValue().contains(vc.title.substring(0, 10))) { vc.citation = element.getStringValue(); vc.supervisor = element.getStringValue(); Iterator profsIterator = profs.iterator(); vc.supervisor = vc.supervisor.replace(vc.title, "");//we remove the title out of the citation //if we have two students we remove the first occurence of "" which stands for "and" if (vc.creators.size() == 2) { vc.supervisor = vc.supervisor.replaceFirst("", ""); } //we remove the students' names Iterator creatorsIterator = vc.creators.iterator(); while (creatorsIterator.hasNext()) { vc.supervisor = vc.supervisor.replace(creatorsIterator.next().toString(), ""); } boolean profFlag = false;//flag used that declares that we found the professor that was supervisor while (profsIterator.hasNext() && !profFlag) { String prof = profsIterator.next().toString(); //we split the professor's name to surname and name //because some entries have first the surname and others first the name String[] profSplitted = prof.split("\\s+"); String supervisorCleared = vc.supervisor; supervisorCleared = supervisorCleared.replaceAll("\\s+", "");//we clear the white space supervisorCleared = supervisorCleared.replaceAll("(\\r|\\n)", "");//we remove the \r\n //now we check if the citation includes any name of the professors from the txt if (supervisorCleared.contains(profSplitted[0]) && supervisorCleared.contains(profSplitted[1])) { vc.supervisor = prof; profFlag = true; } } //if we don't find the name of the supervisor, we have to perform string manipulation to extract it if (!profFlag) { vc.supervisor = vc.supervisor.trim(); //we remove the word "" which stands for "Thessaloniki" and "" which stands for Greece if (vc.supervisor.contains("")) { vc.supervisor = vc.supervisor.replaceFirst("", ""); } if (vc.supervisor.contains("")) { vc.supervisor = vc.supervisor.replaceFirst("", ""); } if (vc.supervisor.contains("")) { vc.supervisor = vc.supervisor.replaceFirst("", ""); } if (vc.supervisor.contains("")) { vc.supervisor = vc.supervisor.replaceFirst("", ""); } //we remove the year and then we should be left only with the supervisor's name vc.supervisor = vc.supervisor.replace("(", ""); vc.supervisor = vc.supervisor.trim(); vc.supervisor = vc.supervisor.replace(")", ""); vc.supervisor = vc.supervisor.trim(); vc.supervisor = vc.supervisor.replace(",", ""); vc.supervisor = vc.supervisor.trim(); vc.supervisor = vc.supervisor.replace(".", ""); vc.supervisor = vc.supervisor.trim(); vc.supervisor = vc.supervisor.replace(vc.datestring.substring(0, 4), ""); vc.supervisor = vc.supervisor.trim(); } //we put everything in a json object JSONObject obj = new JSONObject(); obj.put("title", vc.title); obj.put("description", vc.description); JSONArray creatorsArray = new JSONArray(); creatorsArray.add(vc.creators); obj.put("creators", creatorsArray); JSONArray subjectsArray = new JSONArray(); List<String> subjectsList = new ArrayList<String>(vc.subjects); subjectsArray.add(subjectsList); obj.put("subjects", subjectsArray); obj.put("datestring", vc.datestring); JSONArray thesisFilesArray = new JSONArray(); thesisFilesArray.add(vc.thesisFiles); obj.put("thesisFiles", thesisFilesArray); obj.put("thesisURL", vc.thesisURL); obj.put("supervisor", vc.supervisor); obj.put("citation", vc.citation); //if you are using JSON.simple do this array.add(obj); } } } listtotal.add(vc);//a list containing all the objects //it is not used for now, but created for potential extension of the work } } //the following if clause searches for new records if (listRecords.getResumptionToken() != null) { listRecords = server.listRecords(listRecords.getResumptionToken()); } else { more = false; } } //we print which records did not have a supervisor for (VivlioCrawlerMavenMain vctest : listtotal) { if (vctest.supervisor == null) { System.out.println(vctest.title); System.out.println(vctest.citation); } } //we create a pretty json with GSON and we write it into a file jsonObject.put("VivliothmmyOldArray", array); JsonParser parser = new JsonParser(); JsonObject json = parser.parse(jsonObject.toJSONString()).getAsJsonObject(); Gson gson = new GsonBuilder().setPrettyPrinting().create(); String prettyJson = gson.toJson(json); try { FileWriter file = new FileWriter( "/home/themis/NetBeansProjects/VivlioCrawlerMaven/src/main/java/com/thesmartweb/vivliocrawlermaven/VivliothmmyOldRecords.json"); file.write(prettyJson); file.flush(); file.close(); } catch (IOException e) { System.out.println("Exception: " + e); } //System.out.print(prettyJson); //int j=0; } catch (OAIException | IOException e) { System.out.println("Exception: " + e); } }