Example usage for java.util Properties Properties

List of usage examples for java.util Properties Properties

Introduction

In this page you can find the example usage for java.util Properties Properties.

Prototype

public Properties() 

Source Link

Document

Creates an empty property list with no default values.

Usage

From source file:com.google.api.services.samples.youtube.cmdline.youtube_cmdline_topics_sample.Topics.java

/**
 * Method kicks off a search via the Freebase API for a topics id.  It initializes a YouTube
 * object to search for videos on YouTube (Youtube.Search.List) using that topics id to make the
 * search more specific.  The program then prints the names and thumbnails of each of the videos
 * (only first 5 videos).  Please note, user input is taken for both search on Freebase and on
 * YouTube.// w ww  .  j  a va  2 s .  c om
 *
 * @param args command line args not used.
*/
public static void main(String[] args) {
    // Read the developer key from youtube.properties
    Properties properties = new Properties();
    try {
        InputStream in = Topics.class.getResourceAsStream("/" + PROPERTIES_FILENAME);
        properties.load(in);

    } catch (IOException e) {
        System.err.println("There was an error reading " + PROPERTIES_FILENAME + ": " + e.getCause() + " : "
                + e.getMessage());
        System.exit(1);
    }

    try {
        // Gets a topic id via the Freebase API based on user input.
        String topicsId = getTopicId();
        if (topicsId.length() < 1) {
            System.out.println("No topic id will be applied to your search.");
        }

        /*
         * Get query term from user.  The "search" parameter is just used as output to clarify that
         * we want a "search" term (vs. a "topics" term).
         */
        String queryTerm = getInputQuery("search");

        /*
         * The YouTube object is used to make all API requests.  The last argument is required, but
         * because we don't need anything initialized when the HttpRequest is initialized, we
         * override the interface and provide a no-op function.
         */
        youtube = new YouTube.Builder(HTTP_TRANSPORT, JSON_FACTORY, new HttpRequestInitializer() {
            public void initialize(HttpRequest request) throws IOException {
            }
        }).setApplicationName("youtube-cmdline-search-sample").build();

        YouTube.Search.List search = youtube.search().list("id,snippet");
        /*
         * It is important to set your developer key from the Google Developer Console for
         * non-authenticated requests (found under the API Access tab at this link:
         * code.google.com/apis/). This is good practice and increases your quota.
         */
        String apiKey = properties.getProperty("youtube.apikey");
        search.setKey(apiKey);
        search.setQ(queryTerm);
        if (topicsId.length() > 0) {
            search.setTopicId(topicsId);
        }

        /*
         * We are only searching for videos (not playlists or channels).  If we were searching for
         * more, we would add them as a string like this: "video,playlist,channel".
         */
        search.setType("video");
        /*
         * This method reduces the info returned to only the fields we need.  It makes things more
         * efficient, because we are transmitting less data.
         */
        search.setFields("items(id/kind,id/videoId,snippet/title,snippet/thumbnails/default/url)");
        search.setMaxResults(NUMBER_OF_VIDEOS_RETURNED);
        SearchListResponse searchResponse = search.execute();

        List<SearchResult> searchResultList = searchResponse.getItems();

        if (searchResultList != null) {
            prettyPrint(searchResultList.iterator(), queryTerm, topicsId);
        } else {
            System.out.println("There were no results for your query.");
        }
    } catch (GoogleJsonResponseException e) {
        System.err.println(
                "There was a service error: " + e.getDetails().getCode() + " : " + e.getDetails().getMessage());
        e.printStackTrace();
    } catch (IOException e) {
        System.err.println("There was an IO error: " + e.getCause() + " : " + e.getMessage());
        e.printStackTrace();
    }
}

From source file:glacierpipe.GlacierPipeMain.java

