Example usage for java.io PrintStream close

List of usage examples for java.io PrintStream close

Introduction

In this page you can find the example usage for java.io PrintStream close.

Prototype

public void close() 

Source Link

Document

Closes the stream.

Usage

From source file:org.apache.jackrabbit.oak.benchmark.BenchmarkRunner.java

public static void main(String[] args) throws Exception {
    OptionParser parser = new OptionParser();
    OptionSpec<File> base = parser.accepts("base", "Base directory").withRequiredArg().ofType(File.class)
            .defaultsTo(new File("target"));
    OptionSpec<String> host = parser.accepts("host", "MongoDB host").withRequiredArg().defaultsTo("localhost");
    OptionSpec<Integer> port = parser.accepts("port", "MongoDB port").withRequiredArg().ofType(Integer.class)
            .defaultsTo(27017);/*from  w  ww  .  j a va 2 s .c o m*/
    OptionSpec<String> dbName = parser.accepts("db", "MongoDB database").withRequiredArg();
    OptionSpec<String> mongouri = parser.accepts("mongouri", "MongoDB URI").withRequiredArg();
    OptionSpec<Boolean> dropDBAfterTest = parser
            .accepts("dropDBAfterTest", "Whether to drop the MongoDB database after the test").withOptionalArg()
            .ofType(Boolean.class).defaultsTo(true);
    OptionSpec<String> rdbjdbcuri = parser.accepts("rdbjdbcuri", "RDB JDBC URI").withOptionalArg()
            .defaultsTo("jdbc:h2:target/benchmark");
    OptionSpec<String> rdbjdbcuser = parser.accepts("rdbjdbcuser", "RDB JDBC user").withOptionalArg()
            .defaultsTo("");
    OptionSpec<String> rdbjdbcpasswd = parser.accepts("rdbjdbcpasswd", "RDB JDBC password").withOptionalArg()
            .defaultsTo("");
    OptionSpec<String> rdbjdbctableprefix = parser.accepts("rdbjdbctableprefix", "RDB JDBC table prefix")
            .withOptionalArg().defaultsTo("");
    OptionSpec<Boolean> mmap = parser.accepts("mmap", "TarMK memory mapping").withOptionalArg()
            .ofType(Boolean.class).defaultsTo("64".equals(System.getProperty("sun.arch.data.model")));
    OptionSpec<Integer> cache = parser.accepts("cache", "cache size (MB)").withRequiredArg()
            .ofType(Integer.class).defaultsTo(100);
    OptionSpec<Integer> fdsCache = parser.accepts("blobCache", "cache size (MB)").withRequiredArg()
            .ofType(Integer.class).defaultsTo(32);
    OptionSpec<File> wikipedia = parser.accepts("wikipedia", "Wikipedia dump").withRequiredArg()
            .ofType(File.class);
    OptionSpec<Boolean> luceneIndexOnFS = parser.accepts("luceneIndexOnFS", "Store Lucene index on file system")
            .withOptionalArg().ofType(Boolean.class).defaultsTo(false);
    OptionSpec<Boolean> withStorage = parser.accepts("storage", "Index storage enabled").withOptionalArg()
            .ofType(Boolean.class);
    OptionSpec<String> withServer = parser.accepts("server", "Solr server host").withOptionalArg()
            .ofType(String.class);
    OptionSpec<Boolean> runAsAdmin = parser.accepts("runAsAdmin", "Run test using admin session")
            .withRequiredArg().ofType(Boolean.class).defaultsTo(Boolean.FALSE);
    OptionSpec<String> runAsUser = parser.accepts("runAsUser", "Run test using admin, anonymous or a test user")
            .withOptionalArg().ofType(String.class).defaultsTo("admin");
    OptionSpec<Boolean> runWithToken = parser
            .accepts("runWithToken", "Run test using a login token vs. simplecredentials").withOptionalArg()
            .ofType(Boolean.class).defaultsTo(Boolean.FALSE);
    OptionSpec<Integer> noIterations = parser
            .accepts("noIterations", "Change default 'passwordHashIterations' parameter.").withOptionalArg()
            .ofType(Integer.class).defaultsTo(AbstractLoginTest.DEFAULT_ITERATIONS);
    OptionSpec<Long> expiration = parser.accepts("expiration", "Expiration time (e.g. principal cache.")
            .withOptionalArg().ofType(Long.class).defaultsTo(AbstractLoginTest.NO_CACHE);
    OptionSpec<Integer> numberOfGroups = parser.accepts("numberOfGroups", "Number of groups to create.")
            .withOptionalArg().ofType(Integer.class)
            .defaultsTo(LoginWithMembershipTest.NUMBER_OF_GROUPS_DEFAULT);
    OptionSpec<Boolean> nestedGroups = parser.accepts("nestedGroups", "Use nested groups.").withOptionalArg()
            .ofType(Boolean.class).defaultsTo(false);
    OptionSpec<Integer> batchSize = parser.accepts("batchSize", "Batch size before persisting operations.")
            .withOptionalArg().ofType(Integer.class).defaultsTo(AddMembersTest.DEFAULT_BATCH_SIZE);
    OptionSpec<String> importBehavior = parser.accepts("importBehavior", "Protected Item Import Behavior")
            .withOptionalArg().ofType(String.class).defaultsTo(ImportBehavior.NAME_BESTEFFORT);
    OptionSpec<Integer> itemsToRead = parser.accepts("itemsToRead", "Number of items to read").withRequiredArg()
            .ofType(Integer.class).defaultsTo(1000);
    OptionSpec<Integer> concurrency = parser.accepts("concurrency", "Number of test threads.").withRequiredArg()
            .ofType(Integer.class).withValuesSeparatedBy(',');
    OptionSpec<Boolean> report = parser.accepts("report", "Whether to output intermediate results")
            .withOptionalArg().ofType(Boolean.class).defaultsTo(Boolean.FALSE);
    OptionSpec<Boolean> randomUser = parser.accepts("randomUser", "Whether to use a random user to read.")
            .withOptionalArg().ofType(Boolean.class).defaultsTo(Boolean.FALSE);
    OptionSpec<File> csvFile = parser.accepts("csvFile", "File to write a CSV version of the benchmark data.")
            .withOptionalArg().ofType(File.class);
    OptionSpec<Boolean> flatStructure = parser
            .accepts("flatStructure", "Whether the test should use a flat structure or not.").withOptionalArg()
            .ofType(Boolean.class).defaultsTo(Boolean.FALSE);
    OptionSpec<Integer> numberOfUsers = parser.accepts("numberOfUsers").withOptionalArg().ofType(Integer.class)
            .defaultsTo(10000);
    OptionSpec<Boolean> setScope = parser
            .accepts("setScope", "Whether to use include setScope in the user query.").withOptionalArg()
            .ofType(Boolean.class).defaultsTo(Boolean.FALSE);
    OptionSpec<Boolean> reverseOrder = parser
            .accepts("reverseOrder", "Invert order of configurations in composite setup.").withOptionalArg()
            .ofType(Boolean.class).defaultsTo(Boolean.FALSE);
    OptionSpec<String> supportedPaths = parser.accepts("supportedPaths", "Supported paths in composite setup.")
            .withOptionalArg().ofType(String.class).withValuesSeparatedBy(',');
    OptionSpec<Boolean> dynamicMembership = parser
            .accepts("dynamicMembership",
                    "Enable dynamic membership handling during synchronisation of external users.")
            .withOptionalArg().ofType(Boolean.class).defaultsTo(Boolean.FALSE);
    OptionSpec<String> autoMembership = parser
            .accepts("autoMembership",
                    "Ids of those groups a given external identity automatically become member of.")
            .withOptionalArg().ofType(String.class).withValuesSeparatedBy(',');
    OptionSpec<String> nonOption = parser.nonOptions();
    OptionSpec help = parser.acceptsAll(asList("h", "?", "help"), "show help").forHelp();
    OptionSet options = parser.parse(args);

    if (options.has(help)) {
        parser.printHelpOn(System.out);
        System.exit(0);
    }

    String uri = mongouri.value(options);
    if (uri == null) {
        String db = dbName.value(options);
        if (db == null) {
            db = OakFixture.getUniqueDatabaseName(OakFixture.OAK_MONGO);
        }
        uri = "mongodb://" + host.value(options) + ":" + port.value(options) + "/" + db;
    }
    int cacheSize = cache.value(options);
    RepositoryFixture[] allFixtures = new RepositoryFixture[] {
            new JackrabbitRepositoryFixture(base.value(options), cacheSize),
            OakRepositoryFixture.getMemoryNS(cacheSize * MB),
            OakRepositoryFixture.getMongo(uri, dropDBAfterTest.value(options), cacheSize * MB),
            OakRepositoryFixture.getMongoWithFDS(uri, dropDBAfterTest.value(options), cacheSize * MB,
                    base.value(options), fdsCache.value(options)),
            OakRepositoryFixture.getMongoNS(uri, dropDBAfterTest.value(options), cacheSize * MB),
            OakRepositoryFixture.getTar(base.value(options), 256, cacheSize, mmap.value(options)),
            OakRepositoryFixture.getTarWithBlobStore(base.value(options), 256, cacheSize, mmap.value(options)),
            OakRepositoryFixture.getSegmentTar(base.value(options), 256, cacheSize, mmap.value(options)),
            OakRepositoryFixture.getSegmentTarWithBlobStore(base.value(options), 256, cacheSize,
                    mmap.value(options)),
            OakRepositoryFixture.getRDB(rdbjdbcuri.value(options), rdbjdbcuser.value(options),
                    rdbjdbcpasswd.value(options), rdbjdbctableprefix.value(options),
                    dropDBAfterTest.value(options), cacheSize * MB) };
    OakRepositoryFixture.getRDBWithFDS(rdbjdbcuri.value(options), rdbjdbcuser.value(options),
            rdbjdbcpasswd.value(options), rdbjdbctableprefix.value(options), dropDBAfterTest.value(options),
            cacheSize * MB, base.value(options), fdsCache.value(options));
    Benchmark[] allBenchmarks = new Benchmark[] { new OrderedIndexQueryOrderedIndexTest(),
            new OrderedIndexQueryStandardIndexTest(), new OrderedIndexQueryNoIndexTest(),
            new OrderedIndexInsertOrderedPropertyTest(), new OrderedIndexInsertStandardPropertyTest(),
            new OrderedIndexInsertNoIndexTest(),
            new LoginTest(runAsUser.value(options), runWithToken.value(options), noIterations.value(options)),
            new LoginLogoutTest(runAsUser.value(options), runWithToken.value(options),
                    noIterations.value(options)),
            new LoginGetRootLogoutTest(
                    runAsUser.value(options), runWithToken.value(options), noIterations.value(options)),
            new LoginSystemTest(), new LoginImpersonateTest(),
            new LoginWithMembershipTest(runWithToken.value(options), noIterations.value(options),
                    numberOfGroups.value(options), nestedGroups.value(options), expiration.value(options)),
            new LoginWithMembersTest(runWithToken.value(options), noIterations.value(options),
                    numberOfGroups.value(options), expiration.value(options)),
            new NamespaceTest(), new NamespaceRegistryTest(), new ReadPropertyTest(), GetNodeTest.withAdmin(),
            GetNodeTest.withAnonymous(), new GetDeepNodeTest(), new SetPropertyTest(),
            new SetMultiPropertyTest(), new SmallFileReadTest(), new SmallFileWriteTest(),
            new ConcurrentReadTest(), new ConcurrentReadWriteTest(), new ConcurrentWriteReadTest(),
            new ConcurrentWriteTest(), new SimpleSearchTest(), new UUIDLookupTest(), new SQL2SearchTest(),
            new DescendantSearchTest(), new SQL2DescendantSearchTest(), new FlatTreeUpdateTest(),
            new CreateManyChildNodesTest(), new CreateManyNodesTest(), new UpdateManyChildNodesTest(),
            new TransientManyChildNodesTest(),
            new WikipediaImport(wikipedia.value(options), flatStructure.value(options), report.value(options)),
            new RepositoryGrowthTest(wikipedia.value(options), base.value(options),
                    luceneIndexOnFS.value(options)),
            new CreateNodesBenchmark(), new ManyNodes(), new ObservationTest(), new RevisionGCTest(),
            new ContinuousRevisionGCTest(), new XmlImportTest(), new FlatTreeWithAceForSamePrincipalTest(),
            new ReadDeepTreeTest(runAsAdmin.value(options), itemsToRead.value(options), report.value(options)),
            new CompositeAuthorizationTest(runAsAdmin.value(options), itemsToRead.value(options)), // NOTE: this is currently the no of configurations
            new CugTest(runAsAdmin.value(options), itemsToRead.value(options), randomUser.value(options),
                    supportedPaths.values(options), reverseOrder.value(options)),
            new CugOakTest(runAsAdmin.value(options), itemsToRead.value(options), randomUser.value(options),
                    supportedPaths.values(options), reverseOrder.value(options)),
            new ConcurrentReadDeepTreeTest(runAsAdmin.value(options), itemsToRead.value(options),
                    report.value(options)),
            new ConcurrentReadSinglePolicyTreeTest(runAsAdmin.value(options), itemsToRead.value(options),
                    report.value(options)),
            new ConcurrentReadAccessControlledTreeTest(runAsAdmin.value(options), itemsToRead.value(options),
                    report.value(options)),
            new ConcurrentReadAccessControlledTreeTest2(runAsAdmin.value(options), itemsToRead.value(options),
                    report.value(options)),
            new ConcurrentReadRandomNodeAndItsPropertiesTest(runAsAdmin.value(options),
                    itemsToRead.value(options), report.value(options)),
            new ConcurrentHasPermissionTest(runAsAdmin.value(options), itemsToRead.value(options),
                    report.value(options)),
            new ConcurrentHasPermissionTest2(runAsAdmin.value(options), itemsToRead.value(options),
                    report.value(options)),
            new ManyUserReadTest(runAsAdmin.value(options), itemsToRead.value(options), report.value(options),
                    randomUser.value(options)),
            new ConcurrentTraversalTest(runAsAdmin.value(options), itemsToRead.value(options),
                    report.value(options), randomUser.value(options)),
            new ConcurrentWriteACLTest(itemsToRead.value(options)),
            new ConcurrentEveryoneACLTest(runAsAdmin.value(options), itemsToRead.value(options)),
            ReadManyTest.linear("LinearReadEmpty", 1, ReadManyTest.EMPTY),
            ReadManyTest.linear("LinearReadFiles", 1, ReadManyTest.FILES),
            ReadManyTest.linear("LinearReadNodes", 1, ReadManyTest.NODES),
            ReadManyTest.uniform("UniformReadEmpty", 1, ReadManyTest.EMPTY),
            ReadManyTest.uniform("UniformReadFiles", 1, ReadManyTest.FILES),
            ReadManyTest.uniform("UniformReadNodes", 1, ReadManyTest.NODES), new ConcurrentCreateNodesTest(),
            new SequentialCreateNodesTest(), new CreateManyIndexedNodesTest(), new GetPoliciesTest(),
            new ConcurrentFileWriteTest(),
            new GetAuthorizableByIdTest(numberOfUsers.value(options), flatStructure.value(options)),
            new GetAuthorizableByPrincipalTest(numberOfUsers.value(options), flatStructure.value(options)),
            new GetPrincipalTest(numberOfUsers.value(options), flatStructure.value(options)),
            new GetGroupPrincipalsTest(numberOfGroups.value(options), nestedGroups.value(options)),

            // benchmarks adding multiple or single members
            new AddMembersTest(numberOfUsers.value(options), batchSize.value(options),
                    importBehavior.value(options)),
            new AddMemberTest(numberOfUsers.value(options), batchSize.value(options)),

            // benchmarks removing multiple or single members
            new RemoveMembersTest(numberOfUsers.value(options), batchSize.value(options)),
            new RemoveMemberTest(numberOfUsers.value(options), batchSize.value(options)),

            // benchmark testing isMember/isDeclared member; each user only being member of 1 group
            new IsMemberTest(numberOfUsers.value(options), nestedGroups.value(options)),
            new IsDeclaredMemberTest(numberOfUsers.value(options), nestedGroups.value(options)),

            // 4 benchmarks with the same setup test various membership operations.
            new MemberDeclaredMemberOf(numberOfGroups.value(options), nestedGroups.value(options),
                    numberOfUsers.value(options)),
            new MemberMemberOf(numberOfGroups.value(options), nestedGroups.value(options),
                    numberOfUsers.value(options)),
            new MemberIsDeclaredMember(numberOfGroups.value(options), nestedGroups.value(options),
                    numberOfUsers.value(options)),
            new MemberIsMember(numberOfGroups.value(options), nestedGroups.value(options),
                    numberOfUsers.value(options)),

            new FullTextSearchTest(wikipedia.value(options), flatStructure.value(options),
                    report.value(options), withStorage.value(options)),
            new FullTextSolrSearchTest(wikipedia.value(options), flatStructure.value(options),
                    report.value(options), withStorage.value(options), withServer.value(options)),
            new FindAuthorizableWithScopeTest(numberOfUsers.value(options), setScope.value(options)),
            new LucenePropertyFullTextTest(wikipedia.value(options), flatStructure.value(options),
                    report.value(options), withStorage.value(options)),
            new LucenePropertyFTSeparated(wikipedia.value(options), flatStructure.value(options),
                    report.value(options), withStorage.value(options)),
            new ReplicaCrashResilienceTest(),

            // benchmarks for oak-auth-external
            new ExternalLoginTest(numberOfUsers.value(options), numberOfGroups.value(options),
                    expiration.value(options), dynamicMembership.value(options),
                    autoMembership.values(options)),
            new SyncAllExternalUsersTest(numberOfUsers.value(options), numberOfGroups.value(options),
                    expiration.value(options), dynamicMembership.value(options),
                    autoMembership.values(options)),
            new SyncExternalUsersTest(numberOfUsers.value(options), numberOfGroups.value(options),
                    expiration.value(options), dynamicMembership.value(options), autoMembership.values(options),
                    batchSize.value(options)) };

    Set<String> argset = Sets.newHashSet(nonOption.values(options));
    List<RepositoryFixture> fixtures = Lists.newArrayList();
    for (RepositoryFixture fixture : allFixtures) {
        if (argset.remove(fixture.toString())) {
            fixtures.add(fixture);
        }
    }

    if (fixtures.isEmpty()) {
        System.err.println("Warning: no repository fixtures specified, supported fixtures are: "
                + asSortedString(Arrays.asList(allFixtures)));
    }

    List<Benchmark> benchmarks = Lists.newArrayList();
    for (Benchmark benchmark : allBenchmarks) {
        if (argset.remove(benchmark.toString())) {
            benchmarks.add(benchmark);
        }
    }

    if (benchmarks.isEmpty()) {
        System.err.println("Warning: no benchmarks specified, supported benchmarks are: "
                + asSortedString(Arrays.asList(allBenchmarks)));
    }

    if (argset.isEmpty()) {
        PrintStream out = null;
        if (options.has(csvFile)) {
            out = new PrintStream(FileUtils.openOutputStream(csvFile.value(options), true));
        }
        for (Benchmark benchmark : benchmarks) {
            if (benchmark instanceof CSVResultGenerator) {
                ((CSVResultGenerator) benchmark).setPrintStream(out);
            }
            benchmark.run(fixtures, options.valuesOf(concurrency));
        }
        if (out != null) {
            out.close();
        }
    } else {
        System.err.println("Unknown arguments: " + argset);
    }
}

