Example usage for java.util.logging Logger getLogger

List of usage examples for java.util.logging Logger getLogger

Introduction

In this page you can find the example usage for java.util.logging Logger getLogger.

Prototype




@CallerSensitive
public static Logger getLogger(String name) 

Source Link

Document

Find or create a logger for a named subsystem.

Usage

From source file:net.sf.mpaxs.test.ImpaxsExecution.java

/**
 *
 * @param args/*  ww w .j  ava2 s.  c om*/
 */
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:sdmx.net.service.opensdmx.OpenSDMXRESTQueryable.java

public static void main(String args[]) {
    OpenSDMXRESTQueryable registry = new OpenSDMXRESTQueryable("FAO", "http://data.fao.org/sdmx");
    //SdmxIO.setSaveXml(true);
    SdmxIO.setLogLevel(7);//from w ww . j  a va2s  . c  o  m
    Logger.getLogger("sdmx").setLevel(Level.ALL);
    DataStructureReference ref = DataStructureReference.create(new NestedNCNameID("FAO"),
            new IDType("CAPTURE_DATASTRUCTURE"), new Version("0.1"));
    System.out.println("DataStructure=" + registry.find(ref));
}

From source file:ie.aib.nbp.zosresttest.RunTest.java

/**
 * @param args the command line arguments
 *//*from   w  w w.j a  v a2s. c o  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:asl.seedscan.DQAWeb.java

public static void main(String args[]) {
    db = new MetricDatabase("", "", "");
    findConsoleHandler();/*from   w  w w.  j  ava  2s . c o  m*/
    consoleHandler.setLevel(Level.ALL);
    Logger.getLogger("").setLevel(Level.CONFIG);

    // Default locations of config and schema files
    File configFile = new File("dqaweb-config.xml");
    File schemaFile = new File("schemas/DQAWebConfig.xsd");
    boolean parseConfig = true;
    boolean testMode = false;

    ArrayList<File> schemaFiles = new ArrayList<File>();
    schemaFiles.add(schemaFile);
    // ==== Command Line Parsing ====
    Options options = new Options();
    Option opConfigFile = new Option("c", "config-file", true,
            "The config file to use for seedscan. XML format according to SeedScanConfig.xsd.");
    Option opSchemaFile = new Option("s", "schema-file", true,
            "The schame file which should be used to verify the config file format. ");
    Option opTest = new Option("t", "test", false, "Run in test console mode rather than as a servlet.");

    OptionGroup ogConfig = new OptionGroup();
    ogConfig.addOption(opConfigFile);

    OptionGroup ogSchema = new OptionGroup();
    ogConfig.addOption(opSchemaFile);

    OptionGroup ogTest = new OptionGroup();
    ogTest.addOption(opTest);

    options.addOptionGroup(ogConfig);
    options.addOptionGroup(ogSchema);
    options.addOptionGroup(ogTest);

    PosixParser optParser = new PosixParser();
    CommandLine cmdLine = null;
    try {
        cmdLine = optParser.parse(options, args, true);
    } catch (org.apache.commons.cli.ParseException e) {
        logger.severe("Error while parsing command-line arguments.");
        System.exit(1);
    }

    Option opt;
    Iterator iter = cmdLine.iterator();
    while (iter.hasNext()) {
        opt = (Option) iter.next();

        if (opt.getOpt().equals("c")) {
            configFile = new File(opt.getValue());
        } else if (opt.getOpt().equals("s")) {
            schemaFile = new File(opt.getValue());
        } else if (opt.getOpt().equals("t")) {
            testMode = true;
        }
    }
    String query = "";
    System.out.println("Entering Test Mode");
    System.out.println("Enter a query string to view results or type \"help\" for example query strings");
    InputStreamReader input = new InputStreamReader(System.in);
    BufferedReader reader = new BufferedReader(input);
    String result = "";

    while (testMode == true) {
        try {

            System.out.printf("Query: ");
            query = reader.readLine();
            if (query.equals("exit")) {
                testMode = false;
            } else if (query.equals("help")) {
                System.out.println("Need to add some help for people"); //TODO
            } else {
                result = processCommand(query);
            }
            System.out.println(result);
        } catch (IOException err) {
            System.err.println("Error reading line, in DQAWeb.java");
        }
    }
    System.err.printf("DONE.\n");
}

From source file:cc.redberry.core.performance.StableSort.java

/**
 * @param args the command line arguments
 *///from w  w  w  .  ja  va2  s.  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 {//from  w  w  w . j  a v  a 2s .c om
        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:at.tuwien.ifs.somtoolbox.apps.SOMToolboxMain.java

/**
 * Central Main for SOMToolbox.//w w  w. j  a v  a 2s  .  com
 * 
 * @param args the command line args
 */