public static void main(String[] args) throws IOException, ParseException {
    CommandLineParser parser = new GnuParser();

    CommandLine cmd = parser.parse(OPTIONS, args);

    if (cmd.hasOption("help")) {
        try (PrintWriter writer = new PrintWriter(System.err)) {
            printHelp(writer);/*from  w w w.j ava2  s  . co  m*/
        }

        System.exit(0);
    } else if (cmd.hasOption("upload")) {

        // Turn the CommandLine into Properties
        Properties cliProperties = new Properties();
        for (Iterator<?> i = cmd.iterator(); i.hasNext();) {
            Option o = (Option) i.next();

            String opt = o.getLongOpt();
            opt = opt != null ? opt : o.getOpt();

            String value = o.getValue();
            value = value != null ? value : "";

            cliProperties.setProperty(opt, value);
        }

        // Build up a configuration
        ConfigBuilder configBuilder = new ConfigBuilder();

        // Archive name
        List<?> archiveList = cmd.getArgList();
        if (archiveList.size() > 1) {
            throw new ParseException("Too many arguments");
        } else if (archiveList.isEmpty()) {
            throw new ParseException("No archive name provided");
        }

        configBuilder.setArchive(archiveList.get(0).toString());

        // All other arguments on the command line
        configBuilder.setFromProperties(cliProperties);

        // Load any config from the properties file
        Properties fileProperties = new Properties();
        try (InputStream in = new FileInputStream(configBuilder.propertiesFile)) {
            fileProperties.load(in);
        } catch (IOException e) {
            System.err.printf("Warning: unable to read properties file %s; %s%n", configBuilder.propertiesFile,
                    e);
        }

        configBuilder.setFromProperties(fileProperties);

        // ...
        Config config = new Config(configBuilder);

        IOBuffer buffer = new MemoryIOBuffer(config.partSize);

        AmazonGlacierClient client = new AmazonGlacierClient(
                new BasicAWSCredentials(config.accessKey, config.secretKey));
        client.setEndpoint(config.endpoint);

        // Actual upload
        try (InputStream in = new BufferedInputStream(System.in, 4096);
                PrintWriter writer = new PrintWriter(System.err);
                ObservableProperties configMonitor = config.reloadProperties
                        ? new ObservableProperties(config.propertiesFile)
                        : null;
                ProxyingThrottlingStrategy throttlingStrategy = new ProxyingThrottlingStrategy(config);) {
            TerminalGlacierPipeObserver observer = new TerminalGlacierPipeObserver(writer);

            if (configMonitor != null) {
                configMonitor.registerObserver(throttlingStrategy);
            }

            GlacierPipe pipe = new GlacierPipe(buffer, observer, config.maxRetries, throttlingStrategy);
            pipe.pipe(client, config.vault, config.archive, in);
        } catch (Exception e) {
            e.printStackTrace(System.err);
        }

        System.exit(0);
    } else {
        try (PrintWriter writer = new PrintWriter(System.err)) {
            writer.println("No action specified.");
            printHelp(writer);
        }

        System.exit(-1);
    }
}

From source file:com.google.api.services.samples.youtube.cmdline.Topics.java

/**
 * Execute a search request that starts by calling the Freebase API to
 * retrieve a topic ID matching a user-provided term. Then initialize a
 * YouTube object to search for YouTube videos and call the YouTube Data
 * API's youtube.search.list method to retrieve a list of videos associated
 * with the selected Freebase topic and with another search query term,
 * which the user also enters. Finally, display the titles, video IDs, and
 * thumbnail images for the first five videos in the YouTube Data API
 * response.//from  w w  w .jav  a  2 s.c om
 *
 * @param args This application does not use command line arguments.
 */
public static void main(String[] args) {
    // Read the developer key from the properties file.
    Properties properties = new Properties();
    try {
        InputStream in = Topics.class.getResourceAsStream("/" + PROPERTIES_FILENAME);
        properties.load(in);

    } catch (IOException e) {
        System.err.println("There was an error reading " + PROPERTIES_FILENAME + ": " + e.getCause() + " : "
                + e.getMessage());
        System.exit(1);
    }

    try {
        // Retrieve a Freebase topic ID based on a user-entered query term.
        String topicsId = getTopicId();
        if (topicsId.length() < 1) {
            System.out.println("No topic id will be applied to your search.");
        }

        // Prompt the user to enter a search query term. This term will be
        // used to retrieve YouTube search results related to the topic
        // selected above.
        String queryTerm = getInputQuery("search");

        // This object is used to make YouTube Data API requests. The last
        // argument is required, but since we don't need anything
        // initialized when the HttpRequest is initialized, we override
        // the interface and provide a no-op function.
        youtube = new YouTube.Builder(Auth.HTTP_TRANSPORT, Auth.JSON_FACTORY, new HttpRequestInitializer() {
            public void initialize(HttpRequest request) throws IOException {
            }
        }).setApplicationName("youtube-cmdline-search-sample").build();

        YouTube.Search.List search = youtube.search().list("id,snippet");

        // Set your developer key from the Google Developers Console for
        // non-authenticated requests. See:
        // https://cloud.google.com/console
        String apiKey = properties.getProperty("youtube.apikey");
        search.setKey(apiKey);
        search.setQ(queryTerm);
        if (topicsId.length() > 0) {
            search.setTopicId(topicsId);
        }

        // Restrict the search results to only include videos. See:
        // https://developers.google.com/youtube/v3/docs/search/list#type
        search.setType("video");

        // To increase efficiency, only retrieve the fields that the
        // application uses.
        search.setFields("items(id/kind,id/videoId,snippet/title,snippet/thumbnails/default/url)");
        search.setMaxResults(NUMBER_OF_VIDEOS_RETURNED);
        SearchListResponse searchResponse = search.execute();

        List<SearchResult> searchResultList = searchResponse.getItems();

        if (searchResultList != null) {
            prettyPrint(searchResultList.iterator(), queryTerm, topicsId);
        } else {
            System.out.println("There were no results for your query.");
        }
    } catch (GoogleJsonResponseException e) {
        System.err.println(
                "There was a service error: " + e.getDetails().getCode() + " : " + e.getDetails().getMessage());
        e.printStackTrace();
    } catch (IOException e) {
        System.err.println("There was an IO error: " + e.getCause() + " : " + e.getMessage());
        e.printStackTrace();
    }
}