From source file:cc.twittertools.util.VerifySubcollection.java

@SuppressWarnings("static-access")
public static void main(String[] args) throws Exception {
    Options options = new Options();

    options.addOption(OptionBuilder.withArgName("dir").hasArg().withDescription("source collection directory")
            .create(COLLECTION_OPTION));
    options.addOption(/* w w w.j ava2  s  .  com*/
            OptionBuilder.withArgName("file").hasArg().withDescription("list of tweetids").create(ID_OPTION));

    CommandLine cmdline = null;
    CommandLineParser parser = new GnuParser();
    try {
        cmdline = parser.parse(options, args);
    } catch (ParseException exp) {
        System.err.println("Error parsing command line: " + exp.getMessage());
        System.exit(-1);
    }

    if (!cmdline.hasOption(COLLECTION_OPTION) || !cmdline.hasOption(ID_OPTION)) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(ExtractSubcollection.class.getName(), options);
        System.exit(-1);
    }

    String collectionPath = cmdline.getOptionValue(COLLECTION_OPTION);

    LongOpenHashSet tweetids = new LongOpenHashSet();
    File tweetidsFile = new File(cmdline.getOptionValue(ID_OPTION));
    if (!tweetidsFile.exists()) {
        System.err.println("Error: " + tweetidsFile + " does not exist!");
        System.exit(-1);
    }
    LOG.info("Reading tweetids from " + tweetidsFile);

    FileInputStream fin = new FileInputStream(tweetidsFile);
    BufferedReader br = new BufferedReader(new InputStreamReader(fin));

    String s;
    while ((s = br.readLine()) != null) {
        tweetids.add(Long.parseLong(s));
    }
    br.close();
    fin.close();
    LOG.info("Read " + tweetids.size() + " tweetids.");

    File file = new File(collectionPath);
    if (!file.exists()) {
        System.err.println("Error: " + file + " does not exist!");
        System.exit(-1);
    }

    LongOpenHashSet seen = new LongOpenHashSet();
    TreeMap<Long, String> tweets = Maps.newTreeMap();

    PrintStream out = new PrintStream(System.out, true, "UTF-8");
    StatusStream stream = new JsonStatusCorpusReader(file);
    Status status;
    int cnt = 0;
    while ((status = stream.next()) != null) {
        if (!tweetids.contains(status.getId())) {
            LOG.error("tweetid " + status.getId() + " doesn't belong in collection");
            continue;
        }
        if (seen.contains(status.getId())) {
            LOG.error("tweetid " + status.getId() + " already seen!");
            continue;
        }

        tweets.put(status.getId(), status.getJsonObject().toString());
        seen.add(status.getId());
        cnt++;
    }
    LOG.info("total of " + cnt + " tweets in subcollection.");

    for (Map.Entry<Long, String> entry : tweets.entrySet()) {
        out.println(entry.getValue());
    }

    stream.close();
    out.close();
}

