List of usage examples for java.util.logging Level SEVERE
Level SEVERE
To view the source code for java.util.logging Level SEVERE.
Click Source Link
From source file:my.yelp.populate.java
public static void main(String[] args) throws FileNotFoundException, ParseException, IOException, java.text.ParseException { try {/* w w w .j a v a2 s . co m*/ DbConnection A1 = new DbConnection(); Connection con = A1.getConnection(); JSONParser jsonParser; jsonParser = new JSONParser(); Object obj1 = jsonParser.parse(new FileReader("C:\\Users\\Sanjay Desai\\Desktop\\yelp_user.json")); Object obj2 = jsonParser.parse(new FileReader("C:\\Users\\Sanjay Desai\\Desktop\\yelp_business.json")); Object obj3 = jsonParser.parse(new FileReader("C:\\Users\\Sanjay Desai\\Desktop\\yelp_review.json")); Object obj4 = jsonParser.parse(new FileReader("C:\\Users\\Sanjay Desai\\Desktop\\yelp_checkin.json")); JSONArray jsonArray1; jsonArray1 = (JSONArray) obj1; JSONArray jsonArray2; jsonArray2 = (JSONArray) obj2; JSONArray jsonArray3; jsonArray3 = (JSONArray) obj3; JSONArray jsonArray4; jsonArray4 = (JSONArray) obj4; // yelp_user String yelping_since, name1, user_id, type1; Long review_count1, fans; Double average_stars; Statement stmt; stmt = con.createStatement(); stmt.executeUpdate("Delete from N_User"); for (int i = 0; i < (jsonArray1.size()); i++) { JSONObject jsonObject = (JSONObject) jsonArray1.get(i); yelping_since = (String) jsonObject.get("yelping_since") + "-01"; JSONArray friends = (JSONArray) jsonObject.get("friends"); int friends_size = friends.size(); review_count1 = (Long) jsonObject.get("review_count"); name1 = (String) jsonObject.get("name"); user_id = (String) jsonObject.get("user_id"); fans = (Long) jsonObject.get("fans"); average_stars = (Double) jsonObject.get("average_stars"); type1 = (String) jsonObject.get("type"); try (PreparedStatement pstmt1 = con.prepareStatement( "Insert INTO N_User(yelping_since,friends_size,review_count,name,user_id,fans,average_stars,type) VALUES(?,?,?,?,?,?,?,?)")) { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); java.util.Date myDate = format.parse(yelping_since); pstmt1.setDate(1, new java.sql.Date(myDate.getTime())); pstmt1.setInt(2, friends_size); pstmt1.setLong(3, review_count1); pstmt1.setString(4, name1); pstmt1.setString(5, user_id); pstmt1.setLong(6, fans); pstmt1.setDouble(7, average_stars); pstmt1.setString(8, type1); pstmt1.executeUpdate(); } catch (java.text.ParseException ex) { Logger.getLogger(populate.class.getName()).log(Level.SEVERE, null, ex); } } //yelp_business String business_id, address, city, state, name, type_business; Double stars; for (int i = 0; i < jsonArray2.size(); i++) { JSONObject jsonObject = (JSONObject) jsonArray2.get(i); business_id = (String) jsonObject.get("business_id"); address = (String) jsonObject.get("full_address"); city = (String) jsonObject.get("city"); state = (String) jsonObject.get("state"); name = (String) jsonObject.get("name"); stars = (Double) jsonObject.get("stars"); type_business = (String) jsonObject.get("type"); try (PreparedStatement pstmt2 = con.prepareStatement( "Insert INTO N_Business(business_id,address,city,state,name,stars,type_business) VALUES(?,?,?,?,?,?,?)")) { pstmt2.setString(1, business_id); pstmt2.setString(2, address); pstmt2.setString(3, city); pstmt2.setString(4, state); pstmt2.setString(5, name); pstmt2.setDouble(6, stars); pstmt2.setString(7, type_business); pstmt2.executeUpdate(); pstmt2.close(); } } //Category Table String[] categories = { "Active Life", "Arts & Entertainment", "Automotive", "Car Rental", "Cafes", "Beauty & Spas", "Convenience Stores", "Dentists", "Doctors", "Drugstores", "Department Stores", "Education", "Event Planning & Services", "Flowers & Gifts", "Food", "Health & Medical", "Home Services", "Home & Garden", "Hospitals", "Hotels & travel", "Hardware stores", "Grocery", "Medical Centers", "Nurseries & Gardening", "Nightlife", "Restaurants", "Shopping", "Transportation" }; JSONArray category; String[] individual_category = new String[100]; int count = 0, flag = 0, m = 0, n = 0; String[] business_category = new String[50]; String[] subcategory = new String[50]; for (int i = 0; i < jsonArray2.size(); i++) { JSONObject jsonObject3 = (JSONObject) jsonArray2.get(i); String business_id2 = (String) jsonObject3.get("business_id"); category = (JSONArray) jsonObject3.get("categories"); for (int j = 0; j < category.size(); j++) { individual_category[j] = (String) category.get(j); count = count + 1; } for (int k = 0; k < count; k++) { for (String categorie : categories) { if (individual_category[k].equals(categorie)) { flag = 1; break; } } if (flag == 1) { business_category[m] = individual_category[k]; m = m + 1; flag = 0; } else { subcategory[n] = individual_category[k]; n = n + 1; } } for (int p = 0; p < m; p++) { for (int q = 0; q < n; q++) { try (PreparedStatement pstmt3 = con.prepareStatement( "INSERT INTO N_Category(business_id,category,subcategory) VALUES(?,?,?)")) { pstmt3.setString(1, business_id2); pstmt3.setString(2, business_category[p]); pstmt3.setString(3, subcategory[q]); pstmt3.executeUpdate(); } } } count = 0; m = 0; n = 0; } //yelp_review String user_id3, review_id, type3, business_id3, text, text1, review_date; Long stars3; int votes = 0; Integer no_votes; JSONObject votes_info; Set<String> keys; for (int i = 0; i < jsonArray3.size(); i++) { JSONObject jsonObject = (JSONObject) jsonArray3.get(i); votes_info = (JSONObject) jsonObject.get("votes"); keys = votes_info.keySet(); for (String r_key : keys) { votes = (int) (votes + (Long) votes_info.get(r_key)); } no_votes = toIntExact(votes); user_id3 = (String) jsonObject.get("user_id"); review_id = (String) jsonObject.get("review_id"); business_id3 = (String) jsonObject.get("business_id"); review_date = (String) jsonObject.get("date"); text1 = (String) jsonObject.get("text"); text = text1.substring(0, Math.min(1000, text1.length())); stars3 = (Long) jsonObject.get("stars"); type3 = (String) jsonObject.get("type"); try (PreparedStatement pstmt4 = con.prepareStatement( "Insert INTO N_Review(no_votes,user_id,review_id,business_id,review_date,text,stars,type) VALUES(?,?,?,?,?,?,?,?)")) { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); java.util.Date myDate = format.parse(review_date); pstmt4.setInt(1, no_votes); pstmt4.setString(2, user_id3); pstmt4.setString(3, review_id); pstmt4.setString(4, business_id3); pstmt4.setDate(5, new java.sql.Date(myDate.getTime())); pstmt4.setString(6, text); pstmt4.setLong(7, stars3); pstmt4.setString(8, type3); pstmt4.executeUpdate(); pstmt4.close(); } } //Checkin_Info JSONObject checkin_info; String business_id4; Long check_in_count; Set<String> keys1; String[] timing = new String[10]; int n1 = 0, time, hour; //Inserting into checkin_info for (int i = 0; i < jsonArray4.size(); i++) { JSONObject jsonObject4 = (JSONObject) jsonArray4.get(i); checkin_info = (JSONObject) jsonObject4.get("checkin_info"); business_id4 = (String) jsonObject4.get("business_id"); keys1 = checkin_info.keySet(); for (String key : keys1) { check_in_count = (Long) checkin_info.get(key); for (String x : key.split("-")) { timing[n1] = x; n1 = n1 + 1; } n1 = 0; hour = Integer.parseInt(timing[0]); time = Integer.parseInt(timing[1]); try (PreparedStatement pstmt5 = con.prepareStatement( "INSERT INTO check_info(business_id,hour,day,check_in_count)VALUES(?,?,?,?)")) { pstmt5.setString(1, business_id4); pstmt5.setInt(2, hour); pstmt5.setInt(3, time); pstmt5.setLong(4, check_in_count); pstmt5.executeUpdate(); } } } con.close(); } catch (SQLException ex) { Logger.getLogger(populate.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:net.sf.mpaxs.test.ImpaxsExecution.java
/** * * @param args/*from w w w . j a v a 2 s . co m*/ */ public static void main(String[] args) { Options options = new Options(); Option[] optionArray = new Option[] { OptionBuilder.withArgName("nhosts").hasArg() .withDescription("Number of hosts for parallel processing").create("n"), OptionBuilder.withArgName("mjobs").hasArg().withDescription("Number of jobs to run in parallel") .create("m"), OptionBuilder.withArgName("runmode").hasArg() .withDescription("The mode in which to operate: one of <ALL,LOCAL,DISTRIBUTED>") .create("r"), // OptionBuilder.withArgName("gui"). // withDescription("Create gui for distributed execution").create("g") }; for (Option opt : optionArray) { options.addOption(opt); } if (args.length == 0) { HelpFormatter hf = new HelpFormatter(); hf.printHelp(StartUp.class.getCanonicalName(), options, true); System.exit(1); } GnuParser gp = new GnuParser(); int nhosts = 1; int mjobs = 10; boolean gui = false; Mode mode = Mode.ALL; try { CommandLine cl = gp.parse(options, args); if (cl.hasOption("n")) { nhosts = Integer.parseInt(cl.getOptionValue("n")); } if (cl.hasOption("m")) { mjobs = Integer.parseInt(cl.getOptionValue("m")); } if (cl.hasOption("r")) { mode = Mode.valueOf(cl.getOptionValue("r")); } // if (cl.hasOption("g")) { // gui = true; // } } catch (Exception ex) { Logger.getLogger(StartUp.class.getName()).log(Level.SEVERE, null, ex); HelpFormatter hf = new HelpFormatter(); hf.printHelp(StartUp.class.getCanonicalName(), options, true); System.exit(1); } String version; try { version = net.sf.mpaxs.api.Version.getVersion(); System.out.println("Running mpaxs " + version); File computeHostJarLocation = new File(System.getProperty("user.dir"), "mpaxs.jar"); if (!computeHostJarLocation.exists() || !computeHostJarLocation.isFile()) { throw new IOException("Could not locate mpaxs.jar in " + System.getProperty("user.dir")); } final PropertiesConfiguration cfg = new PropertiesConfiguration(); //set default execution type cfg.setProperty(ConfigurationKeys.KEY_EXECUTION_MODE, ExecutionType.DRMAA); //set location of compute host jar cfg.setProperty(ConfigurationKeys.KEY_PATH_TO_COMPUTEHOST_JAR, computeHostJarLocation); //do not exit to console when master server shuts down cfg.setProperty(ConfigurationKeys.KEY_MASTER_SERVER_EXIT_ON_SHUTDOWN, false); //limit the number of used compute hosts cfg.setProperty(ConfigurationKeys.KEY_MAX_NUMBER_OF_CHOSTS, nhosts); cfg.setProperty(ConfigurationKeys.KEY_NATIVE_SPEC, ""); cfg.setProperty(ConfigurationKeys.KEY_GUI_MODE, gui); cfg.setProperty(ConfigurationKeys.KEY_SILENT_MODE, true); cfg.setProperty(ConfigurationKeys.KEY_SCHEDULE_WAIT_TIME, "500"); final int maxJobs = mjobs; final int maxThreads = nhosts; final Mode runMode = mode; printMessage("Run mode: " + runMode); Executors.newSingleThreadExecutor().submit(new Runnable() { @Override public void run() { if (runMode == Mode.ALL || runMode == Mode.LOCAL) { printMessage("Running Within VM Execution"); /* * LOCAL within VM execution */ WithinVmExecution lhe = new WithinVmExecution(maxJobs, maxThreads); try { Logger.getLogger(ImpaxsExecution.class.getName()).log(Level.INFO, "Sum is: " + lhe.call()); } catch (Exception ex) { Logger.getLogger(ImpaxsExecution.class.getName()).log(Level.SEVERE, null, ex); } } if (runMode == Mode.ALL || runMode == Mode.DISTRIBUTED) { printMessage("Running Distributed Host RMI Execution"); /* * Grid Engine (DRMAA API) or local host distributed RMI execution */ DistributedRmiExecution de = new DistributedRmiExecution(cfg, maxJobs); try { Logger.getLogger(ImpaxsExecution.class.getName()).log(Level.INFO, "Sum is: " + de.call()); } catch (Exception ex) { Logger.getLogger(ImpaxsExecution.class.getName()).log(Level.SEVERE, null, ex); } } System.exit(0); } }); } catch (IOException ex) { Logger.getLogger(ImpaxsExecution.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:de.citec.csra.highlight.HighlightService.java
public static void main(String[] args) throws InitializeException, RSBException, InterruptedException, ParseException { Options opts = new Options(); opts.addOption("scope", true, "RSB scope for highlight targets.\nDefault: '" + scope + "'"); opts.addOption("server", true, "RSB server for configuration, e.g., tokens.\nDefault: '" + cfg + "'"); opts.addOption("help", false, "Print this help and exit"); String footer = null;/*w w w . j a v a 2 s. c om*/ // String footer = "\nThe following sub-scopes are registered automatically:\n" // + "\n.../preset for color presets:\n" + Arrays.toString(ColorConfig.values()) // + "\n.../color for color values:\n" + "HSV (comma separated)" // + "\n.../power for power states:\n" + Arrays.toString(PowerState.State.values()) // + "\n.../history for history commands:\n" + Arrays.toString(ColorHistory.values()); CommandLineParser parser = new BasicParser(); CommandLine cmd = parser.parse(opts, args); if (cmd.hasOption("help")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("csra-highlight-service [OPTION...]", "where OPTION includes:", opts, footer); System.exit(0); } if (System.getenv().containsKey(SCOPEVAR)) { scope = System.getenv(SCOPEVAR); } String s = cmd.getOptionValue("scope"); if (s != null) { scope = s; } scope = scope.replaceAll("/$", ""); String c = cmd.getOptionValue("cfg"); if (c != null) { cfg = c; } cfg = cfg.replaceAll("/$", ""); Defaults.loadDefaults(); ExecutorService exec = Executors.newFixedThreadPool(2); exec.submit(() -> { try { ConfigServer cfgServer = new ConfigServer(cfg); cfgServer.execute(); } catch (RSBException ex) { LOG.log(Level.SEVERE, "Config server failed", ex); } }); exec.submit(() -> { try { TaskServer server = new TaskServer(scope, new HighlightTaskHandler()); server.execute(); } catch (RSBException | InterruptedException ex) { LOG.log(Level.SEVERE, "Task server failed", ex); } }); }
From source file:eu.interedition.collatex.http.Server.java
public static void main(String... args) { try {// w w w . j a v a2 s.c om final CommandLine commandLine = new GnuParser().parse(OPTIONS, args); if (commandLine.hasOption("h")) { new HelpFormatter().printHelp("collatex-server [<options> ...]\n", OPTIONS); return; } final Collator collator = new Collator(Integer.parseInt(commandLine.getOptionValue("mpc", "2")), Integer.parseInt(commandLine.getOptionValue("mcs", "0")), commandLine.getOptionValue("dot", null)); final String staticPath = System.getProperty("collatex.static.path", ""); final HttpHandler httpHandler = staticPath.isEmpty() ? new CLStaticHttpHandler(Server.class.getClassLoader(), "/static/") { @Override protected void onMissingResource(Request request, Response response) throws Exception { collator.service(request, response); } } : new StaticHttpHandler(staticPath.replaceAll("/+$", "") + "/") { @Override protected void onMissingResource(Request request, Response response) throws Exception { collator.service(request, response); } }; final NetworkListener httpListener = new NetworkListener("http", "0.0.0.0", Integer.parseInt(commandLine.getOptionValue("p", "7369"))); final CompressionConfig compressionConfig = httpListener.getCompressionConfig(); compressionConfig.setCompressionMode(CompressionConfig.CompressionMode.ON); compressionConfig.setCompressionMinSize(860); // http://webmasters.stackexchange.com/questions/31750/what-is-recommended-minimum-object-size-for-gzip-performance-benefits compressionConfig.setCompressableMimeTypes("application/javascript", "application/json", "application/xml", "text/css", "text/html", "text/javascript", "text/plain", "text/xml"); final HttpServer httpServer = new HttpServer(); httpServer.addListener(httpListener); httpServer.getServerConfiguration().addHttpHandler(httpHandler, commandLine.getOptionValue("cp", "").replaceAll("/+$", "") + "/*"); Runtime.getRuntime().addShutdownHook(new Thread(() -> { if (LOG.isLoggable(Level.INFO)) { LOG.info("Stopping HTTP server"); } httpServer.shutdown(); })); httpServer.start(); Thread.sleep(Long.MAX_VALUE); } catch (Throwable t) { LOG.log(Level.SEVERE, "Error while parsing command line", t); System.exit(1); } }
From source file:ie.aib.nbp.zosresttest.RunTest.java
/** * @param args the command line arguments */// w ww. ja v a2s . co m public static void main(String[] args) { PrintStream printer = null; if (args.length < 2) { System.out.println("***************************************************************************"); System.out.println("* Z/OS REST SERVICES PERFORMANCE TESTER *"); System.out.println("* *"); System.out.println("* At least 2 run parameters are required: *"); System.out.println("* 1 username: your mainframe username *"); System.out.println("* 2 password: your mainframe passeord *"); System.out.println("* 3 runtime behaviour switch: 1 - active, everything else - inactive *"); System.out.println("* this parameter is optional and causes the app to run the test or not *"); System.out.println("* lack of it assings default value: 0 *"); System.out.println("* which triggers the service discovery feature *"); System.out.println("* and displays all currently available services *"); System.out.println("* 4 output type: *"); System.out.println("* F - output to file (then fifth parameter hold the file location) *"); System.out.println("* Everything else (including no parameter at all) outputs to console *"); System.out.println("***************************************************************************"); return; } readConfig(CONFIG_FILE_PATH); String username = args[0]; String password = args[1]; String runPerformanceTest; try { runPerformanceTest = args[2]; } catch (ArrayIndexOutOfBoundsException ex) { runPerformanceTest = "0"; } String outputType; String outputFileLocation; try { outputType = args[3]; // F saves to file, everything else output to console } catch (ArrayIndexOutOfBoundsException ex) { outputType = "C"; } if (outputType.equalsIgnoreCase("F")) { // write to file String outputFile; try { outputFile = args[4]; // if prev param is F then this one may contain the file name (default name instead) } catch (ArrayIndexOutOfBoundsException ex) { SimpleDateFormat sdf = new SimpleDateFormat("ddMMyyyy-HHmmssZ"); outputFile = "ZosPerformanceTest".concat("-".concat(sdf.format(new Date()))).concat(".txt"); } try { String filePath = config.getProperty("OUT_FILE_PATH").concat(outputFile); printer = new PrintStream(new FileOutputStream(filePath, true)); } catch (FileNotFoundException ex) { Logger.getLogger(RunTest.class.getName()).log(Level.SEVERE, null, ex); } } else { // othewise write to java console printer = new PrintStream(System.out); } if (runPerformanceTest.equals("1")) runPerformanceTest(username, password, printer, true, false); else runServiceDiscovery(username, password, printer); }
From source file:de.fosd.jdime.Main.java
/** * Perform a merge operation on the input files or directories. * * @param args//from w w w. ja v a 2 s.c o m * command line arguments */ public static void main(String[] args) { try { run(args); } catch (AbortException e) { if (e.getCause() != null) { LOG.log(Level.SEVERE, e.getCause(), () -> "Aborting the merge."); } else { System.err.println(e.getMessage()); LOG.log(Level.FINE, e, () -> "Aborting the merge."); } System.exit(EXIT_ABORTED); } catch (Throwable e) { LOG.log(Level.SEVERE, e, () -> "Uncaught exception."); System.exit(EXIT_FAILURE); } }
From source file:cc.redberry.core.performance.StableSort.java
/** * @param args the command line arguments *//*from w w w.j av a 2s . c o m*/ public static void main(String[] args) { try { //burn JVM BitsStreamGenerator bitsStreamGenerator = new Well19937c(); for (int i = 0; i < 1000; ++i) nextArray(1000, bitsStreamGenerator); System.out.println("!"); BufferedWriter timMeanOut = new BufferedWriter( new FileWriter("/home/stas/Projects/stableSort/timMean.dat")); BufferedWriter insertionMeanOut = new BufferedWriter( new FileWriter("/home/stas/Projects/stableSort/insertionMean.dat")); BufferedWriter timMaxOut = new BufferedWriter( new FileWriter("/home/stas/Projects/stableSort/timMax.dat")); BufferedWriter insertionMaxOut = new BufferedWriter( new FileWriter("/home/stas/Projects/stableSort/insertionMax.dat")); BufferedWriter timSigOut = new BufferedWriter( new FileWriter("/home/stas/Projects/stableSort/timSig.dat")); BufferedWriter insertionSigOut = new BufferedWriter( new FileWriter("/home/stas/Projects/stableSort/insertionSig.dat")); DescriptiveStatistics timSort; DescriptiveStatistics insertionSort; int tryies = 200; int arrayLength = 0; for (; arrayLength < 1000; ++arrayLength) { int[] coSort = nextArray(arrayLength, bitsStreamGenerator); timSort = new DescriptiveStatistics(); insertionSort = new DescriptiveStatistics(); for (int i = 0; i < tryies; ++i) { int[] t1 = nextArray(arrayLength, bitsStreamGenerator); int[] t2 = t1.clone(); long start = System.currentTimeMillis(); ArraysUtils.timSort(t1, coSort); long stop = System.currentTimeMillis(); timSort.addValue(stop - start); start = System.currentTimeMillis(); ArraysUtils.insertionSort(t2, coSort); stop = System.currentTimeMillis(); insertionSort.addValue(stop - start); } timMeanOut.write(arrayLength + "\t" + timSort.getMean() + "\n"); insertionMeanOut.write(arrayLength + "\t" + insertionSort.getMean() + "\n"); timMaxOut.write(arrayLength + "\t" + timSort.getMax() + "\n"); insertionMaxOut.write(arrayLength + "\t" + insertionSort.getMax() + "\n"); timSigOut.write(arrayLength + "\t" + timSort.getStandardDeviation() + "\n"); insertionSigOut.write(arrayLength + "\t" + insertionSort.getStandardDeviation() + "\n"); } timMeanOut.close(); insertionMeanOut.close(); timMaxOut.close(); insertionMaxOut.close(); timSigOut.close(); insertionSigOut.close(); } catch (IOException ex) { Logger.getLogger(StableSort.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:com.wso2telco.core.mnc.resolver.MNCQueryClient.java
public static void main(String arg[]) { //IProviderNetwork networkprovider = new DNSSSLQueryClient(); try {/*w w w.ja v a 2 s. c o m*/ String pfapiMnc = new DNSSSLQueryClient().queryNetworkStandalone(String.valueOf(arg[0]), arg[1].substring(arg[0].length())); System.out.println("Mnc:" + pfapiMnc); } catch (Exception ex) { Logger.getLogger(MNCQueryClient.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:ch.epfl.leb.sass.commandline.CommandLineInterface.java
/** * Shows help, launches the interpreter and executes scripts according to input args. * @param args input arguments/* w ww . j a v a 2 s. c om*/ */ public static void main(String args[]) { // parse input arguments CommandLineParser parser = new DefaultParser(); CommandLine line = null; try { line = parser.parse(options, args); } catch (ParseException ex) { System.err.println("Parsing of arguments failed. Reason: " + ex.getMessage()); System.err.println("Use -help for usage."); System.exit(1); } // decide how do we make the interpreter available based on options Interpreter interpreter = null; // show help and exit if (line.hasOption("help")) { HelpFormatter helpFormatter = new HelpFormatter(); helpFormatter.printHelp("java -jar <jar-name>", options, true); System.exit(0); // launch interpreter inside current terminal } else if (line.hasOption("interpreter")) { // assign in, out and err streams to the interpreter interpreter = new Interpreter(new InputStreamReader(System.in), System.out, System.err, true); interpreter.setShowResults(true); // if a script was given, execute it before giving access to user if (line.hasOption("script")) { try { interpreter.source(line.getOptionValue("script")); } catch (IOException ex) { Logger.getLogger(BeanShellConsole.class.getName()).log(Level.SEVERE, "IOException while executing shell script.", ex); } catch (EvalError ex) { Logger.getLogger(BeanShellConsole.class.getName()).log(Level.SEVERE, "EvalError while executing shell script.", ex); } } // give access to user new Thread(interpreter).start(); // only execute script and exit } else if (line.hasOption("script")) { interpreter = new Interpreter(); try { interpreter.source(line.getOptionValue("script")); System.exit(0); } catch (IOException ex) { Logger.getLogger(BeanShellConsole.class.getName()).log(Level.SEVERE, "IOException while executing shell script.", ex); System.exit(1); } catch (EvalError ex) { Logger.getLogger(BeanShellConsole.class.getName()).log(Level.SEVERE, "EvalError while executing shell script.", ex); System.exit(1); } // Launches the RPC server with the model contained in the file whose // filename was passed by argument. } else if (line.hasOption("rpc_server")) { IJPluginModel model = new IJPluginModel(); File file = new File(line.getOptionValue("rpc_server")); try { FileInputStream stream = new FileInputStream(file); model = IJPluginModel.read(stream); } catch (FileNotFoundException ex) { System.out.println("Error: " + file.getName() + " not found."); System.exit(1); } catch (Exception ex) { ex.printStackTrace(); } // Check whether a port number was specified. if (line.hasOption("port")) { try { port = Integer.valueOf(line.getOptionValue("port")); System.out.println("Using port: " + String.valueOf(port)); } catch (java.lang.NumberFormatException ex) { System.out.println("Error: the port number argument is not a number."); System.exit(1); } } else { System.out.println("No port number provided. Using default port: " + String.valueOf(port)); } RPCServer server = new RPCServer(model, port); System.out.println("Starting RPC server..."); server.serve(); } else if (line.hasOption("port") & !line.hasOption("rpc_server")) { System.out.println("Error: Port number provided without requesting the RPC server. Exiting..."); System.exit(1); // if System.console() returns null, it means we were launched by // double-clicking the .jar, so launch own BeanShellConsole // if System.console() returns null, it means we were launched by // double-clicking the .jar, so launch own ConsoleFrame } else if (System.console() == null) { BeanShellConsole cframe = new BeanShellConsole("SASS BeanShell Prompt"); interpreter = cframe.getInterpreter(); cframe.setVisible(true); System.setOut(cframe.getInterpreter().getOut()); System.setErr(cframe.getInterpreter().getErr()); new Thread(cframe.getInterpreter()).start(); // otherwise, show help } else { HelpFormatter helpFormatter = new HelpFormatter(); helpFormatter.printHelp("java -jar <jar-name>", options, true); System.exit(0); } if (interpreter != null) { printWelcomeText(interpreter.getOut()); } }
From source file:GoogleImages.java
public static void main(String[] args) throws InterruptedException { String searchTerm = "s woman"; // term to search for (use spaces to separate terms) int offset = 40; // we can only 20 results at a time - use this to offset and get more! String fileSize = "50mp"; // specify file size in mexapixels (S/M/L not figured out yet) String source = null; // string to save raw HTML source code // format spaces in URL to avoid problems searchTerm = searchTerm.replaceAll(" ", "%20"); // get Google image search HTML source code; mostly built from PhyloWidget example: // http://code.google.com/p/phylowidget/source/browse/trunk/PhyloWidget/src/org/phylowidget/render/images/ImageSearcher.java int offset2 = 0; Set urlsss = new HashSet<String>(); while (offset2 < 600) { try {/*from w ww. jav a2 s . co m*/ URL query = new URL("https://www.google.ru/search?start=" + offset2 + "&q=angry+woman&newwindow=1&client=opera&hs=bPE&source=lnms&tbm=isch&sa=X&ved=0ahUKEwiAgcKozIfNAhWoHJoKHSb_AUoQ_AUIBygB&biw=1517&bih=731&dpr=0.9#imgrc=G_1tH3YOPcc8KM%3A"); HttpURLConnection urlc = (HttpURLConnection) query.openConnection(); // start connection... urlc.setInstanceFollowRedirects(true); urlc.setRequestProperty("User-Agent", ""); urlc.connect(); BufferedReader in = new BufferedReader(new InputStreamReader(urlc.getInputStream())); // stream in HTTP source to file StringBuffer response = new StringBuffer(); char[] buffer = new char[1024]; while (true) { int charsRead = in.read(buffer); if (charsRead == -1) { break; } response.append(buffer, 0, charsRead); } in.close(); // close input stream (also closes network connection) source = response.toString(); } // any problems connecting? let us know catch (Exception e) { e.printStackTrace(); } // print full source code (for debugging) // println(source); // extract image URLs only, starting with 'imgurl' if (source != null) { // System.out.println(source); int c = StringUtils.countMatches(source, "http://www.vmir.su"); System.out.println(c); int index = source.indexOf("src="); System.out.println(source.subSequence(index, index + 200)); while (index >= 0) { System.out.println(index); index = source.indexOf("src=", index + 1); if (index == -1) { break; } String rr = source.substring(index, index + 200 > source.length() ? source.length() : index + 200); if (rr.contains("\"")) { rr = rr.substring(5, rr.indexOf("\"", 5)); } System.out.println(rr); urlsss.add(rr); } } offset2 += 20; Thread.sleep(1000); System.out.println("off set = " + offset2); } System.out.println(urlsss); urlsss.forEach(new Consumer<String>() { public void accept(String s) { try { saveImage(s, "C:\\Users\\Java\\Desktop\\ang\\" + UUID.randomUUID().toString() + ".jpg"); } catch (IOException ex) { Logger.getLogger(GoogleImages.class.getName()).log(Level.SEVERE, null, ex); } } }); // String[][] m = matchAll(source, "img height=\"\\d+\" src=\"([^\"]+)\""); // older regex, no longer working but left for posterity // built partially from: http://www.mkyong.com/regular-expressions/how-to-validate-image-file-extension-with-regular-expression // String[][] m = matchAll(source, "imgurl=(.*?\\.(?i)(jpg|jpeg|png|gif|bmp|tif|tiff))"); // (?i) means case-insensitive // for (int i = 0; i < m.length; i++) { // iterate all results of the match // println(i + ":\t" + m[i][1]); // print (or store them)** // } }