From source file:com.google.api.services.samples.youtube.cmdline.data.Topics.java

/**
 * Execute a search request that starts by calling the Freebase API to
 * retrieve a topic ID matching a user-provided term. Then initialize a
 * YouTube object to search for YouTube videos and call the YouTube Data
 * API's youtube.search.list method to retrieve a list of videos associated
 * with the selected Freebase topic and with another search query term,
 * which the user also enters. Finally, display the titles, video IDs, and
 * thumbnail images for the first five videos in the YouTube Data API
 * response./*from ww  w .  ja v  a  2  s  .co m*/
 *
 * @param args This application does not use command line arguments.
 */
public static void main(String[] args) {
    // Read the developer key from the properties file.
    Properties properties = new Properties();
    try {
        InputStream in = Topics.class.getResourceAsStream("/" + PROPERTIES_FILENAME);
        properties.load(in);

    } catch (IOException e) {
        System.err.println("There was an error reading " + PROPERTIES_FILENAME + ": " + e.getCause() + " : "
                + e.getMessage());
        System.exit(1);
    }

    try {
        // Retrieve a Freebase topic ID based on a user-entered query term.
        String topicsId = getTopicId();
        if (topicsId.length() < 1) {
            System.out.println("No topic id will be applied to your search.");
        }

        // Prompt the user to enter a search query term. This term will be
        // used to retrieve YouTube search results related to the topic
        // selected above.
        String queryTerm = getInputQuery("search");

        // This object is used to make YouTube Data API requests. The last
        // argument is required, but since we don't need anything
        // initialized when the HttpRequest is initialized, we override
        // the interface and provide a no-op function.
        youtube = new YouTube.Builder(Auth.HTTP_TRANSPORT, Auth.JSON_FACTORY, new HttpRequestInitializer() {
            public void initialize(HttpRequest request) throws IOException {
            }
        }).setApplicationName("youtube-cmdline-search-sample").build();

        YouTube.Search.List search = youtube.search().list("id,snippet");

        // Set your developer key from the {{ Google Cloud Console }} for
        // non-authenticated requests. See:
        // {{ https://cloud.google.com/console }}
        String apiKey = properties.getProperty("youtube.apikey");
        search.setKey(apiKey);
        search.setQ(queryTerm);
        if (topicsId.length() > 0) {
            search.setTopicId(topicsId);
        }

        // Restrict the search results to only include videos. See:
        // https://developers.google.com/youtube/v3/docs/search/list#type
        search.setType("video");

        // To increase efficiency, only retrieve the fields that the
        // application uses.
        search.setFields("items(id/kind,id/videoId,snippet/title,snippet/thumbnails/default/url)");
        search.setMaxResults(NUMBER_OF_VIDEOS_RETURNED);
        SearchListResponse searchResponse = search.execute();

        List<SearchResult> searchResultList = searchResponse.getItems();

        if (searchResultList != null) {
            prettyPrint(searchResultList.iterator(), queryTerm, topicsId);
        } else {
            System.out.println("There were no results for your query.");
        }
    } catch (GoogleJsonResponseException e) {
        System.err.println(
                "There was a service error: " + e.getDetails().getCode() + " : " + e.getDetails().getMessage());
        e.printStackTrace();
    } catch (IOException e) {
        System.err.println("There was an IO error: " + e.getCause() + " : " + e.getMessage());
        e.printStackTrace();
    }
}

From source file:LauncherBootstrap.java

/**
 * The main method.//w w  w . j av a 2  s  .c  om
 *
 * @param args command line arguments
 */