From source file:com.oltpbenchmark.DBWorkload.java

/**
 * @param args/*from w w w .  jav a 2  s. c om*/
 * @throws Exception 
 */
public static void main(String[] args) throws Exception {
    // Initialize log4j
    String log4jPath = System.getProperty("log4j.configuration");
    if (log4jPath != null) {
        org.apache.log4j.PropertyConfigurator.configure(log4jPath);
    } else {
        throw new RuntimeException("Missing log4j.properties file");
    }

    // create the command line parser
    CommandLineParser parser = new PosixParser();
    XMLConfiguration pluginConfig = null;
    try {
        pluginConfig = new XMLConfiguration("config/plugin.xml");
    } catch (ConfigurationException e1) {
        LOG.info("Plugin configuration file config/plugin.xml is missing");
        e1.printStackTrace();
    }
    pluginConfig.setExpressionEngine(new XPathExpressionEngine());
    Options options = new Options();
    options.addOption("b", "bench", true,
            "[required] Benchmark class. Currently supported: " + pluginConfig.getList("/plugin//@name"));
    options.addOption("c", "config", true, "[required] Workload configuration file");
    options.addOption(null, "create", true, "Initialize the database for this benchmark");
    options.addOption(null, "clear", true, "Clear all records in the database for this benchmark");
    options.addOption(null, "load", true, "Load data using the benchmark's data loader");
    options.addOption(null, "execute", true, "Execute the benchmark workload");
    options.addOption(null, "runscript", true, "Run an SQL script");
    options.addOption(null, "upload", true, "Upload the result");

    options.addOption("v", "verbose", false, "Display Messages");
    options.addOption("h", "help", false, "Print this help");
    options.addOption("s", "sample", true, "Sampling window");
    options.addOption("ss", false, "Verbose Sampling per Transaction");
    options.addOption("o", "output", true, "Output file (default System.out)");
    options.addOption("d", "directory", true,
            "Base directory for the result files, default is current directory");
    options.addOption("t", "timestamp", false,
            "Each result file is prepended with a timestamp for the beginning of the experiment");
    options.addOption(null, "histograms", false, "Print txn histograms");
    options.addOption(null, "dialects-export", true, "Export benchmark SQL to a dialects file");

    // parse the command line arguments
    CommandLine argsLine = parser.parse(options, args);
    if (argsLine.hasOption("h")) {
        printUsage(options);
        return;
    } else if (argsLine.hasOption("c") == false) {
        LOG.error("Missing Configuration file");
        printUsage(options);
        return;
    } else if (argsLine.hasOption("b") == false) {
        LOG.fatal("Missing Benchmark Class to load");
        printUsage(options);
        return;
    }

    // If an output directory is used, store the information
    String outputDirectory = "";
    if (argsLine.hasOption("d")) {
        outputDirectory = argsLine.getOptionValue("d");
    }

    String timestampValue = "";
    if (argsLine.hasOption("t")) {
        timestampValue = String.valueOf(TimeUtil.getCurrentTime().getTime()) + "_";
    }

    //       -------------------------------------------------------------------
    //        GET PLUGIN LIST
    //       -------------------------------------------------------------------

    String plugins = argsLine.getOptionValue("b");

    String[] pluginList = plugins.split(",");
    List<BenchmarkModule> benchList = new ArrayList<BenchmarkModule>();

    // Use this list for filtering of the output
    List<TransactionType> activeTXTypes = new ArrayList<TransactionType>();

    String configFile = argsLine.getOptionValue("c");
    XMLConfiguration xmlConfig = new XMLConfiguration(configFile);
    xmlConfig.setExpressionEngine(new XPathExpressionEngine());
    int lastTxnId = 0;

    for (String plugin : pluginList) {

        // ----------------------------------------------------------------
        // WORKLOAD CONFIGURATION
        // ----------------------------------------------------------------

        String pluginTest = "";

        pluginTest = "[@bench='" + plugin + "']";

        WorkloadConfiguration wrkld = new WorkloadConfiguration();
        wrkld.setBenchmarkName(plugin);
        wrkld.setXmlConfig(xmlConfig);
        wrkld.setDBType(DatabaseType.get(xmlConfig.getString("dbtype")));
        wrkld.setDBDriver(xmlConfig.getString("driver"));
        wrkld.setDBConnection(xmlConfig.getString("DBUrl"));
        wrkld.setDBName(xmlConfig.getString("DBName"));
        wrkld.setDBUsername(xmlConfig.getString("username"));
        wrkld.setDBPassword(xmlConfig.getString("password"));
        int terminals = xmlConfig.getInt("terminals[not(@bench)]", 0);
        terminals = xmlConfig.getInt("terminals" + pluginTest, terminals);
        wrkld.setTerminals(terminals);
        wrkld.setIsolationMode(xmlConfig.getString("isolation", "TRANSACTION_SERIALIZABLE"));
        wrkld.setScaleFactor(xmlConfig.getDouble("scalefactor", 1.0));
        wrkld.setRecordAbortMessages(xmlConfig.getBoolean("recordabortmessages", false));

        int size = xmlConfig.configurationsAt("/works/work").size();
        for (int i = 1; i < size + 1; i++) {
            SubnodeConfiguration work = xmlConfig.configurationAt("works/work[" + i + "]");
            List<String> weight_strings;

            // use a workaround if there multiple workloads or single
            // attributed workload
            if (pluginList.length > 1 || work.containsKey("weights[@bench]")) {
                weight_strings = get_weights(plugin, work);
            } else {
                weight_strings = work.getList("weights[not(@bench)]");
            }
            int rate = 1;
            boolean rateLimited = true;
            boolean disabled = false;

            // can be "disabled", "unlimited" or a number
            String rate_string;
            rate_string = work.getString("rate[not(@bench)]", "");
            rate_string = work.getString("rate" + pluginTest, rate_string);
            if (rate_string.equals(RATE_DISABLED)) {
                disabled = true;
            } else if (rate_string.equals(RATE_UNLIMITED)) {
                rateLimited = false;
            } else if (rate_string.isEmpty()) {
                LOG.fatal(String.format("Please specify the rate for phase %d and workload %s", i, plugin));
                System.exit(-1);
            } else {
                try {
                    rate = Integer.parseInt(rate_string);
                    if (rate < 1) {
                        LOG.fatal("Rate limit must be at least 1. Use unlimited or disabled values instead.");
                        System.exit(-1);
                    }
                } catch (NumberFormatException e) {
                    LOG.fatal(String.format("Rate string must be '%s', '%s' or a number", RATE_DISABLED,
                            RATE_UNLIMITED));
                    System.exit(-1);
                }
            }
            Phase.Arrival arrival = Phase.Arrival.REGULAR;
            String arrive = work.getString("@arrival", "regular");
            if (arrive.toUpperCase().equals("POISSON"))
                arrival = Phase.Arrival.POISSON;

            int activeTerminals;
            activeTerminals = work.getInt("active_terminals[not(@bench)]", terminals);
            activeTerminals = work.getInt("active_terminals" + pluginTest, activeTerminals);
            if (activeTerminals > terminals) {
                System.out.println("Configuration error in work " + i + ": number of active terminals" + ""
                        + "is bigger than the total number of terminals");
                System.exit(-1);
            }
            wrkld.addWork(work.getInt("/time"), rate, weight_strings, rateLimited, disabled, activeTerminals,
                    arrival);
        } // FOR

        int numTxnTypes = xmlConfig.configurationsAt("transactiontypes" + pluginTest + "/transactiontype")
                .size();
        if (numTxnTypes == 0 && pluginList.length == 1) {
            //if it is a single workload run, <transactiontypes /> w/o attribute is used
            pluginTest = "[not(@bench)]";
            numTxnTypes = xmlConfig.configurationsAt("transactiontypes" + pluginTest + "/transactiontype")
                    .size();
        }
        wrkld.setNumTxnTypes(numTxnTypes);

        // CHECKING INPUT PHASES
        int j = 0;
        for (Phase p : wrkld.getAllPhases()) {
            j++;
            if (p.getWeightCount() != wrkld.getNumTxnTypes()) {
                LOG.fatal(String.format(
                        "Configuration files is inconsistent, phase %d contains %d weights but you defined %d transaction types",
                        j, p.getWeightCount(), wrkld.getNumTxnTypes()));
                System.exit(-1);
            }
        } // FOR

        // Generate the dialect map
        wrkld.init();

        assert (wrkld.getNumTxnTypes() >= 0);
        assert (xmlConfig != null);

        // ----------------------------------------------------------------
        // BENCHMARK MODULE
        // ----------------------------------------------------------------

        String classname = pluginConfig.getString("/plugin[@name='" + plugin + "']");

        if (classname == null) {
            throw new ParseException("Plugin " + plugin + " is undefined in config/plugin.xml");
        }
        BenchmarkModule bench = ClassUtil.newInstance(classname, new Object[] { wrkld },
                new Class<?>[] { WorkloadConfiguration.class });
        assert (benchList.get(0) != null);

        Map<String, Object> initDebug = new ListOrderedMap<String, Object>();
        initDebug.put("Benchmark", String.format("%s {%s}", plugin.toUpperCase(), classname));
        initDebug.put("Configuration", configFile);
        initDebug.put("Type", wrkld.getDBType());
        initDebug.put("Driver", wrkld.getDBDriver());
        initDebug.put("URL", wrkld.getDBConnection());
        initDebug.put("Isolation", xmlConfig.getString("isolation", "TRANSACTION_SERIALIZABLE [DEFAULT]"));
        initDebug.put("Scale Factor", wrkld.getScaleFactor());
        INIT_LOG.info(SINGLE_LINE + "\n\n" + StringUtil.formatMaps(initDebug));
        INIT_LOG.info(SINGLE_LINE);

        // Load TransactionTypes
        List<TransactionType> ttypes = new ArrayList<TransactionType>();

        // Always add an INVALID type for Carlo
        ttypes.add(TransactionType.INVALID);
        int txnIdOffset = lastTxnId;
        for (int i = 1; i < wrkld.getNumTxnTypes() + 1; i++) {
            String key = "transactiontypes" + pluginTest + "/transactiontype[" + i + "]";
            String txnName = xmlConfig.getString(key + "/name");
            int txnId = i + 1;
            if (xmlConfig.containsKey(key + "/id")) {
                txnId = xmlConfig.getInt(key + "/id");
            }
            TransactionType tmpType = bench.initTransactionType(txnName, txnId + txnIdOffset);
            // Keep a reference for filtering
            activeTXTypes.add(tmpType);
            // Add a reference for the active TTypes in this benchmark
            ttypes.add(tmpType);
            lastTxnId = i;
        } // FOR
        TransactionTypes tt = new TransactionTypes(ttypes);
        wrkld.setTransTypes(tt);
        LOG.debug("Using the following transaction types: " + tt);

        benchList.add(bench);
    }

    // Export StatementDialects
    if (isBooleanOptionSet(argsLine, "dialects-export")) {
        BenchmarkModule bench = benchList.get(0);
        if (bench.getStatementDialects() != null) {
            LOG.info("Exporting StatementDialects for " + bench);
            String xml = bench.getStatementDialects().export(bench.getWorkloadConfiguration().getDBType(),
                    bench.getProcedures().values());
            System.out.println(xml);
            System.exit(0);
        }
        throw new RuntimeException("No StatementDialects is available for " + bench);
    }

    @Deprecated
    boolean verbose = argsLine.hasOption("v");

    // Create the Benchmark's Database
    if (isBooleanOptionSet(argsLine, "create")) {
        for (BenchmarkModule benchmark : benchList) {
            CREATE_LOG.info("Creating new " + benchmark.getBenchmarkName().toUpperCase() + " database...");
            runCreator(benchmark, verbose);
            CREATE_LOG.info("Finished!");
            CREATE_LOG.info(SINGLE_LINE);
        }
    } else if (CREATE_LOG.isDebugEnabled()) {
        CREATE_LOG.debug("Skipping creating benchmark database tables");
        CREATE_LOG.info(SINGLE_LINE);
    }

    // Clear the Benchmark's Database
    if (isBooleanOptionSet(argsLine, "clear")) {
        for (BenchmarkModule benchmark : benchList) {
            CREATE_LOG.info("Resetting " + benchmark.getBenchmarkName().toUpperCase() + " database...");
            benchmark.clearDatabase();
            CREATE_LOG.info("Finished!");
            CREATE_LOG.info(SINGLE_LINE);
        }
    } else if (CREATE_LOG.isDebugEnabled()) {
        CREATE_LOG.debug("Skipping creating benchmark database tables");
        CREATE_LOG.info(SINGLE_LINE);
    }

    // Execute Loader
    if (isBooleanOptionSet(argsLine, "load")) {
        for (BenchmarkModule benchmark : benchList) {
            LOAD_LOG.info("Loading data into " + benchmark.getBenchmarkName().toUpperCase() + " database...");
            runLoader(benchmark, verbose);
            LOAD_LOG.info("Finished!");
            LOAD_LOG.info(SINGLE_LINE);
        }
    } else if (LOAD_LOG.isDebugEnabled()) {
        LOAD_LOG.debug("Skipping loading benchmark database records");
        LOAD_LOG.info(SINGLE_LINE);
    }

    // Execute a Script
    if (argsLine.hasOption("runscript")) {
        for (BenchmarkModule benchmark : benchList) {
            String script = argsLine.getOptionValue("runscript");
            SCRIPT_LOG.info("Running a SQL script: " + script);
            runScript(benchmark, script);
            SCRIPT_LOG.info("Finished!");
            SCRIPT_LOG.info(SINGLE_LINE);
        }
    }

    // Execute Workload
    if (isBooleanOptionSet(argsLine, "execute")) {
        // Bombs away!
        Results r = null;
        try {
            r = runWorkload(benchList, verbose);
        } catch (Throwable ex) {
            LOG.error("Unexpected error when running benchmarks.", ex);
            System.exit(1);
        }
        assert (r != null);

        PrintStream ps = System.out;
        PrintStream rs = System.out;
        ResultUploader ru = new ResultUploader(r, xmlConfig, argsLine);

        if (argsLine.hasOption("o")) {
            // Check if directory needs to be created
            if (outputDirectory.length() > 0) {
                FileUtil.makeDirIfNotExists(outputDirectory.split("/"));
            }

            // Build the complex path
            String baseFile = timestampValue + argsLine.getOptionValue("o");

            // Increment the filename for new results
            String nextName = FileUtil.getNextFilename(FileUtil.joinPath(outputDirectory, baseFile + ".res"));
            ps = new PrintStream(new File(nextName));
            EXEC_LOG.info("Output into file: " + nextName);

            nextName = FileUtil.getNextFilename(FileUtil.joinPath(outputDirectory, baseFile + ".raw"));
            rs = new PrintStream(new File(nextName));
            EXEC_LOG.info("Output Raw data into file: " + nextName);

            nextName = FileUtil.getNextFilename(FileUtil.joinPath(outputDirectory, baseFile + ".summary"));
            PrintStream ss = new PrintStream(new File(nextName));
            EXEC_LOG.info("Output summary data into file: " + nextName);
            ru.writeSummary(ss);
            ss.close();

            nextName = FileUtil.getNextFilename(FileUtil.joinPath(outputDirectory, baseFile + ".db.cnf"));
            ss = new PrintStream(new File(nextName));
            EXEC_LOG.info("Output db config into file: " + nextName);
            ru.writeDBParameters(ss);
            ss.close();

            nextName = FileUtil.getNextFilename(FileUtil.joinPath(outputDirectory, baseFile + ".ben.cnf"));
            ss = new PrintStream(new File(nextName));
            EXEC_LOG.info("Output benchmark config into file: " + nextName);
            ru.writeBenchmarkConf(ss);
            ss.close();
        } else if (EXEC_LOG.isDebugEnabled()) {
            EXEC_LOG.debug("No output file specified");
        }

        if (argsLine.hasOption("s")) {
            int windowSize = Integer.parseInt(argsLine.getOptionValue("s"));
            EXEC_LOG.info("Grouped into Buckets of " + windowSize + " seconds");
            r.writeCSV(windowSize, ps);

            if (isBooleanOptionSet(argsLine, "upload")) {
                ru.uploadResult();
            }

            // Allow more detailed reporting by transaction to make it easier to check
            if (argsLine.hasOption("ss")) {

                for (TransactionType t : activeTXTypes) {
                    PrintStream ts = ps;

                    if (ts != System.out) {
                        // Get the actual filename for the output
                        String baseFile = timestampValue + argsLine.getOptionValue("o") + "_" + t.getName();
                        String prepended = outputDirectory + timestampValue;
                        String nextName = FileUtil
                                .getNextFilename(FileUtil.joinPath(outputDirectory, baseFile + ".res"));
                        ts = new PrintStream(new File(nextName));
                        r.writeCSV(windowSize, ts, t);
                        ts.close();
                    }
                }
            }
        } else if (EXEC_LOG.isDebugEnabled()) {
            EXEC_LOG.warn("No bucket size specified");
        }
        if (argsLine.hasOption("histograms")) {
            EXEC_LOG.info(SINGLE_LINE);
            EXEC_LOG.info("Completed Transactions:\n" + r.getTransactionSuccessHistogram() + "\n");
            EXEC_LOG.info("Aborted Transactions:\n" + r.getTransactionAbortHistogram() + "\n");
            EXEC_LOG.info("Rejected Transactions:\n" + r.getTransactionRetryHistogram());
            EXEC_LOG.info("Unexpected Errors:\n" + r.getTransactionErrorHistogram());
            if (r.getTransactionAbortMessageHistogram().isEmpty() == false)
                EXEC_LOG.info(
                        "User Aborts:\n" + StringUtil.formatMaps(r.getTransactionAbortMessageHistogram()));
        } else if (EXEC_LOG.isDebugEnabled()) {
            EXEC_LOG.warn("No bucket size specified");
        }

        r.writeAllCSVAbsoluteTiming(rs);

        ps.close();
        rs.close();
    } else {
        EXEC_LOG.info("Skipping benchmark workload execution");
    }
}

