List of usage examples for java.lang String equalsIgnoreCase
public boolean equalsIgnoreCase(String anotherString)
From source file:edu.asu.bscs.csiebler.waypointapplication.WaypointServerStub.java
/** * * @param args/*from ww w . java2s . c o m*/ */ public static void main(String args[]) { try { String url = "http://127.0.0.1:8080/"; if (args.length > 0) { url = args[0]; } WaypointServerStub cjc = new WaypointServerStub(url); BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in)); System.out.print( "Enter end or {remove|get|getNames|getCategoryNames|getNamesInCategory|dist|bear} arg1 arg2 eg remove Toreros >"); String inStr = stdin.readLine(); StringTokenizer st = new StringTokenizer(inStr); String opn = st.nextToken(); while (!opn.equalsIgnoreCase("end")) { switch (opn) { case "remove": { boolean result = cjc.remove(st.nextToken()); System.out.println("response: " + result); break; } case "get": { Waypoint result = cjc.get(st.nextToken()); System.out.println("response: " + result.toJsonString()); break; } case "getNames": { String[] result = cjc.getNames(); for (int i = 0; i < result.length; i++) { System.out.println("response[" + i + "] is " + result[i]); } break; } case "getCategoryNames": { String[] result = cjc.getCategoryNames(); for (int i = 0; i < result.length; i++) { System.out.println("response[" + i + "] is " + result[i]); } break; } case "getNamesInCategory": { String[] result = cjc.getNamesInCategory(st.nextToken()); for (int i = 0; i < result.length; i++) { System.out.println("response[" + i + "] is " + result[i]); } break; } case "dist": { double result = cjc.distanceGCTo(st.nextToken(), st.nextToken()); System.out.println("response: " + result); break; } case "bear": { double result = cjc.bearingGCInitTo(st.nextToken(), st.nextToken()); System.out.println("response: " + result); break; } default: { break; } } System.out.print( "Enter end or {remove|get|getNames|getCategoryNames|getNamesInCategory|dist|bear} arg1 arg2 eg remove Toreros >"); inStr = stdin.readLine(); st = new StringTokenizer(inStr); opn = st.nextToken(); } } catch (Exception e) { System.out.println("Oops, you didn't enter the right stuff"); } }
From source file:net.k3rnel.arena.server.GameServer.java
/** * If you don't know what this method does, you clearly don't know enough Java to be working on this. * @param args//from ww w . ja va 2 s.c o m */ public static void main(String[] args) { /* * Pipe errors to a file */ try { PrintStream p = new PrintStream(new File("./errors.txt")); System.setErr(p); } catch (Exception e) { e.printStackTrace(); } /* * Server settings */ Options options = new Options(); options.addOption("s", "settings", true, "Can be low, medium, or high."); options.addOption("p", "players", true, "Sets the max number of players."); options.addOption("ng", "nogui", false, "Starts server in headless mode."); options.addOption("ar", "autorun", false, "Runs without asking a single question."); options.addOption("h", "help", false, "Shows this menu."); if (args.length > 0) { CommandLineParser parser = new GnuParser(); try { // parse the command line arguments CommandLine line = parser.parse(options, args); /* * The following sets the server's settings based on the * computing ability of the server specified by the server owner. */ if (line.hasOption("settings")) { String settings = line.getOptionValue("settings"); if (settings.equalsIgnoreCase("low")) { m_movementThreads = 4; } else if (settings.equalsIgnoreCase("medium")) { m_movementThreads = 8; } else if (settings.equalsIgnoreCase("high")) { m_movementThreads = 12; } else { System.err.println("Server requires a settings parameter"); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("java GameServer [param] <args>", options); System.exit(0); } } else { System.err.println("Server requires a settings parameter"); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("java GameServer [param] <args>", options); System.exit(0); } if (line.hasOption("players")) { m_maxPlayers = Integer.parseInt(line.getOptionValue("players")); if (m_maxPlayers == 0 || m_maxPlayers == -1) m_maxPlayers = 99999; } else { System.err.println("WARNING: No maximum player count provided. Will default to 500 players."); m_maxPlayers = 500; } if (line.hasOption("help")) { HelpFormatter formatter = new HelpFormatter(); System.err.println("Server requires a settings parameter"); formatter.printHelp("java GameServer [param] <args>", options); } /* * Create the server gui */ @SuppressWarnings("unused") GameServer gs; if (line.hasOption("nogui")) { if (line.hasOption("autorun")) gs = new GameServer(true); else gs = new GameServer(false); } else { if (line.hasOption("autorun")) System.out.println("autorun doesn't work with GUI"); gs = new GameServer(false); } } catch (ParseException exp) { // oops, something went wrong System.err.println("Parsing failed. Reason: " + exp.getMessage()); // automatically generate the help statement HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("java GameServer [param] <args>", options); } } else { // automatically generate the help statement HelpFormatter formatter = new HelpFormatter(); System.err.println("Server requires a settings parameter"); formatter.printHelp("java GameServer [param] <args>", options); } }
From source file:ExecSQL.java
public static void main(String args[]) { try {//from w ww . j ava 2 s . c o m Scanner in; if (args.length == 0) in = new Scanner(System.in); else in = new Scanner(new File(args[0])); Connection conn = getConnection(); try { Statement stat = conn.createStatement(); while (true) { if (args.length == 0) System.out.println("Enter command or EXIT to exit:"); if (!in.hasNextLine()) return; String line = in.nextLine(); if (line.equalsIgnoreCase("EXIT")) return; if (line.trim().endsWith(";")) // remove trailing semicolon { line = line.trim(); line = line.substring(0, line.length() - 1); } try { boolean hasResultSet = stat.execute(line); if (hasResultSet) showResultSet(stat); } catch (SQLException ex) { for (Throwable e : ex) e.printStackTrace(); } } } finally { conn.close(); } } catch (SQLException e) { for (Throwable t : e) t.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
From source file:edu.uci.ics.crawler4j.weatherCrawler.BasicCrawlController.java
public static void main(String[] args) { String folder = ConfigUtils.getFolder(); String crawlerCount = ConfigUtils.getCrawlerCount(); args = new String[2]; if (StringUtils.isBlank(folder) || StringUtils.isBlank(crawlerCount)) { args[0] = "weather"; args[1] = "10"; System.out.println("No parameters in config.properties ......."); System.out.println("[weather] will be used as rootFolder (it will contain intermediate crawl data)"); System.out.println("[10] will be used as numberOfCralwers (number of concurrent threads)"); } else {/* ww w .j ava 2s . co m*/ args[0] = folder; args[1] = crawlerCount; } /* * crawlStorageFolder is a folder where intermediate crawl data is * stored. */ String crawlStorageFolder = args[0]; /* * numberOfCrawlers shows the number of concurrent threads that should * be initiated for crawling. */ int numberOfCrawlers = Integer.parseInt(args[1]); CrawlConfig config = new CrawlConfig(); if (crawlStorageFolder != null && IO.deleteFolderContents(new File(crawlStorageFolder))) System.out.println(""); config.setCrawlStorageFolder(crawlStorageFolder + "/d" + System.currentTimeMillis()); /* * Be polite: Make sure that we don't send more than 1 request per * second (1000 milliseconds between requests). */ config.setPolitenessDelay(1000); config.setConnectionTimeout(1000 * 60); // config1.setPolitenessDelay(1000); /* * You can set the maximum crawl depth here. The default value is -1 for * unlimited depth */ config.setMaxDepthOfCrawling(StringUtils.isBlank(ConfigUtils.getCrawlerDepth()) ? 40 : Integer.valueOf(ConfigUtils.getCrawlerDepth())); // config1.setMaxDepthOfCrawling(0); /* * You can set the maximum number of pages to crawl. The default value * is -1 for unlimited number of pages */ config.setMaxPagesToFetch(100000); // config1.setMaxPagesToFetch(10000); /* * Do you need to set a proxy? If so, you can use: * config.setProxyHost("proxyserver.example.com"); * config.setProxyPort(8080); * * If your proxy also needs authentication: * config.setProxyUsername(username); config.getProxyPassword(password); */ if (ConfigUtils.getValue("useProxy", "false").equalsIgnoreCase("true")) { System.out.println("?============"); List<ProxySetting> proxys = ConfigUtils.getProxyList(); ProxySetting proxy = proxys.get(RandomUtils.nextInt(proxys.size() - 1)); /* test the proxy is alaviable or not */ while (!TestProxy.testProxyAvailable(proxy)) { proxy = proxys.get(RandomUtils.nextInt(proxys.size() - 1)); } System.out.println("??" + proxy.getIp() + ":" + proxy.getPort()); config.setProxyHost(proxy.getIp()); config.setProxyPort(proxy.getPort()); // config.setProxyHost("127.0.0.1"); // config.setProxyPort(8087); } else { System.out.println("??============"); } /* * This config parameter can be used to set your crawl to be resumable * (meaning that you can resume the crawl from a previously * interrupted/crashed crawl). Note: if you enable resuming feature and * want to start a fresh crawl, you need to delete the contents of * rootFolder manually. */ config.setResumableCrawling(false); // config1.setResumableCrawling(false); /* * Instantiate the controller for this crawl. */ PageFetcher pageFetcher = new PageFetcher(config); // PageFetcher pageFetcher1 = new PageFetcher(config1); RobotstxtConfig robotstxtConfig = new RobotstxtConfig(); RobotstxtServer robotstxtServer = new RobotstxtServer(robotstxtConfig, pageFetcher); try { /* * For each crawl, you need to add some seed urls. These are the * first URLs that are fetched and then the crawler starts following * links which are found in these pages */ CrawlController controller = new CrawlController(config, pageFetcher, robotstxtServer); controller.addSeed(StringUtils.isBlank(ConfigUtils.getSeed()) ? "http://www.tianqi.com/chinacity.html" : ConfigUtils.getSeed()); // controller.addSeed("http://www.ics.uci.edu/~lopes/"); // controller.addSeed("http://www.ics.uci.edu/~welling/"); /* * Start the crawl. This is a blocking operation, meaning that your * code will reach the line after this only when crawling is * finished. */ String isDaily = null; isDaily = ConfigUtils.getValue("isDaily", "true"); System.out .println("?=======" + ConfigUtils.getValue("table", "weather_data") + "======="); if (isDaily.equalsIgnoreCase("true")) { System.out.println("???=============="); controller.start(BasicDailyCrawler.class, numberOfCrawlers); } else { System.out.println("???=============="); controller.start(BasicCrawler.class, numberOfCrawlers); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } }
From source file:com.imaginary.home.cloud.api.call.LocationCall.java
static public void main(String... args) throws Exception { if (args.length < 1) { System.err.println("You must specify an action"); System.exit(-1);//from w ww . j av a 2 s . c om return; } String action = args[0]; if (action.equalsIgnoreCase("initializePairing")) { if (args.length < 5) { System.err.println("You must specify a location ID"); System.exit(-2); return; } String endpoint = args[1]; String locationId = args[2]; String apiKeyId = args[3]; String apiKeySecret = args[4]; HashMap<String, Object> act = new HashMap<String, Object>(); act.put("action", "initializePairing"); HttpParams params = new BasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); //noinspection deprecation HttpProtocolParams.setContentCharset(params, HTTP.UTF_8); HttpProtocolParams.setUserAgent(params, "Imaginary Home"); HttpClient client = new DefaultHttpClient(params); HttpPut method = new HttpPut(endpoint + "/location/" + locationId); long timestamp = System.currentTimeMillis(); method.addHeader("Content-Type", "application/json"); method.addHeader("x-imaginary-version", CloudService.VERSION); method.addHeader("x-imaginary-timestamp", String.valueOf(timestamp)); method.addHeader("x-imaginary-api-key", apiKeyId); method.addHeader("x-imaginary-signature", CloudService.sign(apiKeySecret.getBytes("utf-8"), "put:/location/" + locationId + ":" + apiKeyId + ":" + timestamp + ":" + CloudService.VERSION)); //noinspection deprecation method.setEntity(new StringEntity((new JSONObject(act)).toString(), "application/json", "UTF-8")); HttpResponse response; StatusLine status; try { response = client.execute(method); status = response.getStatusLine(); } catch (IOException e) { e.printStackTrace(); throw new CommunicationException(e); } if (status.getStatusCode() == HttpServletResponse.SC_OK) { String json = EntityUtils.toString(response.getEntity()); JSONObject u = new JSONObject(json); System.out.println((u.has("pairingCode") && !u.isNull("pairingCode")) ? u.getString("pairingCode") : "--no code--"); } else { System.err.println("Failed to initialize pairing (" + status.getStatusCode() + ": " + EntityUtils.toString(response.getEntity())); System.exit(status.getStatusCode()); } } else if (action.equalsIgnoreCase("create")) { if (args.length < 7) { System.err.println("create ENDPOINT NAME DESCRIPTION TIMEZONE API_KEY_ID API_KEY_SECRET"); System.exit(-2); return; } String endpoint = args[1]; String name = args[2]; String description = args[3]; String tz = args[4]; String apiKeyId = args[5]; String apiKeySecret = args[6]; HashMap<String, Object> lstate = new HashMap<String, Object>(); lstate.put("name", name); lstate.put("description", description); lstate.put("timeZone", tz); HttpParams params = new BasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); //noinspection deprecation HttpProtocolParams.setContentCharset(params, HTTP.UTF_8); HttpProtocolParams.setUserAgent(params, "Imaginary Home"); HttpClient client = new DefaultHttpClient(params); HttpPost method = new HttpPost(endpoint + "/location"); long timestamp = System.currentTimeMillis(); System.out.println( "Signing: " + "post:/location:" + apiKeyId + ":" + timestamp + ":" + CloudService.VERSION); method.addHeader("Content-Type", "application/json"); method.addHeader("x-imaginary-version", CloudService.VERSION); method.addHeader("x-imaginary-timestamp", String.valueOf(timestamp)); method.addHeader("x-imaginary-api-key", apiKeyId); method.addHeader("x-imaginary-signature", CloudService.sign(apiKeySecret.getBytes("utf-8"), "post:/location:" + apiKeyId + ":" + timestamp + ":" + CloudService.VERSION)); //noinspection deprecation method.setEntity(new StringEntity((new JSONObject(lstate)).toString(), "application/json", "UTF-8")); HttpResponse response; StatusLine status; try { response = client.execute(method); status = response.getStatusLine(); } catch (IOException e) { e.printStackTrace(); throw new CommunicationException(e); } if (status.getStatusCode() == HttpServletResponse.SC_CREATED) { String json = EntityUtils.toString(response.getEntity()); JSONObject u = new JSONObject(json); System.out.println((u.has("locationId") && !u.isNull("locationId")) ? u.getString("locationId") : "--no location--"); } else { System.err.println("Failed to create location (" + status.getStatusCode() + ": " + EntityUtils.toString(response.getEntity())); System.exit(status.getStatusCode()); } } else { System.err.println("No such action: " + action); System.exit(-3); } }
From source file:com.kylinolap.metadata.tool.HiveSourceTableMgmt.java
/** * @param args/*from w w w .j a va 2 s . com*/ * HiveSourceTableMgmt jdbc:hive2://kylin-local:10000/default, * hive, hive, c:\\temp [, name] */ public static void main(String[] args) { if (args.length < 3) { System.out.println("Wrong arguments, example"); System.out.println("Get data from command: -c Kylin*, c:\\temp"); System.out.println("Get data from outputfile: -f /tmp/hiveout.txt, c:\\temp"); System.exit(1); } String mode = args[0]; String tableMetaOutcomeDir = args[2]; HiveSourceTableMgmt rssMgmt = new HiveSourceTableMgmt(); try { if (mode.equalsIgnoreCase("-c")) { rssMgmt.extractTableDescWithTablePattern(args[1], tableMetaOutcomeDir); } if (mode.equalsIgnoreCase("-f")) { rssMgmt.extractTableDescFromFile(args[1], tableMetaOutcomeDir); } } catch (IllegalArgumentException e) { e.printStackTrace(); } }
From source file:dk.netarkivet.harvester.tools.CreateIndex.java
/** * The main method that does the parsing of the commandline, and makes the actual index request. * * @param args the arguments/*from w ww . j ava 2 s .c o m*/ */ public static void main(String[] args) { Options options = new Options(); CommandLineParser parser = new PosixParser(); CommandLine cmd = null; Option indexType = new Option("t", "type", true, "Type of index"); Option jobList = new Option("l", "jobids", true, "list of jobids"); indexType.setRequired(true); jobList.setRequired(true); options.addOption(indexType); options.addOption(jobList); try { // parse the command line arguments cmd = parser.parse(options, args); } catch (MissingOptionException e) { System.err.println("Some of the required parameters are missing: " + e.getMessage()); dieWithUsage(); } catch (ParseException exp) { System.err.println("Parsing of parameters failed: " + exp.getMessage()); dieWithUsage(); } String typeValue = cmd.getOptionValue(INDEXTYPE_OPTION); String jobidsValue = cmd.getOptionValue(JOBIDS_OPTION); String[] jobidsAsStrings = jobidsValue.split(","); Set<Long> jobIDs = new HashSet<Long>(); for (String idAsString : jobidsAsStrings) { jobIDs.add(Long.valueOf(idAsString)); } JobIndexCache cache = null; String indexTypeAstring = ""; if (typeValue.equalsIgnoreCase("CDX")) { indexTypeAstring = "CDX"; cache = IndexClientFactory.getCDXInstance(); } else if (typeValue.equalsIgnoreCase("DEDUP")) { indexTypeAstring = "DEDUP"; cache = IndexClientFactory.getDedupCrawllogInstance(); } else if (typeValue.equalsIgnoreCase("CRAWLLOG")) { indexTypeAstring = "CRAWLLOG"; cache = IndexClientFactory.getFullCrawllogInstance(); } else { System.err.println("Unknown indextype '" + typeValue + "' requested."); dieWithUsage(); } System.out.println("Creating " + indexTypeAstring + " index for ids: " + jobIDs); Index<Set<Long>> index = cache.getIndex(jobIDs); JMSConnectionFactory.getInstance().cleanup(); }
From source file:knowledgeMiner.mining.SentenceParserHeuristic.java
public static void main(String[] args) throws Exception { ResourceAccess.newInstance();/*from ww w . j ava2 s . c om*/ CycMapper mapper = new CycMapper(); CycMiner miner = new CycMiner(null, mapper); SentenceParserHeuristic sph = new SentenceParserHeuristic(mapper, miner); WMISocket wmi = ResourceAccess.requestWMISocket(); OntologySocket cyc = ResourceAccess.requestOntologySocket(); String input = ""; MappableConcept mappable = new TextMappedConcept("PLACEHOLDER", false, false); while (!input.equalsIgnoreCase("exit")) { System.out.println("Enter sentence to parse:"); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); input = in.readLine(); Collection<PartialAssertion> assertions = sph.extractAssertions(input, mappable, true, wmi, cyc, null); System.out.println(assertions); } }
From source file:com.thesmartweb.vivliocrawlermaven.VivlioCrawlerMavenMain.java
/** * @param args the command line arguments *///from www .ja va2s .c o 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); } }
From source file:cc.twittertools.search.local.SearchStatuses.java
@SuppressWarnings("static-access") public static void main(String[] args) throws Exception { Options options = new Options(); options.addOption(/*from www .j a va2s . c o m*/ OptionBuilder.withArgName("path").hasArg().withDescription("index location").create(INDEX_OPTION)); options.addOption( OptionBuilder.withArgName("string").hasArg().withDescription("query id").create(QID_OPTION)); options.addOption( OptionBuilder.withArgName("string").hasArg().withDescription("query text").create(QUERY_OPTION)); options.addOption( OptionBuilder.withArgName("string").hasArg().withDescription("runtag").create(RUNTAG_OPTION)); options.addOption(OptionBuilder.withArgName("num").hasArg().withDescription("maxid").create(MAX_ID_OPTION)); options.addOption(OptionBuilder.withArgName("num").hasArg().withDescription("number of results to return") .create(NUM_RESULTS_OPTION)); options.addOption(OptionBuilder.withArgName("similarity").hasArg() .withDescription("similarity to use (BM25, LM)").create(SIMILARITY_OPTION)); options.addOption(new Option(VERBOSE_OPTION, "print out complete document")); CommandLine cmdline = null; CommandLineParser parser = new GnuParser(); try { cmdline = parser.parse(options, args); } catch (ParseException exp) { System.err.println("Error parsing command line: " + exp.getMessage()); System.exit(-1); } if (!cmdline.hasOption(QUERY_OPTION) || !cmdline.hasOption(INDEX_OPTION)) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(SearchStatuses.class.getName(), options); System.exit(-1); } File indexLocation = new File(cmdline.getOptionValue(INDEX_OPTION)); if (!indexLocation.exists()) { System.err.println("Error: " + indexLocation + " does not exist!"); System.exit(-1); } String qid = cmdline.hasOption(QID_OPTION) ? cmdline.getOptionValue(QID_OPTION) : DEFAULT_QID; String queryText = cmdline.hasOption(QUERY_OPTION) ? cmdline.getOptionValue(QUERY_OPTION) : DEFAULT_Q; String runtag = cmdline.hasOption(RUNTAG_OPTION) ? cmdline.getOptionValue(RUNTAG_OPTION) : DEFAULT_RUNTAG; long maxId = cmdline.hasOption(MAX_ID_OPTION) ? Long.parseLong(cmdline.getOptionValue(MAX_ID_OPTION)) : DEFAULT_MAX_ID; int numResults = cmdline.hasOption(NUM_RESULTS_OPTION) ? Integer.parseInt(cmdline.getOptionValue(NUM_RESULTS_OPTION)) : DEFAULT_NUM_RESULTS; boolean verbose = cmdline.hasOption(VERBOSE_OPTION); String similarity = "LM"; if (cmdline.hasOption(SIMILARITY_OPTION)) { similarity = cmdline.getOptionValue(SIMILARITY_OPTION); } PrintStream out = new PrintStream(System.out, true, "UTF-8"); IndexReader reader = DirectoryReader.open(FSDirectory.open(indexLocation)); IndexSearcher searcher = new IndexSearcher(reader); if (similarity.equalsIgnoreCase("BM25")) { searcher.setSimilarity(new BM25Similarity()); } else if (similarity.equalsIgnoreCase("LM")) { searcher.setSimilarity(new LMDirichletSimilarity(2500.0f)); } QueryParser p = new QueryParser(Version.LUCENE_43, IndexStatuses.StatusField.TEXT.name, IndexStatuses.ANALYZER); Query query = p.parse(queryText); Filter filter = NumericRangeFilter.newLongRange(StatusField.ID.name, 0L, maxId, true, true); TopDocs rs = searcher.search(query, filter, numResults); int i = 1; for (ScoreDoc scoreDoc : rs.scoreDocs) { Document hit = searcher.doc(scoreDoc.doc); out.println(String.format("%s Q0 %s %d %f %s", qid, hit.getField(StatusField.ID.name).numericValue(), i, scoreDoc.score, runtag)); if (verbose) { out.println("# " + hit.toString().replaceAll("[\\n\\r]+", " ")); } i++; } reader.close(); out.close(); }