public static void main(String[] args) {

    try {

        // Try to find the LAUNCHER_JAR_FILE_NAME file in the class
        // loader's and JVM's classpath.
        URL coreURL = LauncherBootstrap.class.getResource("/" + LauncherBootstrap.LAUNCHER_JAR_FILE_NAME);
        if (coreURL == null)
            throw new FileNotFoundException(LauncherBootstrap.LAUNCHER_JAR_FILE_NAME);

        // Coerce the coreURL's directory into a file
        File coreDir = new File(URLDecoder.decode(coreURL.getFile())).getCanonicalFile().getParentFile();

        // Try to find the LAUNCHER_PROPS_FILE_NAME file in the same
        // directory as this class
        File propsFile = new File(coreDir, LauncherBootstrap.LAUNCHER_PROPS_FILE_NAME);
        if (!propsFile.canRead())
            throw new FileNotFoundException(propsFile.getPath());

        // Load the properties in the LAUNCHER_PROPS_FILE_NAME 
        Properties props = new Properties();
        FileInputStream fis = new FileInputStream(propsFile);
        props.load(fis);
        fis.close();

        // Create a class loader that contains the Launcher, Ant, and
        // JAXP classes.
        URL[] antURLs = LauncherBootstrap
                .fileListToURLs((String) props.get(LauncherBootstrap.ANT_CLASSPATH_PROP_NAME));
        URL[] urls = new URL[1 + antURLs.length];
        urls[0] = coreURL;
        for (int i = 0; i < antURLs.length; i++)
            urls[i + 1] = antURLs[i];
        ClassLoader parentLoader = Thread.currentThread().getContextClassLoader();
        URLClassLoader loader = null;
        if (parentLoader != null)
            loader = new URLClassLoader(urls, parentLoader);
        else
            loader = new URLClassLoader(urls);

        // Load the LAUNCHER_MAIN_CLASS_NAME class
        launcherClass = loader.loadClass(LAUNCHER_MAIN_CLASS_NAME);

        // Get the LAUNCHER_MAIN_CLASS_NAME class' getLocalizedString()
        // method as we need it for printing the usage statement
        Method getLocalizedStringMethod = launcherClass.getDeclaredMethod("getLocalizedString",
                new Class[] { String.class });

        // Invoke the LAUNCHER_MAIN_CLASS_NAME class' start() method.
        // If the ant.class.path property is not set correctly in the 
        // LAUNCHER_PROPS_FILE_NAME, this will throw an exception.
        Method startMethod = launcherClass.getDeclaredMethod("start", new Class[] { String[].class });
        int returnValue = ((Integer) startMethod.invoke(null, new Object[] { args })).intValue();
        // Always exit cleanly after invoking the start() method
        System.exit(returnValue);

    } catch (Throwable t) {

        t.printStackTrace();
        System.exit(1);

    }

}

From source file:net.ontopia.persistence.rdbms.CSVImport.java

public static void main(String[] argv) throws Exception {

    // Initialize logging
    CmdlineUtils.initializeLogging();//from  w w w  . j av a2s  .com

    // Initialize command line option parser and listeners
    CmdlineOptions options = new CmdlineOptions("CSVImport", argv);
    OptionsListener ohandler = new OptionsListener();

    // Register local options
    options.addLong(ohandler, "separator", 's', true);
    options.addLong(ohandler, "stripquotes", 'q');
    options.addLong(ohandler, "ignorelines", 'i', true);

    // Register logging options
    CmdlineUtils.registerLoggingOptions(options);

    // Parse command line options
    try {
        options.parse();
    } catch (CmdlineOptions.OptionsException e) {
        System.err.println("Error: " + e.getMessage());
        System.exit(1);
    }

    // Get command line arguments
    String[] args = options.getArguments();
    if (args.length < 4) {
        System.err.println("Error: wrong number of arguments.");
        usage();
        System.exit(1);
    }

    String schema = args[0];
    String dbprops = args[1];
    String csvfile = args[2];
    String table = args[3];
    String[] columns = StringUtils.split(args[4], ",");

    // Load property file
    Properties props = new Properties();
    props.load(new FileInputStream(dbprops));

    // Create database connection
    DefaultConnectionFactory cfactory = new DefaultConnectionFactory(props, false);
    Connection conn = cfactory.requestConnection();

    CSVImport ci = new CSVImport(DatabaseProjectReader.loadProject(schema), conn);
    ci.setTable(table);
    ci.setColumns(columns);
    ci.setSeparator(ohandler.separator);
    ci.setClearTable(true);
    ci.setStripQuotes(ohandler.stripquotes);
    ci.setIgnoreColumns(true);
    ci.setIgnoreLines(ohandler.ignorelines);

    ci.importCSV(new FileInputStream(csvfile));
}