From source file:edu.stanford.epadd.launcher.Main.java

public static void main(String args[]) throws Exception {
    setupLogging();//from   w w w  . j  av a2  s . c  om
    basicSetup(args);
    setupResources();

    out.println("Starting up ePADD on the local computer at " + BASE_URL + ", "
            + formatDateLong(new GregorianCalendar()));
    out.println("***For troubleshooting information, see this file: " + debugFile + "***\n");
    out.println("Current directory = " + System.getProperty("user.dir") + ", home directory = "
            + System.getProperty("user.home"));
    out.println("Memory status at the beginning: " + getMemoryStats());
    if (Runtime.getRuntime().maxMemory() / MB < 512)
        aggressiveWarn(
                "You are probably running ePADD without enough memory. \nIf you launched ePADD from the command line, you can increase memory with an option like java -Xmx1g",
                2000);

    // handle frequent error of user trying to launch another server when its already on
    // server.start() usually takes a few seconds to return
    // after that it takes a few seconds for the webapp to deploy
    // ignore any exceptions along the way and assume not if we can't prove it is alive
    boolean urlAlive = false;
    try {
        urlAlive = isURLAlive(MUSE_CHECK_URL);
    } catch (Exception e) {
        out.println("Exception: e");
        e.printStackTrace(out);
    }

    boolean disableStart = false;
    if (urlAlive) {
        out.println("Oh! ePADD is already running at the URL: " + BASE_URL + ", will have to kill it!");
        killRunningServer(BASE_URL);
        Thread.sleep(3000);
        try {
            urlAlive = isURLAlive(MUSE_CHECK_URL);
        } catch (Exception e) {
            out.println("Exception: e");
            e.printStackTrace(out);
        }
        if (!urlAlive)
            out.println("Good. Kill succeeded, will restart");
        else {
            String message = "Previously running ePADD still alive despite attempt to kill it, disabling fresh restart!\n";
            message += "If you just want to use the previous instance of ePADD, please go to " + BASE_URL;
            message += "\nTo kill this instance, please go to your computer's task manager and kill running java or javaw processes.\nThen try launching ePADD again.\n";
            aggressiveWarn(message, 2000);
            return;
        }
    }
    //        else
    //          out.println ("Muse not already alive at URL: ..." + URL);

    if (!disableStart) {
        out.println("Starting ePADD at URL: ..." + BASE_URL);
        try {
            server.start();
        } catch (BindException be) {
            out.println("port busy, but webapp not alive: " + BASE_URL + "\n" + be);
            throw new RuntimeException("Error: Port in use (Please kill ePADD if its already running!)\n" + be);
        }
    }

    //      webapp1.start(); -- not needed
    PrintStream debugOut1 = System.err;
    try {
        File f = new File(debugFile);
        if (f.exists())
            f.delete(); // particular problem on windows :-(
        debugOut1 = new PrintStream(new FileOutputStream(debugFile), false, "UTF-8");
    } catch (IOException ioe) {
        System.err.println("Warning: failed to delete debug file " + debugFile + " : " + ioe);
    }

    final PrintStream debugOut = debugOut1;

    Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
        public void run() {
            try {
                server.stop();
                server.destroy();
                debugOut.close();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }));

    //        InfoFrame frame = new InfoFrame();
    //        frame.doShow();

    boolean success = waitTillPageAlive(MUSE_CHECK_URL, TIMEOUT_SECS);
    //        frame.updateText ("Opening a browser window");

    if (success) {
        // best effort to start shutdown thread
        //           out.println ("Starting Muse shutdown listener at port " + JettyShutdownThread.SHUTDOWN_PORT);

        try {
            int shutdownPort = PORT + 1; // shut down port is arbitrarily set to port + 1. it is ASSUMED to be free. 

            new JettyShutdownThread(server, shutdownPort).start();
            out.println("Listening for ePADD shutdown message on port " + shutdownPort);
        } catch (Exception e) {
            out.println(
                    "Unable to start shutdown listener, you will have to stop the server manually using Cmd-Q on Mac OS or kill javaw processes on Windows");
        }

        try {
            setupSystemTrayIcon();
        } catch (Exception e) {
            System.err.println("Unable to setup system tray icon: " + e);
            e.printStackTrace(System.err);
        }

        // open browser window
        if (browserOpen) {
            preferredBrowser = null;
            // launch a browser here
            try {

                String link;
                link = "http://localhost:" + PORT + "/epadd/index.jsp";

                if (startPage != null) {
                    // startPage has to be absolute
                    link = "http://localhost:" + PORT + "/epadd/" + startPage;
                }

                if (baseDir != null)
                    link = link + "?cacheDir=" + baseDir; // typically this is used when starting from command line. note: still using name, cacheDir

                out.println("Launching URL in browser: " + link);
                launchBrowser(link);

            } catch (Exception e) {
                out.println(
                        "Warning: Unable to launch browser due to exception (use the -n option to prevent ePADD from trying to launch a browser):");
                e.printStackTrace(out);
            }
        }

        if (!noShutdown) {
            // arrange to kill Muse after a period of time, we don't want the server to run forever

            // i clearly have too much time on my hands right now...
            long secs = KILL_AFTER_MILLIS / 1000;
            long hh = secs / 3600;
            long mm = (secs % 3600) / 60;
            long ss = secs % (60);
            out.print("ePADD will shut down automatically after ");
            if (hh != 0)
                out.print(hh + " hours ");
            if (mm != 0 || (hh != 0 && ss != 0))
                out.print(mm + " minutes");
            if (ss != 0)
                out.print(ss + " seconds");
            out.println();

            Timer timer = new Timer();
            TimerTask tt = new ShutdownTimerTask();
            timer.schedule(tt, KILL_AFTER_MILLIS);
        }
    } else {
        out.println("\n\n\nSORRY!!! UNABLE TO DEPLOY WEBAPP, EXITING\n\n\n");
        //          frame.updateText("Sorry, looks like we are having trouble starting the jetty server\n");
    }

    savedSystemOut = out;
    savedSystemErr = System.err;
    System.setOut(debugOut);
    System.setErr(debugOut);
}