public static void main(String[] args) {
    int screenWidth = 80;
    try {
        screenWidth = Integer.parseInt(System.getenv("COLUMNS"));
    } catch (Exception e) {
        screenWidth = 80;
    }

    JSAP jsap = new JSAP();
    try {
        jsap.registerParameter(new UnflaggedOption("main", JSAP.STRING_PARSER, null, false, false));
        jsap.registerParameter(new Switch("gui", 'G', "gui"));
        jsap.registerParameter(new Switch("version", JSAP.NO_SHORTFLAG, "version"));
        jsap.registerParameter(new Switch("listmains", JSAP.NO_SHORTFLAG, "list-mains"));
        jsap.registerParameter(
                new FlaggedOption("help", JSAP.STRING_PARSER, null, false, JSAP.NO_SHORTFLAG, "help"));
    } catch (JSAPException e) {
        assert false;
    }
    JSAPResult result = jsap.parse(args);

    ArrayList<Class<? extends SOMToolboxApp>> runnables = SubClassFinder.findSubclassesOf(SOMToolboxApp.class,
            true);
    Collections.sort(runnables, SOMToolboxApp.TYPE_GROUPED_COMPARATOR);

    // args > 0
    boolean useGUI = result.getBoolean("gui", false);
    if (useGUI) {
        UiUtils.setSOMToolboxLookAndFeel();
    }

    if (result.getBoolean("listmains")) {
        if (useGUI) {
            showAvailableRunnables(runnables, args);
        } else {
            printAvailableRunnables(screenWidth, runnables);
        }
    } else if (result.getBoolean("version")) {
        if (result.userSpecified("main")) {
            printVersion(result.getString("main"));
        } else {
            printVersion("somtoolbox");
        }
    } else if (result.userSpecified("main")) {
        String mainClass = result.getString("main");
        String[] cleanArgs = Arrays.copyOfRange(args, 1, args.length);
        if (!invokeMainClass(runnables, mainClass, cleanArgs, useGUI)) {
            Logger.getLogger("at.tuwien.ifs.somtoolbox").severe("Runnable \"" + mainClass + "\" not found.");
            printAvailableRunnables(screenWidth, runnables);
        }
    } else if (result.contains("help")) {
        if (result.getString("help") != null) {
            invokeMainClass(runnables, result.getString("help"), new String[] { "--help" }, useGUI);
        } else {
            printHelp();
        }
    } else {
        if (useGUI) {
            showAvailableRunnables(runnables, args);
        } else {
            printAvailableRunnables(screenWidth, runnables);
        }

    }
}

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//from  w w w . j av  a 2 s .c o m
 */
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:edu.usu.sdl.wso2client.SampleWSRegistryClient.java

public static void main(String[] args) throws Exception {
    Registry registry = initialize();
    try {/*w  w  w.ja  v a  2 s . co  m*/
        //load component

        List<ComponentAll> components;
        try (InputStream in = new FileInputStream("C:\\temp\\components.json")) {
            components = StringProcessor.defaultObjectMapper().readValue(in,
                    new TypeReference<List<ComponentAll>>() {
                    });
        } catch (IOException ex) {
            throw ex;
        }

        ComponentAll componentAll = components.get(0);

        Resource resource = registry.newResource();
        resource.setContent(componentAll.getComponent().getDescription());

        resource.setDescription("Storefront Component");
        resource.setMediaType("application/openstorefront");
        resource.setUUID(componentAll.getComponent().getComponentId());

        try {
            Map fieldMap = BeanUtils.describe(componentAll.getComponent());
            fieldMap.keySet().stream().forEach((key) -> {
                if ("description".equals(key) == false) {
                    resource.setProperty(Component.class.getSimpleName() + "_" + key, "" + fieldMap.get(key));
                    //System.out.println("key  = " + Component.class.getSimpleName() + "_" + key);
                    //System.out.println("Value  = " + fieldMap.get(key));
                }
            });
        } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException ex) {
            Logger.getLogger(StringProcessor.class.getName()).log(Level.SEVERE, null, ex);
        }

        String resourcePath = "/storefront/components/" + componentAll.getComponent().getComponentId();
        registry.put(resourcePath, resource);

        //
        System.out.println("A resource added to: " + resourcePath);
        //         registry.rateResource(resourcePath, 4);
        //
        //         System.out.println("Resource rated with 4 stars!");
        //         Comment comment = new Comment();
        //         comment.setText("Testing Connection");
        //         registry.addComment(resourcePath, comment);
        //         System.out.println("Comment added to resource");
        //
        //         Resource getResource = registry.get("/abc2");
        //         System.out.println("Resource retrived");
        //         System.out.println("Printing retrieved resource content: "
        //               + new String((byte[]) getResource.getContent()));

        //         Resource resource = registry.newResource();
        //         resource.setContent("Hello Out there!");
        //
        //         String resourcePath = "/abc3";
        //         registry.put(resourcePath, resource);
        //
        //         System.out.println("A resource added to: " + resourcePath);
        //
        //         registry.rateResource(resourcePath, 4);
        //
        //         System.out.println("Resource rated with 4 stars!");
        //         Comment comment = new Comment();
        //         comment.setText("Testing Connection");
        //         registry.addComment(resourcePath, comment);
        //         System.out.println("Comment added to resource");
        //
        //         Resource getResource = registry.get("/abc3");
        //         System.out.println("Resource retrived");
        //         System.out.println("Printing retrieved resource content: "
        //               + new String((byte[]) getResource.getContent()));
    } finally {
        //Close the session
        ((WSRegistryServiceClient) registry).logut();
    }
    System.exit(0);
}

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 {/*w w  w .  j ava  2  s  .  c o  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)**
    //            }
}