From source file:com.betfair.cougar.test.socket.app.SocketCompatibilityTestingApp.java

public static void main(String[] args) throws Exception {

    Parser parser = new PosixParser();
    Options options = new Options();
    options.addOption("r", "repo", true, "Repository type to search: local|central");
    options.addOption("c", "client-concurrency", true,
            "Max threads to allow each client tester to run tests, defaults to 10");
    options.addOption("t", "test-concurrency", true, "Max client testers to run concurrently, defaults to 5");
    options.addOption("m", "max-time", true,
            "Max time (in minutes) to allow tests to complete, defaults to 10");
    options.addOption("v", "version", false, "Print version and exit");
    options.addOption("h", "help", false, "This help text");
    CommandLine commandLine = parser.parse(options, args);
    if (commandLine.hasOption("h")) {
        System.out.println(options);
        System.exit(0);//ww w . jav  a  2s  .  c o  m
    }
    if (commandLine.hasOption("v")) {
        System.out.println("How the hell should I know?");
        System.exit(0);
    }
    // 1. Find all testers in given repos
    List<RepoSearcher> repoSearchers = new ArrayList<>();
    for (String repo : commandLine.getOptionValues("r")) {
        if ("local".equals(repo.toLowerCase())) {
            repoSearchers.add(new LocalRepoSearcher());
        } else if ("central".equals(repo.toLowerCase())) {
            repoSearchers.add(new CentralRepoSearcher());
        } else {
            System.err.println("Unrecognized repo: " + repo);
            System.err.println(options);
            System.exit(1);
        }
    }
    int clientConcurrency = 10;
    if (commandLine.hasOption("c")) {
        try {
            clientConcurrency = Integer.parseInt(commandLine.getOptionValue("c"));
        } catch (NumberFormatException nfe) {
            System.err.println(
                    "client-concurrency is not a valid integer: '" + commandLine.getOptionValue("c") + "'");
            System.exit(1);
        }
    }
    int testConcurrency = 5;
    if (commandLine.hasOption("t")) {
        try {
            testConcurrency = Integer.parseInt(commandLine.getOptionValue("t"));
        } catch (NumberFormatException nfe) {
            System.err.println(
                    "test-concurrency is not a valid integer: '" + commandLine.getOptionValue("t") + "'");
            System.exit(1);
        }
    }
    int maxMinutes = 10;
    if (commandLine.hasOption("m")) {
        try {
            maxMinutes = Integer.parseInt(commandLine.getOptionValue("m"));
        } catch (NumberFormatException nfe) {
            System.err.println("max-time is not a valid integer: '" + commandLine.getOptionValue("m") + "'");
            System.exit(1);
        }
    }

    Properties clientProps = new Properties();
    clientProps.setProperty("client.concurrency", String.valueOf(clientConcurrency));

    File baseRunDir = new File(System.getProperty("user.dir") + "/run");
    baseRunDir.mkdirs();

    File tmpDir = new File(baseRunDir, "jars");
    tmpDir.mkdirs();

    List<ServerRunner> serverRunners = new ArrayList<>();
    List<ClientRunner> clientRunners = new ArrayList<>();
    for (RepoSearcher searcher : repoSearchers) {
        List<File> jars = searcher.findAndCache(tmpDir);
        for (File f : jars) {
            ServerRunner serverRunner = new ServerRunner(f, baseRunDir);
            System.out.println("Found tester: " + serverRunner.getVersion());
            serverRunners.add(serverRunner);
            clientRunners.add(new ClientRunner(f, baseRunDir, clientProps));
        }
    }

    // 2. Start servers and collect ports
    System.out.println();
    System.out.println("Starting " + serverRunners.size() + " servers...");
    for (ServerRunner server : serverRunners) {
        server.startServer();
    }
    System.out.println();

    List<TestCombo> tests = new ArrayList<>(serverRunners.size() * clientRunners.size());
    for (ServerRunner server : serverRunners) {
        for (ClientRunner client : clientRunners) {
            tests.add(new TestCombo(server, client));
        }
    }

    System.out.println("Enqueued " + tests.size() + " test combos to run...");

    long startTime = System.currentTimeMillis();
    // 3. Run every client against every server, collecting results
    BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue(serverRunners.size() * clientRunners.size());
    ThreadPoolExecutor service = new ThreadPoolExecutor(testConcurrency, testConcurrency, 5000,
            TimeUnit.MILLISECONDS, workQueue);
    service.prestartAllCoreThreads();
    workQueue.addAll(tests);
    while (!workQueue.isEmpty()) {
        Thread.sleep(1000);
    }
    service.shutdown();
    service.awaitTermination(maxMinutes, TimeUnit.MINUTES);
    long endTime = System.currentTimeMillis();
    long totalTimeSecs = Math.round((endTime - startTime) / 1000.0);
    for (ServerRunner server : serverRunners) {
        server.shutdownServer();
    }

    System.out.println();
    System.out.println("=======");
    System.out.println("Results");
    System.out.println("-------");
    // print a summary
    int totalTests = 0;
    int totalSuccess = 0;
    for (TestCombo combo : tests) {
        String clientVer = combo.getClientVersion();
        String serverVer = combo.getServerVersion();
        String results = combo.getClientResults();
        ObjectMapper mapper = new ObjectMapper(new JsonFactory());
        JsonNode node = mapper.reader().readTree(results);
        JsonNode resultsArray = node.get("results");
        int numTests = resultsArray.size();
        int numSuccess = 0;
        for (int i = 0; i < numTests; i++) {
            if ("success".equals(resultsArray.get(i).get("result").asText())) {
                numSuccess++;
            }
        }
        totalSuccess += numSuccess;
        totalTests += numTests;
        System.out.println(clientVer + "/" + serverVer + ": " + numSuccess + "/" + numTests
                + " succeeded - took " + String.format("%2f", combo.getRunningTime()) + " seconds");
    }
    System.out.println("-------");
    System.out.println(
            "Overall: " + totalSuccess + "/" + totalTests + " succeeded - took " + totalTimeSecs + " seconds");

    FileWriter out = new FileWriter("results.json");
    PrintWriter pw = new PrintWriter(out);

    // 4. Output full results
    pw.println("{\n  \"results\": [");
    for (TestCombo combo : tests) {
        combo.emitResults(pw, "    ");
    }
    pw.println("  ],");
    pw.println("  \"servers\": [");
    for (ServerRunner server : serverRunners) {
        server.emitInfo(pw, "    ");
    }
    pw.println("  ],");
    pw.close();
}