From source file:cc.twittertools.search.api.RunQueriesThrift.java

@SuppressWarnings("static-access")
public static void main(String[] args) throws Exception {
    Options options = new Options();

    options.addOption(OptionBuilder.withArgName("string").hasArg().withDescription("host").create(HOST_OPTION));
    options.addOption(OptionBuilder.withArgName("port").hasArg().withDescription("port").create(PORT_OPTION));
    options.addOption(OptionBuilder.withArgName("file").hasArg()
            .withDescription("file containing topics in TREC format").create(QUERIES_OPTION));
    options.addOption(OptionBuilder.withArgName("num").hasArg().withDescription("number of results to return")
            .create(NUM_RESULTS_OPTION));
    options.addOption(// ww  w . ja va  2 s  .c  o  m
            OptionBuilder.withArgName("string").hasArg().withDescription("group id").create(GROUP_OPTION));
    options.addOption(
            OptionBuilder.withArgName("string").hasArg().withDescription("access token").create(TOKEN_OPTION));
    options.addOption(
            OptionBuilder.withArgName("string").hasArg().withDescription("runtag").create(RUNTAG_OPTION));
    options.addOption(new Option(VERBOSE_OPTION, "print out complete document"));

    CommandLine cmdline = null;
    CommandLineParser parser = new GnuParser();
    try {
        cmdline = parser.parse(options, args);
    } catch (ParseException exp) {
        System.err.println("Error parsing command line: " + exp.getMessage());
        System.exit(-1);
    }

    if (!cmdline.hasOption(HOST_OPTION) || !cmdline.hasOption(PORT_OPTION)
            || !cmdline.hasOption(QUERIES_OPTION)) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(RunQueriesThrift.class.getName(), options);
        System.exit(-1);
    }

    String queryFile = cmdline.getOptionValue(QUERIES_OPTION);
    if (!new File(queryFile).exists()) {
        System.err.println("Error: " + queryFile + " doesn't exist!");
        System.exit(-1);
    }

    String runtag = cmdline.hasOption(RUNTAG_OPTION) ? cmdline.getOptionValue(RUNTAG_OPTION) : DEFAULT_RUNTAG;

    TrecTopicSet topicsFile = TrecTopicSet.fromFile(new File(queryFile));

    int numResults = 1000;
    try {
        if (cmdline.hasOption(NUM_RESULTS_OPTION)) {
            numResults = Integer.parseInt(cmdline.getOptionValue(NUM_RESULTS_OPTION));
        }
    } catch (NumberFormatException e) {
        System.err.println("Invalid " + NUM_RESULTS_OPTION + ": " + cmdline.getOptionValue(NUM_RESULTS_OPTION));
        System.exit(-1);
    }

    String group = cmdline.hasOption(GROUP_OPTION) ? cmdline.getOptionValue(GROUP_OPTION) : null;
    String token = cmdline.hasOption(TOKEN_OPTION) ? cmdline.getOptionValue(TOKEN_OPTION) : null;

    boolean verbose = cmdline.hasOption(VERBOSE_OPTION);

    PrintStream out = new PrintStream(System.out, true, "UTF-8");

    TrecSearchThriftClient client = new TrecSearchThriftClient(cmdline.getOptionValue(HOST_OPTION),
            Integer.parseInt(cmdline.getOptionValue(PORT_OPTION)), group, token);

    for (cc.twittertools.search.TrecTopic query : topicsFile) {
        List<TResult> results = client.search(query.getQuery(), query.getQueryTweetTime(), numResults);
        int i = 1;
        Set<Long> tweetIds = new HashSet<Long>();
        for (TResult result : results) {
            if (!tweetIds.contains(result.id)) {
                tweetIds.add(result.id);
                out.println(
                        String.format("%s Q0 %d %d %f %s", query.getId(), result.id, i, result.rsv, runtag));
                if (verbose) {
                    out.println("# " + result.toString().replaceAll("[\\n\\r]+", " "));
                }
                i++;
            }
        }
    }
    out.close();
}