From source file:fr.inria.atlanmod.kyanos.benchmarks.KyanosGraphTraverser.java

public static void main(String[] args) {
    Options options = new Options();

    Option inputOpt = OptionBuilder.create(IN);
    inputOpt.setArgName("INPUT");
    inputOpt.setDescription("Input Kyanos resource directory");
    inputOpt.setArgs(1);/* ww  w.  ja  v  a2s .  co m*/
    inputOpt.setRequired(true);

    Option inClassOpt = OptionBuilder.create(EPACKAGE_CLASS);
    inClassOpt.setArgName("CLASS");
    inClassOpt.setDescription("FQN of EPackage implementation class");
    inClassOpt.setArgs(1);
    inClassOpt.setRequired(true);

    Option optFileOpt = OptionBuilder.create(OPTIONS_FILE);
    optFileOpt.setArgName("FILE");
    optFileOpt.setDescription("Properties file holding the options to be used in the Kyanos Resource");
    optFileOpt.setArgs(1);

    options.addOption(inputOpt);
    options.addOption(inClassOpt);
    options.addOption(optFileOpt);

    CommandLineParser parser = new PosixParser();

    try {
        PersistenceBackendFactoryRegistry.getFactories().put(NeoBlueprintsURI.NEO_GRAPH_SCHEME,
                new BlueprintsPersistenceBackendFactory());

        CommandLine commandLine = parser.parse(options, args);

        URI uri = NeoBlueprintsURI.createNeoGraphURI(new File(commandLine.getOptionValue(IN)));

        Class<?> inClazz = KyanosGraphTraverser.class.getClassLoader()
                .loadClass(commandLine.getOptionValue(EPACKAGE_CLASS));
        inClazz.getMethod("init").invoke(null);

        ResourceSet resourceSet = new ResourceSetImpl();
        resourceSet.getResourceFactoryRegistry().getProtocolToFactoryMap()
                .put(NeoBlueprintsURI.NEO_GRAPH_SCHEME, PersistentResourceFactory.eINSTANCE);

        Resource resource = resourceSet.createResource(uri);

        Map<String, Object> loadOpts = new HashMap<String, Object>();

        if (commandLine.hasOption(OPTIONS_FILE)) {
            Properties properties = new Properties();
            properties.load(new FileInputStream(new File(commandLine.getOptionValue(OPTIONS_FILE))));
            for (final Entry<Object, Object> entry : properties.entrySet()) {
                loadOpts.put((String) entry.getKey(), (String) entry.getValue());
            }
        }
        resource.load(loadOpts);

        LOG.log(Level.INFO, "Start counting");
        int count = 0;
        long begin = System.currentTimeMillis();
        for (Iterator<EObject> iterator = resource.getAllContents(); iterator.hasNext(); iterator
                .next(), count++)
            ;
        long end = System.currentTimeMillis();
        LOG.log(Level.INFO, "End counting");
        LOG.log(Level.INFO, MessageFormat.format("Resource {0} contains {1} elements", uri, count));
        LOG.log(Level.INFO, MessageFormat.format("Time spent: {0}", MessageUtil.formatMillis(end - begin)));

        if (resource instanceof PersistentResourceImpl) {
            PersistentResourceImpl.shutdownWithoutUnload((PersistentResourceImpl) resource);
        } else {
            resource.unload();
        }

    } catch (ParseException e) {
        MessageUtil.showError(e.toString());
        MessageUtil.showError("Current arguments: " + Arrays.toString(args));
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("java -jar <this-file.jar>", options, true);
    } catch (Throwable e) {
        MessageUtil.showError(e.toString());
    }
}

From source file:hu.bme.mit.sette.run.Run.java

public static void main(String[] args) {
    LOG.debug("main() called");

    // parse properties
    Properties prop = new Properties();
    InputStream is = null;//  w w w.ja va  2  s. c  o m

    try {
        is = new FileInputStream(SETTE_PROPERTIES);
        prop.load(is);
    } catch (IOException e) {
        System.err.println("Parsing  " + SETTE_PROPERTIES + " has failed");
        e.printStackTrace();
        System.exit(1);
    } finally {
        IOUtils.closeQuietly(is);
    }

    String[] basedirs = StringUtils.split(prop.getProperty("basedir"), '|');
    String snippetDir = prop.getProperty("snippet-dir");
    String snippetProject = prop.getProperty("snippet-project");
    String catgPath = prop.getProperty("catg");
    String catgVersionFile = prop.getProperty("catg-version-file");
    String jPETPath = prop.getProperty("jpet");
    String jPETDefaultBuildXml = prop.getProperty("jpet-default-build.xml");
    String jPETVersionFile = prop.getProperty("jpet-version-file");
    String spfPath = prop.getProperty("spf");
    String spfDefaultBuildXml = prop.getProperty("spf-default-build.xml");
    String spfVersionFile = prop.getProperty("spf-version-file");
    String outputDir = prop.getProperty("output-dir");

    Validate.notEmpty(basedirs, "At least one basedir must be specified in " + SETTE_PROPERTIES);
    Validate.notBlank(snippetDir, "The property snippet-dir must be set in " + SETTE_PROPERTIES);
    Validate.notBlank(snippetProject, "The property snippet-project must be set in " + SETTE_PROPERTIES);
    Validate.notBlank(catgPath, "The property catg must be set in " + SETTE_PROPERTIES);
    Validate.notBlank(jPETPath, "The property jpet must be set in " + SETTE_PROPERTIES);
    Validate.notBlank(spfPath, "The property spf must be set in " + SETTE_PROPERTIES);
    Validate.notBlank(outputDir, "The property output-dir must be set in " + SETTE_PROPERTIES);

    String basedir = null;
    for (String bd : basedirs) {
        bd = StringUtils.trimToEmpty(bd);

        if (bd.startsWith("~")) {
            // Linux home
            bd = System.getProperty("user.home") + bd.substring(1);
        }

        FileValidator v = new FileValidator(new File(bd));
        v.type(FileType.DIRECTORY);

        if (v.isValid()) {
            basedir = bd;
            break;
        }
    }

    if (basedir == null) {
        System.err.println("basedir = " + Arrays.toString(basedirs));
        System.err.println("ERROR: No valid basedir was found, please check " + SETTE_PROPERTIES);
        System.exit(2);
    }

    BASEDIR = new File(basedir);
    SNIPPET_DIR = new File(basedir, snippetDir);
    SNIPPET_PROJECT = snippetProject;
    OUTPUT_DIR = new File(basedir, outputDir);

    try {
        String catgVersion = readToolVersion(new File(BASEDIR, catgVersionFile));
        if (catgVersion != null) {
            new CatgTool(new File(BASEDIR, catgPath), catgVersion);
        }

        String jPetVersion = readToolVersion(new File(BASEDIR, jPETVersionFile));
        if (jPetVersion != null) {
            new JPetTool(new File(BASEDIR, jPETPath), new File(BASEDIR, jPETDefaultBuildXml), jPetVersion);
        }

        String spfVersion = readToolVersion(new File(BASEDIR, spfVersionFile));
        if (spfVersion != null) {
            new SpfTool(new File(BASEDIR, spfPath), new File(BASEDIR, spfDefaultBuildXml), spfVersion);
        }

        // TODO stuff
        stuff(args);
    } catch (Exception e) {
        System.err.println(ExceptionUtils.getStackTrace(e));

        ValidatorException vex = (ValidatorException) e;

        for (ValidationException v : vex.getValidator().getAllExceptions()) {
            v.printStackTrace();
        }

        // System.exit(0);

        e.printStackTrace();
        System.err.println("==========");
        e.printStackTrace();

        if (e instanceof ValidatorException) {
            System.err.println("Details:");
            System.err.println(((ValidatorException) e).getFullMessage());
        } else if (e.getCause() instanceof ValidatorException) {
            System.err.println("Details:");
            System.err.println(((ValidatorException) e.getCause()).getFullMessage());
        }
    }
}