From source file:org.fcrepo.client.test.PerformanceTests.java

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

    if (args.length < 8 || args.length > 9) {
        usage();//w  w w.j  a v  a 2s. c  o m
    }

    String host = args[0];
    String port = args[1];
    String username = args[2];
    String password = args[3];
    String itr = args[4];
    String thrds = args[5];
    String output = args[6];
    String name = args[7];
    String context = Constants.FEDORA_DEFAULT_APP_CONTEXT;

    if (args.length == 9 && !args[8].equals("")) {
        context = args[8];
    }

    if (host == null || host.startsWith("$") || port == null || port.startsWith("$") || username == null
            || username.startsWith("$") || password == null || password.startsWith("$") || itr == null
            || itr.startsWith("$") || thrds == null || thrds.startsWith("$") || output == null
            || output.startsWith("$") || name == null || name.startsWith("$")) {
        usage();
    }
    name = name.replaceAll(",", ";");
    iterations = Integer.parseInt(itr);
    threads = Integer.parseInt(thrds);

    boolean newFile = true;
    File outputFile = new File(output);

    File tempFile = null;
    BufferedReader reader = null;
    String line = "";
    if (outputFile.exists()) {
        newFile = false;

        // Create a copy of the file to read from
        tempFile = File.createTempFile("performance-test", "tmp");
        BufferedReader input = new BufferedReader(new FileReader(outputFile));
        PrintStream tempOut = new PrintStream(tempFile);

        while ((line = input.readLine()) != null) {
            tempOut.println(line);
        }
        input.close();
        tempOut.close();

        reader = new BufferedReader(new FileReader(tempFile));
    }
    PrintStream out = new PrintStream(outputFile);

    if (newFile) {
        out.println(
                "--------------------------------------------------------------" + " Performance Test Results "
                        + "--------------------------------------------------------------");
    }

    PerformanceTests tests = new PerformanceTests();
    tests.init(host, port, context, username, password);
    System.out.println("Running Ingest Round-Trip Test...");
    long ingestResults = tests.runIngestTest();
    System.out.println("Running AddDatastream Round-Trip Test...");
    long addDsResults = tests.runAddDatastreamTest();
    System.out.println("Running ModifyDatastreamByReference Round-Trip Test...");
    long modifyRefResults = tests.runModifyDatastreamByRefTest();
    System.out.println("Running ModifyDatastreamByValue Round-Trip Test...");
    long modifyValResults = tests.runModifyDatastreamByValueTest();
    System.out.println("Running PurgeDatastream Round-Trip Test...");
    long purgeDsResults = tests.runPurgeDatastreamTest();
    System.out.println("Running PurgeObject Round-Trip Test...");
    long purgeObjectResults = tests.runPurgeObjectTest();
    System.out.println("Running GetDatastream Round-Trip Test...");
    long getDatastreamResults = tests.runGetDatastreamTest();
    System.out.println("Running GetDatastreamREST Round-Trip Test...");
    long getDatastreamRestResults = tests.runGetDatastreamRestTest();
    System.out.println("Running Throughput Tests...");
    long[] tpResults = tests.runThroughputTests();
    System.out.println("Running Threaded Throughput Tests...");
    long[] tptResults = tests.runThreadedThroughputTests();

    if (newFile) {
        out.println(
                "1. Test performing each operation in isolation. Time (in ms) is the average required to perform each operation.");
        out.println(
                "test name, ingest, addDatastream, modifyDatastreamByReference, modifyDatastreamByValue, purgeDatastream, purgeObject, getDatastream, getDatastreamREST");
    } else {
        line = reader.readLine();
        while (line != null && line.length() > 2) {
            out.println(line);
            line = reader.readLine();
        }
    }
    out.println(name + ", " + ingestResults + ", " + addDsResults + ", " + modifyRefResults + ", "
            + modifyValResults + ", " + purgeDsResults + ", " + purgeObjectResults + ", "
            + getDatastreamResults / iterations + ", " + getDatastreamRestResults / iterations);

    out.println();
    if (newFile) {
        out.println("2. Operations-Per-Second based on results listed in item 1.");
        out.println(
                "test name, ingest, addDatastream, modifyDatastreamByReference, modifyDatastreamByValue, purgeDatastream, purgeObject, getDatastream, getDatastreamREST");
    } else {
        line = reader.readLine();
        while (line != null && line.length() > 2) {
            out.println(line);
            line = reader.readLine();
        }
    }
    double ingestPerSecond = 1000 / (double) ingestResults;
    double addDsPerSecond = 1000 / (double) addDsResults;
    double modifyRefPerSecond = 1000 / (double) modifyRefResults;
    double modifyValPerSecond = 1000 / (double) modifyValResults;
    double purgeDsPerSecond = 1000 / (double) purgeDsResults;
    double purgeObjPerSecond = 1000 / (double) purgeObjectResults;
    double getDatastreamPerSecond = 1000 / ((double) getDatastreamResults / iterations);
    double getDatastreamRestPerSecond = 1000 / ((double) getDatastreamRestResults / iterations);
    out.println(name + ", " + round(ingestPerSecond) + ", " + round(addDsPerSecond) + ", "
            + round(modifyRefPerSecond) + ", " + round(modifyValPerSecond) + ", " + round(purgeDsPerSecond)
            + ", " + round(purgeObjPerSecond) + ", " + round(getDatastreamPerSecond) + ", "
            + round(getDatastreamRestPerSecond));

    out.println();
    if (newFile) {
        out.println(
                "3. Test performing operations back-to-back. Time (in ms) is that required to perform all iterations.");
        out.println(
                "test name, ingest, addDatastream, modifyDatastreamByReference, modifyDatastreamByValue, purgeDatastream, purgeObject, getDatastream, getDatastreamREST");
    } else {
        line = reader.readLine();
        while (line != null && line.length() > 2) {
            out.println(line);
            line = reader.readLine();
        }
    }
    out.println(name + ", " + tpResults[0] + ", " + tpResults[1] + ", " + tpResults[2] + ", " + tpResults[3]
            + ", " + tpResults[4] + ", " + tpResults[5] + ", " + getDatastreamResults + ", "
            + getDatastreamRestResults);

    out.println();
    if (newFile) {
        out.println("4. Operations-Per-Second based on results listed in item 3.");
        out.println(
                "test name, ingest, addDatastream, modifyDatastreamByReference, modifyDatastreamByValue, purgeDatastream, purgeObject, getDatastream, getDatastreamREST");
    } else {
        line = reader.readLine();
        while (line != null && line.length() > 2) {
            out.println(line);
            line = reader.readLine();
        }
    }
    double ingestItPerSecond = (double) (iterations * 1000) / tpResults[0];
    double addDsItPerSecond = (double) (iterations * 1000) / tpResults[1];
    double modifyRefItPerSecond = (double) (iterations * 1000) / tpResults[2];
    double modifyValItPerSecond = (double) (iterations * 1000) / tpResults[3];
    double purgeDsItPerSecond = (double) (iterations * 1000) / tpResults[4];
    double purgeObjItPerSecond = (double) (iterations * 1000) / tpResults[5];
    double getDsItPerSecond = (double) (iterations * 1000) / getDatastreamResults;
    double getDsRestItPerSecond = (double) (iterations * 1000) / getDatastreamRestResults;
    out.println(name + ", " + round(ingestItPerSecond) + ", " + round(addDsItPerSecond) + ", "
            + round(modifyRefItPerSecond) + ", " + round(modifyValItPerSecond) + ", "
            + round(purgeDsItPerSecond) + ", " + round(purgeObjItPerSecond) + ", " + round(getDsItPerSecond)
            + ", " + round(getDsRestItPerSecond));

    out.println();
    if (newFile) {
        out.println(
                "5. Test performing operations using a thread pool. Time (in ms) is that required to perform all iterations.");
        out.println(
                "test name, ingest, addDatastream, modifyDatastreamByReference, modifyDatastreamByValue, purgeDatastream, purgeObject, getDatastream, getDatastreamREST");
    } else {
        line = reader.readLine();
        while (line != null && line.length() > 2) {
            out.println(line);
            line = reader.readLine();
        }
    }
    out.println(name + ", " + tptResults[0] + ", " + tptResults[1] + ", " + tptResults[2] + ", " + tptResults[3]
            + ", " + tptResults[4] + ", " + tptResults[5] + ", " + tptResults[6] + ", " + tptResults[7]);

    out.println();
    if (newFile) {
        out.println("6. Operations-Per-Second based on results listed in item 5.");
        out.println(
                "test name, ingest, addDatastream, modifyDatastreamByReference, modifyDatastreamByValue, purgeDatastream, purgeObject, getDatastream, getDatastreamREST");
    } else {
        line = reader.readLine();
        while (line != null && line.length() > 2) {
            out.println(line);
            line = reader.readLine();
        }
    }
    double thrdIngestItPerSecond = (double) (iterations * 1000) / tptResults[0];
    double thrdAddDsItPerSecond = (double) (iterations * 1000) / tptResults[1];
    double thrdModifyRefItPerSecond = (double) (iterations * 1000) / tptResults[2];
    double thrdModifyValItPerSecond = (double) (iterations * 1000) / tptResults[3];
    double thrdPurgeDsItPerSecond = (double) (iterations * 1000) / tptResults[4];
    double thrdPurgeObjItPerSecond = (double) (iterations * 1000) / tptResults[5];
    double thrdGetDsItPerSecond = (double) (iterations * 1000) / tptResults[6];
    double thrdGetDsRestItPerSecond = (double) (iterations * 1000) / tptResults[7];
    out.println(name + ", " + round(thrdIngestItPerSecond) + ", " + round(thrdAddDsItPerSecond) + ", "
            + round(thrdModifyRefItPerSecond) + ", " + round(thrdModifyValItPerSecond) + ", "
            + round(thrdPurgeDsItPerSecond) + ", " + round(thrdPurgeObjItPerSecond) + ", "
            + round(thrdGetDsItPerSecond) + ", " + round(thrdGetDsRestItPerSecond));

    if (!newFile) {
        reader.close();
        tempFile.delete();
    }
    out.close();

    System.out.println("Performance Tests Complete.");
}

From source file:edu.stanford.muse.launcher.Main.java

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

    // set javawebstart.version to a dummy value if not already set (might happen when running with java -jar from cmd line)
    // exit.jsp doesn't allow us to showdown unless this prop is set
    if (System.getProperty("javawebstart.version") == null)
        System.setProperty("javawebstart.version", "UNKNOWN");

    final int TIMEOUT_SECS = 60;
    if (args.length > 0) {
        out.print(args.length + " argument(s): ");
        for (int i = 0; i < args.length; i++)
            out.print(args[i] + " ");
        out.println();//from   w w w  .j a v a2  s .c  om
    }

    Options options = getOpt();
    CommandLineParser parser = new PosixParser();
    CommandLine cmd = parser.parse(options, args);
    if (cmd.hasOption("help")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("Muse batch mode", options);
        return;
    }

    boolean debug = false;
    if (cmd.hasOption("debug")) {
        URL url = ClassLoader.getSystemResource("log4j.properties.debug");
        out.println("Loading logging configuration from url: " + url);
        PropertyConfigurator.configure(url);
        debug = true;
    } else if (cmd.hasOption("debug-address-book")) {
        URL url = ClassLoader.getSystemResource("log4j.properties.debug.ab");
        out.println("Loading logging configuration from url: " + url);
        PropertyConfigurator.configure(url);
        debug = false;
    } else if (cmd.hasOption("debug-groups")) {
        URL url = ClassLoader.getSystemResource("log4j.properties.debug.groups");
        out.println("Loading logging configuration from url: " + url);
        PropertyConfigurator.configure(url);
        debug = false;
    }

    if (cmd.hasOption("no-browser-open"))
        browserOpen = false;

    if (cmd.hasOption("port")) {
        String portStr = cmd.getOptionValue('p');
        try {
            PORT = Integer.parseInt(portStr);
            String mesg = " Running on port: " + PORT;
            out.println(mesg);
        } catch (NumberFormatException nfe) {
            out.println("invalid port number " + portStr);
        }
    }

    if (cmd.hasOption("start-page"))
        startPage = cmd.getOptionValue("start-page");
    if (cmd.hasOption("base-dir"))
        baseDir = cmd.getOptionValue("base-dir");
    if (cmd.hasOption("search-mode"))
        searchMode = true;
    if (cmd.hasOption("amuse-mode"))
        amuseMode = true;

    System.setSecurityManager(null); // this is important
    WebAppContext webapp0 = null; // deployWarAt("root.war", "/"); // for redirecting
    String path = "/muse";
    WebAppContext webapp1 = deployWarAt("muse.war", path);
    if (webapp1 == null) {
        System.err.println("Aborting... no webapp");
        return;
    }

    // if in any debug mode, turn blurring off
    if (debug)
        webapp1.setAttribute("noblur", true);

    // we set this and its read by JSPHelper within the webapp 
    System.setProperty("muse.container", "jetty");

    // need to copy crossdomain.xml file for
    String tmp = System.getProperty("java.io.tmpdir");
    final URL url = Main.class.getClassLoader().getResource("crossdomain.xml");
    try {
        InputStream is = url.openStream();
        String file = tmp + File.separatorChar + "crossdomain.xml";
        copy_stream_to_file(is, file);
    } catch (Exception e) {
        System.err.println("Aborting..." + e);
        return;
    }
    server = new Server(PORT);
    ResourceHandler resource_handler = new ResourceHandler();
    //        resource_handler.setWelcomeFiles(new String[]{ "index.html" });
    resource_handler.setResourceBase(tmp);

    // set the header buffer size in the connectors, default is a ridiculous 4K, which causes failures any time there is
    // is a large request, such as selecting a few hundred folders. (even for posts!)
    // usually there is only one SocketConnector, so we just put the setHeaderBufferSize in a loop.
    Connector conns[] = server.getConnectors();
    for (Connector conn : conns) {
        int NEW_BUFSIZE = 1000000;
        // out.println ("Connector " + conn + " buffer size is " + conn.getHeaderBufferSize() + " setting to " + NEW_BUFSIZE);
        conn.setHeaderBufferSize(NEW_BUFSIZE);
    }

    BASE_URL = "http://localhost:" + PORT + path;
    String MUSE_CHECK_URL = BASE_URL + "/js/muse.js"; // for quick check of existing muse or successful start up. BASE_URL may take some time to run and may not always be available now that we set dirAllowed to false and public mode does not serve /muse.
    String debugFile = tmp + File.separatorChar + "debug.txt";

    HandlerList hl = new HandlerList();
    if (webapp0 != null)
        hl.setHandlers(new Handler[] { webapp1, webapp0, resource_handler });
    else
        hl.setHandlers(new Handler[] { webapp1, resource_handler });
    out.println("Starting up Muse on the local computer at " + BASE_URL + ", "
            + formatDateLong(new GregorianCalendar()));
    out.println("***For troubleshooting information, see this file: " + debugFile + "***\n");
    out.println("Current directory = " + System.getProperty("user.dir") + ", home directory = "
            + System.getProperty("user.home"));
    out.println("Memory status at the beginning: " + getMemoryStats());
    if (Runtime.getRuntime().maxMemory() / MB < 512)
        aggressiveWarn(
                "You are probably running Muse without enough memory. \nIf you launched Muse from the command line, you can increase memory with an option like java -Xmx1g",
                2000);
    server.setHandler(hl);

    // handle frequent error of user trying to launch another server when its already on
    // server.start() usually takes a few seconds to return
    // after that it takes a few seconds for the webapp to deploy
    // ignore any exceptions along the way and assume not if we can't prove it is alive
    boolean urlAlive = false;
    try {
        urlAlive = isURLAlive(MUSE_CHECK_URL);
    } catch (Exception e) {
        out.println("Exception: e");
        e.printStackTrace(out);
    }

    boolean disableStart = false;
    if (urlAlive) {
        out.println("Oh! Muse is already running at the URL: " + BASE_URL + ", will have to kill it!");
        killRunningServer(BASE_URL);
        Thread.sleep(3000);
        try {
            urlAlive = isURLAlive(MUSE_CHECK_URL);
        } catch (Exception e) {
            out.println("Exception: e");
            e.printStackTrace(out);
        }
        if (!urlAlive)
            out.println("Good. Kill succeeded, will restart");
        else {
            String message = "Previously running Muse still alive despite attempt to kill it, disabling fresh restart!\n";
            message += "If you just want to use the previous instance of Muse, please go to http://localhost:9099/muse\n";
            message += "\nTo kill this instance, please go to your computer's task manager and kill running java or javaw processes.\nThen try launching Muse again.\n";
            aggressiveWarn(message, 2000);
            return;
        }
    }
    //        else
    //          out.println ("Muse not already alive at URL: ..." + URL);

    if (!disableStart) {
        out.println("Starting Muse at URL: ..." + BASE_URL);
        try {
            server.start();
        } catch (BindException be) {
            out.println("port busy, but webapp not alive: " + BASE_URL + "\n" + be);
            throw new RuntimeException("Error: Port in use (Please kill Muse if its already running!)\n" + be);
        }
    }

    //      webapp1.start(); -- not needed
    PrintStream debugOut1 = System.err;
    try {
        File f = new File(debugFile);
        if (f.exists())
            f.delete(); // particular problem on windows :-(
        debugOut1 = new PrintStream(new FileOutputStream(debugFile), false, "UTF-8");
    } catch (IOException ioe) {
        System.err.println("Warning: failed to delete debug file " + debugFile + " : " + ioe);
    }

    final PrintStream debugOut = debugOut1;

    Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
        public void run() {
            try {
                server.stop();
                server.destroy();
                debugOut.close();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }));

    //        InfoFrame frame = new InfoFrame();
    //        frame.doShow();

    boolean success = waitTillPageAlive(MUSE_CHECK_URL, TIMEOUT_SECS);
    //        frame.updateText ("Opening a browser window");

    if (success) {
        // best effort to start shutdown thread
        //           out.println ("Starting Muse shutdown listener at port " + JettyShutdownThread.SHUTDOWN_PORT);

        try {
            int shutdownPort = PORT + 1; // shut down port is arbitrarily set to port + 1. it is ASSUMED to be free. 

            new JettyShutdownThread(server, shutdownPort).start();
            out.println("Listening for Muse shutdown message on port " + shutdownPort);
        } catch (Exception e) {
            out.println(
                    "Unable to start shutdown listener, you will have to stop the server manually using Cmd-Q on Mac OS or kill javaw processes on Windows");
        }

        try {
            setupSystemTrayIcon();
        } catch (Exception e) {
            out.println("Unable to setup system tray icon: " + e);
            e.printStackTrace(out);
        }

        // open browser window
        if (browserOpen) {
            preferredBrowser = null;
            // launch a browser here
            try {

                String link;
                if (System.getProperty("muse.mode.public") != null)
                    link = "http://localhost:" + PORT + "/muse/archives/";
                else
                    link = "http://localhost:" + PORT + "/muse/index.jsp";

                if (searchMode) {
                    String u = "http://localhost:" + PORT + "/muse/search";
                    out.println("Launching URL in browser: " + u);
                    link += "?mode=search";
                } else if (amuseMode) {
                    String u = "http://localhost:" + PORT + "/muse/amuse.jsp";
                    out.println("Launching URL in browser: " + u);
                    link = u;
                } else if (startPage != null) {
                    // startPage has to be absolute
                    link = "http://localhost:" + PORT + "/muse/" + startPage;
                }

                if (baseDir != null)
                    link = link + "?cacheDir=" + baseDir; // typically this is used when starting from command line. note: still using name, cacheDir

                out.println("Launching URL in browser: " + link);
                launchBrowser(link);

            } catch (Exception e) {
                out.println(
                        "Warning: Unable to launch browser due to exception (use the -n option to prevent Muse from trying to launch a browser):");
                e.printStackTrace(out);
            }
        }

        if (!cmd.hasOption("no-shutdown")) {
            // arrange to kill Muse after a period of time, we don't want the server to run forever

            // i clearly have too much time on my hands right now...
            long secs = KILL_AFTER_MILLIS / 1000;
            long hh = secs / 3600;
            long mm = (secs % 3600) / 60;
            long ss = secs % (60);
            out.print("Muse will shut down automatically after ");
            if (hh != 0)
                out.print(hh + " hours ");
            if (mm != 0 || (hh != 0 && ss != 0))
                out.print(mm + " minutes");
            if (ss != 0)
                out.print(ss + " seconds");
            out.println();

            Timer timer = new Timer();
            TimerTask tt = new ShutdownTimerTask();
            timer.schedule(tt, KILL_AFTER_MILLIS);
        }
    } else {
        out.println("\n\n\nSORRY!!! UNABLE TO DEPLOY WEBAPP, EXITING\n\n\n");
        //          frame.updateText("Sorry, looks like we are having trouble starting the jetty server\n");
    }

    savedSystemOut = out;
    savedSystemErr = System.err;
    System.setOut(debugOut);
    System.setErr(debugOut);
}

From source file:fr.cs.examples.conversion.PropagatorConversion.java