From source file:fr.inria.atlanmod.kyanos.benchmarks.KyanosGraphQueryRenameAllMethods.java

public static void main(String[] args) {
    Options options = new Options();

    Option inputOpt = OptionBuilder.create(IN);
    inputOpt.setArgName("INPUT");
    inputOpt.setDescription("Input Kyanos resource directory");
    inputOpt.setArgs(1);//from  ww w .j av a 2  s  .c om
    inputOpt.setRequired(true);

    Option inClassOpt = OptionBuilder.create(EPACKAGE_CLASS);
    inClassOpt.setArgName("CLASS");
    inClassOpt.setDescription("FQN of EPackage implementation class");
    inClassOpt.setArgs(1);
    inClassOpt.setRequired(true);

    Option optFileOpt = OptionBuilder.create(OPTIONS_FILE);
    optFileOpt.setArgName("FILE");
    optFileOpt.setDescription("Properties file holding the options to be used in the Kyanos Resource");
    optFileOpt.setArgs(1);

    options.addOption(inputOpt);
    options.addOption(inClassOpt);
    options.addOption(optFileOpt);

    CommandLineParser parser = new PosixParser();

    try {
        PersistenceBackendFactoryRegistry.getFactories().put(NeoBlueprintsURI.NEO_GRAPH_SCHEME,
                new BlueprintsPersistenceBackendFactory());

        CommandLine commandLine = parser.parse(options, args);

        URI uri = NeoBlueprintsURI.createNeoGraphURI(new File(commandLine.getOptionValue(IN)));

        Class<?> inClazz = KyanosGraphQueryRenameAllMethods.class.getClassLoader()
                .loadClass(commandLine.getOptionValue(EPACKAGE_CLASS));
        inClazz.getMethod("init").invoke(null);

        ResourceSet resourceSet = new ResourceSetImpl();
        resourceSet.getResourceFactoryRegistry().getProtocolToFactoryMap()
                .put(NeoBlueprintsURI.NEO_GRAPH_SCHEME, PersistentResourceFactory.eINSTANCE);

        Resource resource = resourceSet.createResource(uri);

        Map<String, Object> loadOpts = new HashMap<String, Object>();

        if (commandLine.hasOption(OPTIONS_FILE)) {
            Properties properties = new Properties();
            properties.load(new FileInputStream(new File(commandLine.getOptionValue(OPTIONS_FILE))));
            for (final Entry<Object, Object> entry : properties.entrySet()) {
                loadOpts.put((String) entry.getKey(), (String) entry.getValue());
            }
        }
        resource.load(loadOpts);
        String name = UUID.randomUUID().toString();
        {
            LOG.log(Level.INFO, "Start query");
            long begin = System.currentTimeMillis();
            JavaQueries.renameAllMethods(resource, name);
            long end = System.currentTimeMillis();
            resource.save(Collections.emptyMap());
            LOG.log(Level.INFO, "End query");
            LOG.log(Level.INFO, MessageFormat.format("Time spent: {0}", MessageUtil.formatMillis(end - begin)));
        }

        if (resource instanceof PersistentResourceImpl) {
            PersistentResourceImpl.shutdownWithoutUnload((PersistentResourceImpl) resource);
        } else {
            resource.unload();
        }

    } catch (ParseException e) {
        MessageUtil.showError(e.toString());
        MessageUtil.showError("Current arguments: " + Arrays.toString(args));
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("java -jar <this-file.jar>", options, true);
    } catch (Throwable e) {
        MessageUtil.showError(e.toString());
    }
}