/** Program entry point.
 * @param args program arguments (unused here)
 *//*from   ww w  . j  a  v a 2s  .  co m*/
public static void main(String[] args) {
    try {

        // configure Orekit
        Autoconfiguration.configureOrekit();

        // gravity field
        NormalizedSphericalHarmonicsProvider provider = GravityFieldFactory.getNormalizedProvider(2, 0);
        double mu = provider.getMu();

        // inertial frame
        Frame inertialFrame = FramesFactory.getEME2000();

        // Initial date
        AbsoluteDate initialDate = new AbsoluteDate(2004, 01, 01, 23, 30, 00.000, TimeScalesFactory.getUTC());

        // Initial orbit (GTO)
        final double a = 24396159; // semi major axis in meters
        final double e = 0.72831215; // eccentricity
        final double i = FastMath.toRadians(7); // inclination
        final double omega = FastMath.toRadians(180); // perigee argument
        final double raan = FastMath.toRadians(261); // right ascention of ascending node
        final double lM = 0; // mean anomaly
        Orbit initialOrbit = new KeplerianOrbit(a, e, i, omega, raan, lM, PositionAngle.MEAN, inertialFrame,
                initialDate, mu);
        final double period = initialOrbit.getKeplerianPeriod();

        // Initial state definition
        final SpacecraftState initialState = new SpacecraftState(initialOrbit);

        // Adaptive step integrator with a minimum step of 0.001 and a maximum step of 1000
        final double minStep = 0.001;
        final double maxStep = 1000.;
        final double dP = 1.e-2;
        final OrbitType orbType = OrbitType.CARTESIAN;
        final double[][] tol = NumericalPropagator.tolerances(dP, initialOrbit, orbType);
        final AbstractIntegrator integrator = new DormandPrince853Integrator(minStep, maxStep, tol[0], tol[1]);

        // Propagator
        NumericalPropagator numProp = new NumericalPropagator(integrator);
        numProp.setInitialState(initialState);
        numProp.setOrbitType(orbType);

        // Force Models:
        // 1 - Perturbing gravity field (only J2 is considered here)
        ForceModel gravity = new HolmesFeatherstoneAttractionModel(
                FramesFactory.getITRF(IERSConventions.IERS_2010, true), provider);

        // Add force models to the propagator
        numProp.addForceModel(gravity);

        // Propagator factory
        PropagatorBuilder builder = new KeplerianPropagatorBuilder(mu, inertialFrame, OrbitType.KEPLERIAN,
                PositionAngle.TRUE);

        // Propagator converter
        PropagatorConverter fitter = new FiniteDifferencePropagatorConverter(builder, 1.e-6, 5000);

        // Resulting propagator
        KeplerianPropagator kepProp = (KeplerianPropagator) fitter.convert(numProp, 2 * period, 251);

        // Step handlers
        StatesHandler numStepHandler = new StatesHandler();
        StatesHandler kepStepHandler = new StatesHandler();

        // Set up operating mode for the propagator as master mode
        // with fixed step and specialized step handler
        numProp.setMasterMode(60., numStepHandler);
        kepProp.setMasterMode(60., kepStepHandler);

        // Extrapolate from the initial to the final date
        numProp.propagate(initialDate.shiftedBy(10. * period));
        kepProp.propagate(initialDate.shiftedBy(10. * period));

        // retrieve the states
        List<SpacecraftState> numStates = numStepHandler.getStates();
        List<SpacecraftState> kepStates = kepStepHandler.getStates();

        // Print the results on the output file
        File output = new File(new File(System.getProperty("user.home")), "elements.dat");
        PrintStream stream = new PrintStream(output);
        stream.println("# date Anum Akep Enum Ekep Inum Ikep LMnum LMkep");
        for (SpacecraftState numState : numStates) {
            for (SpacecraftState kepState : kepStates) {
                if (numState.getDate().compareTo(kepState.getDate()) == 0) {
                    stream.println(numState.getDate() + " " + numState.getA() + " " + kepState.getA() + " "
                            + numState.getE() + " " + kepState.getE() + " "
                            + FastMath.toDegrees(numState.getI()) + " " + FastMath.toDegrees(kepState.getI())
                            + " " + FastMath.toDegrees(MathUtils.normalizeAngle(numState.getLM(), FastMath.PI))
                            + " "
                            + FastMath.toDegrees(MathUtils.normalizeAngle(kepState.getLM(), FastMath.PI)));
                    break;
                }
            }
        }
        stream.close();
        System.out.println("Results saved as file " + output);

        File output1 = new File(new File(System.getProperty("user.home")), "elts_pv.dat");
        PrintStream stream1 = new PrintStream(output1);
        stream.println("# date pxn pyn pzn vxn vyn vzn pxk pyk pzk vxk vyk vzk");
        for (SpacecraftState numState : numStates) {
            for (SpacecraftState kepState : kepStates) {
                if (numState.getDate().compareTo(kepState.getDate()) == 0) {
                    final double pxn = numState.getPVCoordinates().getPosition().getX();
                    final double pyn = numState.getPVCoordinates().getPosition().getY();
                    final double pzn = numState.getPVCoordinates().getPosition().getZ();
                    final double vxn = numState.getPVCoordinates().getVelocity().getX();
                    final double vyn = numState.getPVCoordinates().getVelocity().getY();
                    final double vzn = numState.getPVCoordinates().getVelocity().getZ();
                    final double pxk = kepState.getPVCoordinates().getPosition().getX();
                    final double pyk = kepState.getPVCoordinates().getPosition().getY();
                    final double pzk = kepState.getPVCoordinates().getPosition().getZ();
                    final double vxk = kepState.getPVCoordinates().getVelocity().getX();
                    final double vyk = kepState.getPVCoordinates().getVelocity().getY();
                    final double vzk = kepState.getPVCoordinates().getVelocity().getZ();
                    stream1.println(numState.getDate() + " " + pxn + " " + pyn + " " + pzn + " " + vxn + " "
                            + vyn + " " + vzn + " " + pxk + " " + pyk + " " + pzk + " " + vxk + " " + vyk + " "
                            + vzk);
                    break;
                }
            }
        }
        stream1.close();
        System.out.println("Results saved as file " + output1);

    } catch (OrekitException oe) {
        System.err.println(oe.getLocalizedMessage());
        System.exit(1);
    } catch (FileNotFoundException fnfe) {
        System.err.println(fnfe.getLocalizedMessage());
        System.exit(1);
    }
}

From source file:com.act.lcms.CompareTwoNetCDFAroundMass.java

public static void main(String[] args) throws Exception {
    if (args.length < 5 || !areNCFiles(Arrays.copyOfRange(args, 3, args.length))) {
        throw new RuntimeException("Needs: \n" + "(1) mass value, e.g., 132.0772 for debugging, \n"
                + "(2) how many timepoints to process (-1 for all), \n"
                + "(3) prefix for .data and rendered .pdf \n" + "(4,5..) 2 or more NetCDF .nc files");
    }// w  w  w . j  av a2  s . c o  m

    String fmt = "pdf";
    Double mz = Double.parseDouble(args[0]);
    Integer numSpectraToProcess = Integer.parseInt(args[1]);
    String outPrefix = args[2];
    String outImg = outPrefix.equals("-") ? null : outPrefix + "." + fmt;
    String outData = outPrefix.equals("-") ? null : outPrefix + ".data";

    CompareTwoNetCDFAroundMass c = new CompareTwoNetCDFAroundMass();
    String[] netCDF_fnames = Arrays.copyOfRange(args, 3, args.length);
    List<List<Pair<Double, Double>>> spectra = c.getSpectraForMass(mz, netCDF_fnames, numSpectraToProcess);

    // Write data output to outfile
    PrintStream out = outData == null ? System.out : new PrintStream(new FileOutputStream(outData));

    // print out the spectra to outData
    for (List<Pair<Double, Double>> spectraInFile : spectra) {
        for (Pair<Double, Double> xy : spectraInFile) {
            out.format("%.4f\t%.4f\n", xy.getLeft(), xy.getRight());
            out.flush();
        }
        // delimit this dataset from the rest
        out.print("\n\n");
    }
    // find the ymax across all spectra, so that we can have a uniform y scale
    Double yrange = 0.0;
    for (List<Pair<Double, Double>> spectraInFile : spectra) {
        Double ymax = 0.0;
        for (Pair<Double, Double> xy : spectraInFile) {
            Double intensity = xy.getRight();
            if (ymax < intensity)
                ymax = intensity;
        }
        if (yrange < ymax)
            yrange = ymax;
    }

    if (outData != null) {
        // if outData is != null, then we have written to .data file
        // now render the .data to the corresponding .pdf file

        // first close the .data
        out.close();

        // render outData to outFILE using gnuplo
        Gnuplotter plotter = new Gnuplotter();
        plotter.plot2D(outData, outImg, netCDF_fnames, "time in seconds", yrange, "intensity", fmt);
    }
}

From source file:Logging.java

public static void main(String args[]) throws Exception {
    FileOutputStream errors = new FileOutputStream("StdErr.txt", true);
    PrintStream stderr = new PrintStream(errors);
    PrintWriter errLog = new PrintWriter(errors, true);
    System.setErr(stderr);/*w  w w .j a  va2 s  . co m*/

    String query = "SELECT Name,Description,Qty,Cost,Sell_Price FROM Stock";

    try {
        Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
        Connection con = DriverManager.getConnection("jdbc:odbc:Inventory");
        Statement stmt = con.createStatement();
        ResultSet rs = stmt.executeQuery(query);
        while (rs.next()) {
            String name = rs.getString("Name");
            String desc = rs.getString("Description");
            int qty = rs.getInt("Qty");
            float cost = rs.getFloat("Cost");
        }
    } catch (ClassNotFoundException e) {
        e.printStackTrace(errLog);
    } catch (SQLException e) {
        System.err.println((new GregorianCalendar()).getTime());
        System.err.println("Thread: " + Thread.currentThread());
        System.err.println("ErrorCode: " + e.getErrorCode());
        System.err.println("SQLState:  " + e.getSQLState());
        System.err.println("Message:   " + e.getMessage());
        System.err.println("NextException: " + e.getNextException());
        e.printStackTrace(errLog);
        System.err.println();
    }
    stderr.close();
}