Example usage for java.lang System getProperty

List of usage examples for java.lang System getProperty

Introduction

In this page you can find the example usage for java.lang System getProperty.

Prototype

public static String getProperty(String key) 

Source Link

Document

Gets the system property indicated by the specified key.

Usage

From source file:com.github.chrbayer84.keybits.KeyBits.java

/**
 * @param args/* ww w.j  a v  a2s  .  c o m*/
 */
public static void main(String[] args) throws Exception {
    int number_of_addresses = 1;
    int depth = 1;

    String usage = "java -jar KeyBits.jar [options]";
    // create parameters which can be chosen
    Option help = new Option("h", "print this message");
    Option verbose = new Option("v", "verbose");
    Option exprt = new Option("e", "export public key to blockchain");
    Option imprt = OptionBuilder.withArgName("string").hasArg()
            .withDescription("import public key from blockchain").create("i");

    Option blockchain_address = OptionBuilder.withArgName("string").hasArg().withDescription("bitcoin address")
            .create("a");
    Option create_wallet = OptionBuilder.withArgName("file name").hasArg().withDescription("create wallet")
            .create("c");
    Option update_wallet = OptionBuilder.withArgName("file name").hasArg().withDescription("update wallet")
            .create("u");
    Option balance_wallet = OptionBuilder.withArgName("file name").hasArg()
            .withDescription("return balance of wallet").create("b");
    Option show_wallet = OptionBuilder.withArgName("file name").hasArg()
            .withDescription("show content of wallet").create("w");
    Option send_coins = OptionBuilder.withArgName("file name").hasArg().withDescription("send satoshis")
            .create("s");
    Option monitor_pending = OptionBuilder.withArgName("file name").hasArg()
            .withDescription("monitor pending transactions of wallet").create("p");
    Option monitor_depth = OptionBuilder.withArgName("file name").hasArg()
            .withDescription("monitor transaction depths of wallet").create("d");
    Option number = OptionBuilder.withArgName("integer").hasArg()
            .withDescription("in combination with -c, -d, -r or -s").create("n");
    Option reset = OptionBuilder.withArgName("file name").hasArg().withDescription("reset wallet").create("r");

    Options options = new Options();

    options.addOption(help);
    options.addOption(verbose);
    options.addOption(imprt);
    options.addOption(exprt);

    options.addOption(blockchain_address);
    options.addOption(create_wallet);
    options.addOption(update_wallet);
    options.addOption(balance_wallet);
    options.addOption(show_wallet);
    options.addOption(send_coins);
    options.addOption(monitor_pending);
    options.addOption(monitor_depth);
    options.addOption(number);
    options.addOption(reset);

    BasicParser parser = new BasicParser();
    CommandLine cmd = null;

    String header = "This is KeyBits v0.01b.1412953962" + System.getProperty("line.separator");
    // show help if wrong usage
    try {
        cmd = parser.parse(options, args);
    } catch (Exception e) {
        printHelp(usage, options, header);
    }

    if (cmd.getOptions().length == 0)
        printHelp(usage, options, header);

    if (cmd.hasOption("h"))
        printHelp(usage, options, header);

    if (cmd.hasOption("v"))
        System.out.println(header);

    if (cmd.hasOption("c") && cmd.hasOption("n"))
        number_of_addresses = new Integer(cmd.getOptionValue("n")).intValue();

    if (cmd.hasOption("d") && cmd.hasOption("n"))
        depth = new Integer(cmd.getOptionValue("n")).intValue();

    String checkpoints_file_name = "checkpoints";
    if (!new File(checkpoints_file_name).exists())
        checkpoints_file_name = null;

    // ---------------------------------------------------------------------

    if (cmd.hasOption("c")) {
        String wallet_file_name = cmd.getOptionValue("c");

        String passphrase = HelpfulStuff.insertPassphrase("enter password for " + wallet_file_name);
        if (!new File(wallet_file_name).exists()) {
            String passphrase_ = HelpfulStuff.reInsertPassphrase("enter password for " + wallet_file_name);

            if (!passphrase.equals(passphrase_)) {
                System.out.println("passwords do not match");
                System.exit(0);
            }
        }

        MyWallet.createWallet(wallet_file_name, wallet_file_name + ".chain", number_of_addresses, passphrase);
        System.exit(0);
    }

    if (cmd.hasOption("u")) {
        String wallet_file_name = cmd.getOptionValue("u");
        MyWallet.updateWallet(wallet_file_name, wallet_file_name + ".chain", checkpoints_file_name);
        System.exit(0);
    }

    if (cmd.hasOption("b")) {
        String wallet_file_name = cmd.getOptionValue("b");
        System.out.println(
                MyWallet.getBalanceOfWallet(wallet_file_name, wallet_file_name + ".chain").longValue());
        System.exit(0);
    }

    if (cmd.hasOption("w")) {
        String wallet_file_name = cmd.getOptionValue("w");
        System.out.println(MyWallet.showContentOfWallet(wallet_file_name, wallet_file_name + ".chain"));
        System.exit(0);
    }

    if (cmd.hasOption("p")) {
        System.out.println("monitoring of pending transactions ... ");
        String wallet_file_name = cmd.getOptionValue("p");
        MyWallet.monitorPendingTransactions(wallet_file_name, wallet_file_name + ".chain",
                checkpoints_file_name);
        System.exit(0);
    }

    if (cmd.hasOption("d")) {
        System.out.println("monitoring of transaction depth ... ");
        String wallet_file_name = cmd.getOptionValue("d");
        MyWallet.monitorTransactionDepth(wallet_file_name, wallet_file_name + ".chain", checkpoints_file_name,
                depth);
        System.exit(0);
    }

    if (cmd.hasOption("r") && cmd.hasOption("n")) {
        long epoch = new Long(cmd.getOptionValue("n"));
        System.out.println("resetting wallet ... ");
        String wallet_file_name = cmd.getOptionValue("r");

        File chain_file = (new File(wallet_file_name + ".chain"));
        if (chain_file.exists())
            chain_file.delete();

        MyWallet.setCreationTime(wallet_file_name, epoch);
        MyWallet.updateWallet(wallet_file_name, wallet_file_name + ".chain", checkpoints_file_name);

        System.exit(0);
    }

    if (cmd.hasOption("s") && cmd.hasOption("a") && cmd.hasOption("n")) {
        String wallet_file_name = cmd.getOptionValue("s");
        String address = cmd.getOptionValue("a");
        Integer amount = new Integer(cmd.getOptionValue("n"));

        String wallet_passphrase = HelpfulStuff.insertPassphrase("enter password for " + wallet_file_name);
        MyWallet.sendCoins(wallet_file_name, wallet_file_name + ".chain", checkpoints_file_name, address,
                new BigInteger(amount + ""), wallet_passphrase);

        System.out.println("waiting ...");
        Thread.sleep(10000);
        System.out.println("monitoring of transaction depth ... ");
        MyWallet.monitorTransactionDepth(wallet_file_name, wallet_file_name + ".chain", checkpoints_file_name,
                1);
        System.out.println("transaction fixed in blockchain with depth " + depth);
        System.exit(0);
    }

    // ----------------------------------------------------------------------------------------
    //                                  creates public key
    // ----------------------------------------------------------------------------------------

    GnuPGP gpg = new GnuPGP();

    if (cmd.hasOption("e")) {
        BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
        String line = null;
        StringBuffer sb = new StringBuffer();
        while ((line = input.readLine()) != null)
            sb.append(line + "\n");

        PGPPublicKeyRing public_key_ring = gpg.getDearmored(sb.toString());
        //System.out.println(gpg.showPublicKeys(public_key_ring));

        byte[] public_key_ring_encoded = gpg.getEncoded(public_key_ring);

        String[] addresses = (new Encoding()).encodePublicKey(public_key_ring_encoded);
        //         System.out.println(gpg.showPublicKey(gpg.getDecoded(encoding.decodePublicKey(addresses))));

        // file names for message
        String public_key_file_name = Long.toHexString(public_key_ring.getPublicKey().getKeyID()) + ".wallet";
        String public_key_wallet_file_name = public_key_file_name;
        String public_key_chain_file_name = public_key_wallet_file_name + ".chain";

        // hier muss dass passwort noch nach encodeAddresses weitergeleitet werden da sonst zweimal abfrage
        String public_key_wallet_passphrase = HelpfulStuff
                .insertPassphrase("enter password for " + public_key_wallet_file_name);
        if (!new File(public_key_wallet_file_name).exists()) {
            String public_key_wallet_passphrase_ = HelpfulStuff
                    .reInsertPassphrase("enter password for " + public_key_wallet_file_name);

            if (!public_key_wallet_passphrase.equals(public_key_wallet_passphrase_)) {
                System.out.println("passwords do not match");
                System.exit(0);
            }
        }

        MyWallet.createWallet(public_key_wallet_file_name, public_key_chain_file_name, 1,
                public_key_wallet_passphrase);
        MyWallet.updateWallet(public_key_wallet_file_name, public_key_chain_file_name, checkpoints_file_name);
        String public_key_address = MyWallet.getAddress(public_key_wallet_file_name, public_key_chain_file_name,
                0);
        System.out.println("address of public key: " + public_key_address);

        // 10000 additional satoshis for sending transaction to address of recipient of message and 10000 for fees
        KeyBits.encodeAddresses(public_key_wallet_file_name, public_key_chain_file_name, checkpoints_file_name,
                addresses, 2 * SendRequest.DEFAULT_FEE_PER_KB.intValue(), depth, public_key_wallet_passphrase);
    }

    if (cmd.hasOption("i")) {
        String location = cmd.getOptionValue("i");

        String[] addresses = null;
        if (location.indexOf(",") > -1) {
            String[] locations = location.split(",");
            addresses = MyWallet.getAddressesFromBlockAndTransaction("main.wallet", "main.wallet.chain",
                    checkpoints_file_name, locations[0], locations[1]);
        } else {
            addresses = BlockchainDotInfo.getKeys(location);
        }

        byte[] encoded = (new Encoding()).decodePublicKey(addresses);
        PGPPublicKeyRing public_key_ring = gpg.getDecoded(encoded);

        System.out.println(gpg.getArmored(public_key_ring));

        System.exit(0);
    }
}

From source file:boa.compiler.BoaCompiler.java

public static void main(final String[] args) throws IOException {
    CommandLine cl = processCommandLineOptions(args);
    if (cl == null)
        return;/*from   w  w w  .j  a v  a 2  s  .c o  m*/
    final ArrayList<File> inputFiles = BoaCompiler.inputFiles;

    // get the name of the generated class
    final String className = getGeneratedClass(cl);

    // get the filename of the jar we will be writing
    final String jarName;
    if (cl.hasOption('o'))
        jarName = cl.getOptionValue('o');
    else
        jarName = className + ".jar";

    // make the output directory
    File outputRoot = null;
    if (cl.hasOption("cd")) {
        outputRoot = new File(cl.getOptionValue("cd"));
    } else {
        outputRoot = new File(new File(System.getProperty("java.io.tmpdir")), UUID.randomUUID().toString());
    }
    final File outputSrcDir = new File(outputRoot, "boa");
    if (!outputSrcDir.mkdirs())
        throw new IOException("unable to mkdir " + outputSrcDir);

    // find custom libs to load
    final List<URL> libs = new ArrayList<URL>();
    if (cl.hasOption('l'))
        for (final String lib : cl.getOptionValues('l'))
            libs.add(new File(lib).toURI().toURL());

    final File outputFile = new File(outputSrcDir, className + ".java");
    final BufferedOutputStream o = new BufferedOutputStream(new FileOutputStream(outputFile));
    try {
        final List<String> jobnames = new ArrayList<String>();
        final List<String> jobs = new ArrayList<String>();
        boolean isSimple = true;

        final List<Program> visitorPrograms = new ArrayList<Program>();

        SymbolTable.initialize(libs);

        final int maxVisitors;
        if (cl.hasOption('v'))
            maxVisitors = Integer.parseInt(cl.getOptionValue('v'));
        else
            maxVisitors = Integer.MAX_VALUE;

        for (int i = 0; i < inputFiles.size(); i++) {
            final File f = inputFiles.get(i);
            try {
                final BoaLexer lexer = new BoaLexer(new ANTLRFileStream(f.getAbsolutePath()));
                lexer.removeErrorListeners();
                lexer.addErrorListener(new LexerErrorListener());

                final CommonTokenStream tokens = new CommonTokenStream(lexer);
                final BoaParser parser = new BoaParser(tokens);
                parser.removeErrorListeners();
                parser.addErrorListener(new BaseErrorListener() {
                    @Override
                    public void syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol, int line,
                            int charPositionInLine, String msg, RecognitionException e)
                            throws ParseCancellationException {
                        throw new ParseCancellationException(e);
                    }
                });

                final BoaErrorListener parserErrorListener = new ParserErrorListener();
                final Start p = parse(tokens, parser, parserErrorListener);
                if (cl.hasOption("ast"))
                    new ASTPrintingVisitor().start(p);

                final String jobName = "" + i;

                try {
                    if (!parserErrorListener.hasError) {
                        new TypeCheckingVisitor().start(p, new SymbolTable());

                        final TaskClassifyingVisitor simpleVisitor = new TaskClassifyingVisitor();
                        simpleVisitor.start(p);

                        LOG.info(f.getName() + ": task complexity: "
                                + (!simpleVisitor.isComplex() ? "simple" : "complex"));
                        isSimple &= !simpleVisitor.isComplex();

                        new ShadowTypeEraser().start(p);
                        new InheritedAttributeTransformer().start(p);

                        new LocalAggregationTransformer().start(p);

                        // if a job has no visitor, let it have its own method
                        // also let jobs have own methods if visitor merging is disabled
                        if (!simpleVisitor.isComplex() || maxVisitors < 2 || inputFiles.size() == 1) {
                            new VisitorOptimizingTransformer().start(p);

                            if (cl.hasOption("pp"))
                                new PrettyPrintVisitor().start(p);
                            if (cl.hasOption("ast2"))
                                new ASTPrintingVisitor().start(p);
                            final CodeGeneratingVisitor cg = new CodeGeneratingVisitor(jobName);
                            cg.start(p);
                            jobs.add(cg.getCode());

                            jobnames.add(jobName);
                        }
                        // if a job has visitors, fuse them all together into a single program
                        else {
                            p.getProgram().jobName = jobName;
                            visitorPrograms.add(p.getProgram());
                        }
                    }
                } catch (final TypeCheckException e) {
                    parserErrorListener.error("typecheck", lexer, null, e.n.beginLine, e.n.beginColumn,
                            e.n2.endColumn - e.n.beginColumn + 1, e.getMessage(), e);
                }
            } catch (final Exception e) {
                System.err.print(f.getName() + ": compilation failed: ");
                e.printStackTrace();
            }
        }

        if (!visitorPrograms.isEmpty())
            try {
                for (final Program p : new VisitorMergingTransformer().mergePrograms(visitorPrograms,
                        maxVisitors)) {
                    new VisitorOptimizingTransformer().start(p);

                    if (cl.hasOption("pp"))
                        new PrettyPrintVisitor().start(p);
                    if (cl.hasOption("ast2"))
                        new ASTPrintingVisitor().start(p);
                    final CodeGeneratingVisitor cg = new CodeGeneratingVisitor(p.jobName);
                    cg.start(p);
                    jobs.add(cg.getCode());

                    jobnames.add(p.jobName);
                }
            } catch (final Exception e) {
                System.err.println("error fusing visitors - falling back: " + e);
                e.printStackTrace();

                for (final Program p : visitorPrograms) {
                    new VisitorOptimizingTransformer().start(p);

                    if (cl.hasOption("pp"))
                        new PrettyPrintVisitor().start(p);
                    if (cl.hasOption("ast2"))
                        new ASTPrintingVisitor().start(p);
                    final CodeGeneratingVisitor cg = new CodeGeneratingVisitor(p.jobName);
                    cg.start(p);
                    jobs.add(cg.getCode());

                    jobnames.add(p.jobName);
                }
            }

        if (jobs.size() == 0)
            throw new RuntimeException("no files compiled without error");

        final ST st = AbstractCodeGeneratingVisitor.stg.getInstanceOf("Program");

        st.add("name", className);
        st.add("numreducers", inputFiles.size());
        st.add("jobs", jobs);
        st.add("jobnames", jobnames);
        st.add("combineTables", CodeGeneratingVisitor.combineAggregatorStrings);
        st.add("reduceTables", CodeGeneratingVisitor.reduceAggregatorStrings);
        st.add("splitsize", isSimple ? 64 * 1024 * 1024 : 10 * 1024 * 1024);
        if (DefaultProperties.localDataPath != null) {
            st.add("isLocal", true);
        }

        o.write(st.render().getBytes());
    } finally {
        o.close();
    }

    compileGeneratedSrc(cl, jarName, outputRoot, outputFile);
}

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

/**
 *
 * @param args/*from   www.jav a2  s. c  o m*/
 */
public static void main(String[] args) {
    Options options = new Options();
    Option[] optionArray = new Option[] {
            OptionBuilder.withArgName("nhosts").hasArg()
                    .withDescription("Number of hosts for parallel processing").create("n"),
            OptionBuilder.withArgName("mjobs").hasArg().withDescription("Number of jobs to run in parallel")
                    .create("m"),
            OptionBuilder.withArgName("runmode").hasArg()
                    .withDescription("The mode in which to operate: one of <ALL,LOCAL,DISTRIBUTED>")
                    .create("r"), //            OptionBuilder.withArgName("gui").
            //            withDescription("Create gui for distributed execution").create("g")
    };
    for (Option opt : optionArray) {
        options.addOption(opt);
    }
    if (args.length == 0) {
        HelpFormatter hf = new HelpFormatter();
        hf.printHelp(StartUp.class.getCanonicalName(), options, true);
        System.exit(1);
    }
    GnuParser gp = new GnuParser();
    int nhosts = 1;
    int mjobs = 10;
    boolean gui = false;
    Mode mode = Mode.ALL;
    try {
        CommandLine cl = gp.parse(options, args);
        if (cl.hasOption("n")) {
            nhosts = Integer.parseInt(cl.getOptionValue("n"));
        }
        if (cl.hasOption("m")) {
            mjobs = Integer.parseInt(cl.getOptionValue("m"));
        }
        if (cl.hasOption("r")) {
            mode = Mode.valueOf(cl.getOptionValue("r"));
        }
        //            if (cl.hasOption("g")) {
        //                gui = true;
        //            }
    } catch (Exception ex) {
        Logger.getLogger(StartUp.class.getName()).log(Level.SEVERE, null, ex);
        HelpFormatter hf = new HelpFormatter();
        hf.printHelp(StartUp.class.getCanonicalName(), options, true);
        System.exit(1);
    }

    String version;
    try {
        version = net.sf.mpaxs.api.Version.getVersion();
        System.out.println("Running mpaxs " + version);
        File computeHostJarLocation = new File(System.getProperty("user.dir"), "mpaxs.jar");
        if (!computeHostJarLocation.exists() || !computeHostJarLocation.isFile()) {
            throw new IOException("Could not locate mpaxs.jar in " + System.getProperty("user.dir"));
        }
        final PropertiesConfiguration cfg = new PropertiesConfiguration();
        //set default execution type
        cfg.setProperty(ConfigurationKeys.KEY_EXECUTION_MODE, ExecutionType.DRMAA);
        //set location of compute host jar
        cfg.setProperty(ConfigurationKeys.KEY_PATH_TO_COMPUTEHOST_JAR, computeHostJarLocation);
        //do not exit to console when master server shuts down
        cfg.setProperty(ConfigurationKeys.KEY_MASTER_SERVER_EXIT_ON_SHUTDOWN, false);
        //limit the number of used compute hosts
        cfg.setProperty(ConfigurationKeys.KEY_MAX_NUMBER_OF_CHOSTS, nhosts);
        cfg.setProperty(ConfigurationKeys.KEY_NATIVE_SPEC, "");
        cfg.setProperty(ConfigurationKeys.KEY_GUI_MODE, gui);
        cfg.setProperty(ConfigurationKeys.KEY_SILENT_MODE, true);
        cfg.setProperty(ConfigurationKeys.KEY_SCHEDULE_WAIT_TIME, "500");
        final int maxJobs = mjobs;
        final int maxThreads = nhosts;
        final Mode runMode = mode;
        printMessage("Run mode: " + runMode);
        Executors.newSingleThreadExecutor().submit(new Runnable() {
            @Override
            public void run() {
                if (runMode == Mode.ALL || runMode == Mode.LOCAL) {
                    printMessage("Running Within VM Execution");
                    /*
                     * LOCAL within VM execution
                     */
                    WithinVmExecution lhe = new WithinVmExecution(maxJobs, maxThreads);
                    try {
                        Logger.getLogger(ImpaxsExecution.class.getName()).log(Level.INFO,
                                "Sum is: " + lhe.call());
                    } catch (Exception ex) {
                        Logger.getLogger(ImpaxsExecution.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }

                if (runMode == Mode.ALL || runMode == Mode.DISTRIBUTED) {
                    printMessage("Running Distributed Host RMI Execution");
                    /*
                     * Grid Engine (DRMAA API) or local host distributed RMI execution
                     */
                    DistributedRmiExecution de = new DistributedRmiExecution(cfg, maxJobs);
                    try {
                        Logger.getLogger(ImpaxsExecution.class.getName()).log(Level.INFO,
                                "Sum is: " + de.call());
                    } catch (Exception ex) {
                        Logger.getLogger(ImpaxsExecution.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
                System.exit(0);
            }
        });
    } catch (IOException ex) {
        Logger.getLogger(ImpaxsExecution.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:FULRequestor.java

public static void main(String[] args) throws Exception {
    String hostId = "";
    String partnerId = "";
    String userId = "";

    CommandLineParser parser = new BasicParser();
    Options options = new Options();
    options.addOption("h", "host", true, "EBICS Host ID");
    options.addOption("p", "partner", true, "Registred Partner ID for you user");
    options.addOption("u", "user", true, "User ID to initiate");

    // Parse the program arguments
    CommandLine commandLine = parser.parse(options, args);

    if (!commandLine.hasOption('h')) {
        System.out.println("Host-ID is mandatory");
        System.exit(0);//from www  . j  a v a 2s . c o m
    } else {
        hostId = commandLine.getOptionValue('h');
        System.out.println("host: " + hostId);
    }

    if (!commandLine.hasOption('p')) {
        System.out.println("Partner-ID is mandatory");
        System.exit(0);
    } else {
        partnerId = commandLine.getOptionValue('p');
        System.out.println("partnerId: " + partnerId);
    }

    if (!commandLine.hasOption('u')) {
        System.out.println("User-ID is mandatory");
        System.exit(0);
    } else {
        userId = commandLine.getOptionValue('u');
        System.out.println("userId: " + userId);
    }

    FULRequestor hbbRequestor;
    PasswordCallback pwdHandler;
    Product product;
    String filePath;

    hbbRequestor = new FULRequestor();
    product = new Product("kopiLeft Dev 1.0", Locale.FRANCE, null);
    pwdHandler = new UserPasswordHandler(userId, "2012");

    // Load alredy created user
    hbbRequestor.loadUser(hostId, partnerId, userId, pwdHandler);

    filePath = System.getProperty("user.home") + File.separator + "test.txt";
    // Send FUL Requets
    hbbRequestor.sendFile(filePath, userId, product);
}

From source file:eu.fbk.utils.lsa.util.Anvur.java

public static void main(String[] args) throws Exception {
    String logConfig = System.getProperty("log-config");
    if (logConfig == null) {
        logConfig = "log-config.txt";
    }/*from  ww  w  .j  a  v a  2  s  .c o m*/

    PropertyConfigurator.configure(logConfig);
    /*
    if (args.length != 2)
    {
    log.println("Usage: java -mx512M eu.fbk.utils.lsa.util.Anvur in-file out-dir");
    System.exit(1);
    }
            
    File l = new File(args[1]);
    if (!l.exists())
    {
    l.mkdir();
    }
    List<String[]> list = readText(new File(args[0]));
    String oldCategory = "";
    for (int i=0;i<list.size();i++)
    {
    String[] s = list.get(i);
    if (!oldCategory.equals(s[0]))
    {
    File f = new File(args[1] + File.separator + s[0]);
    boolean b = f.mkdir();
    logger.debug(f + " created " + b);
    }
            
    File g = new File(args[1] + File.separator + s[0] + File.separator + s[1] + ".txt");
    logger.debug("writing " + g + "...");
    PrintWriter pw = new PrintWriter(new FileWriter(g));
    //pw.println(tokenize(s[1].substring(0, s[1].indexOf(".")).replace('_', ' ') + " " + s[2]));
    if (s.length == 5)
    {
    pw.println(tokenize(s[1].substring(0, s[1].indexOf(".")).replace('_', ' ') + " " + s[2] + " " + s[4].replace('_', ' ')));
    }
    else
    {
    pw.println(tokenize(s[1].substring(0, s[1].indexOf(".")).replace('_', ' ') + " " + s[2]));
    }
    pw.flush();
    pw.close();
            
    } // end for i
    */

    if (args.length != 7) {
        System.out.println(args.length);
        System.out.println(
                "Usage: java -mx2G eu.fbk.utils.lsa.util.Anvur input threshold size dim idf in-file-csv fields\n\n");
        System.exit(1);
    }

    //
    DecimalFormat dec = new DecimalFormat("#.00");

    File Ut = new File(args[0] + "-Ut");
    File Sk = new File(args[0] + "-S");
    File r = new File(args[0] + "-row");
    File c = new File(args[0] + "-col");
    File df = new File(args[0] + "-df");
    double threshold = Double.parseDouble(args[1]);
    int size = Integer.parseInt(args[2]);
    int dim = Integer.parseInt(args[3]);
    boolean rescaleIdf = Boolean.parseBoolean(args[4]);

    //"author_check"0,   "authors"1,   "title"2,   "year"3,   "pubtype"4,   "publisher"5,   "journal"6,   "volume"7,   "number"8,   "pages"9,   "abstract"10,   "nauthors",   "citedby"
    String[] labels = { "author_check", "authors", "title", "year", "pubtype", "publisher", "journal", "volume",
            "number", "pages", "abstract", "nauthors", "citedby"
            //author_id   authors   title   year   pubtype   publisher   journal   volume   number   pages   abstract   nauthors   citedby

    };
    String name = buildName(labels, args[6]);

    File bwf = new File(args[5] + name + "-bow.txt");
    PrintWriter bw = new PrintWriter(
            new BufferedWriter(new OutputStreamWriter(new FileOutputStream(bwf), "UTF-8")));
    File bdf = new File(args[5] + name + "-bow.csv");
    PrintWriter bd = new PrintWriter(
            new BufferedWriter(new OutputStreamWriter(new FileOutputStream(bdf), "UTF-8")));
    File lwf = new File(args[5] + name + "-ls.txt");
    PrintWriter lw = new PrintWriter(
            new BufferedWriter(new OutputStreamWriter(new FileOutputStream(lwf), "UTF-8")));
    File ldf = new File(args[5] + name + "-ls.csv");
    PrintWriter ld = new PrintWriter(
            new BufferedWriter(new OutputStreamWriter(new FileOutputStream(ldf), "UTF-8")));
    File blwf = new File(args[5] + name + "-bow+ls.txt");
    PrintWriter blw = new PrintWriter(
            new BufferedWriter(new OutputStreamWriter(new FileOutputStream(blwf), "UTF-8")));
    File bldf = new File(args[5] + name + "-bow+ls.csv");
    PrintWriter bld = new PrintWriter(
            new BufferedWriter(new OutputStreamWriter(new FileOutputStream(bldf), "UTF-8")));
    File logf = new File(args[5] + name + ".log");
    PrintWriter log = new PrintWriter(
            new BufferedWriter(new OutputStreamWriter(new FileOutputStream(logf), "UTF-8")));

    //System.exit(0);
    LSM lsm = new LSM(Ut, Sk, r, c, df, dim, rescaleIdf);
    LSSimilarity lss = new LSSimilarity(lsm, size);

    List<String[]> list = readText(new File(args[5]));

    // author_check   authors   title   year   pubtype   publisher   journal   volume   number   pages   abstract   nauthors   citedby

    //header
    for (int i = 0; i < list.size(); i++) {
        String[] s1 = list.get(i);
        String t1 = s1[0].toLowerCase();
        bw.print("\t");
        lw.print("\t");
        blw.print("\t");
        bw.print(i + "(" + s1[0] + ")");
        lw.print(i + "(" + s1[0] + ")");
        blw.print(i + "(" + s1[0] + ")");
    } // end for i

    bw.print("\n");
    lw.print("\n");
    blw.print("\n");
    for (int i = 0; i < list.size(); i++) {
        logger.info(i + "\t");
        String[] s1 = list.get(i);
        String t1 = buildText(s1, args[6]);
        BOW bow1 = new BOW(t1);
        logger.info(bow1);

        Vector d1 = lsm.mapDocument(bow1);
        d1.normalize();
        log.println("d1:" + d1);

        Vector pd1 = lsm.mapPseudoDocument(d1);
        pd1.normalize();
        log.println("pd1:" + pd1);

        Vector m1 = merge(pd1, d1);
        log.println("m1:" + m1);

        // write the orginal line
        for (int j = 0; j < s1.length; j++) {
            bd.print(s1[j]);
            bd.print("\t");
            ld.print(s1[j]);
            ld.print("\t");
            bld.print(s1[j]);
            bld.print("\t");

        }
        // write the bow, ls, and bow+ls vectors
        bd.println(d1);
        ld.println(pd1);
        bld.println(m1);

        bw.print(i + "(" + s1[0] + ")");
        lw.print(i + "(" + s1[0] + ")");
        blw.print(i + "(" + s1[0] + ")");
        for (int j = 0; j < i + 1; j++) {
            bw.print("\t");
            lw.print("\t");
            blw.print("\t");
        } // end for j

        for (int j = i + 1; j < list.size(); j++) {
            logger.info(i + "\t" + j);
            String[] s2 = list.get(j);

            String t2 = buildText(s2, args[6]);
            BOW bow2 = new BOW(t2);

            log.println(i + ":" + j + "(" + s1[0] + ":" + s2[0] + ") t1:" + t1);
            log.println(i + ":" + j + "(" + s1[0] + ":" + s2[0] + ") t2:" + t2);
            log.println(i + ":" + j + "(" + s1[0] + ":" + s2[0] + ") bow1:" + bow1);
            log.println(i + ":" + j + "(" + s1[0] + ":" + s2[0] + ") bow2:" + bow2);

            Vector d2 = lsm.mapDocument(bow2);
            d2.normalize();
            log.println("d2:" + d2);

            Vector pd2 = lsm.mapPseudoDocument(d2);
            pd2.normalize();
            log.println("pd2:" + pd2);

            Vector m2 = merge(pd2, d2);
            log.println("m2:" + m2);

            float cosVSM = d1.dotProduct(d2) / (float) Math.sqrt(d1.dotProduct(d1) * d2.dotProduct(d2));
            float cosLSM = pd1.dotProduct(pd2) / (float) Math.sqrt(pd1.dotProduct(pd1) * pd2.dotProduct(pd2));
            float cosBOWLSM = m1.dotProduct(m2) / (float) Math.sqrt(m1.dotProduct(m1) * m2.dotProduct(m2));
            bw.print("\t");
            bw.print(dec.format(cosVSM));
            lw.print("\t");
            lw.print(dec.format(cosLSM));
            blw.print("\t");
            blw.print(dec.format(cosBOWLSM));

            log.println(i + ":" + j + "(" + s1[0] + ":" + s2[0] + ") bow\t" + cosVSM);
            log.println(i + ":" + j + "(" + s1[0] + ":" + s2[0] + ") ls:\t" + cosLSM);
            log.println(i + ":" + j + "(" + s1[0] + ":" + s2[0] + ") bow+ls:\t" + cosBOWLSM);
        }
        bw.print("\n");
        lw.print("\n");
        blw.print("\n");
    } // end for i

    logger.info("wrote " + bwf);
    logger.info("wrote " + bwf);
    logger.info("wrote " + bdf);
    logger.info("wrote " + lwf);
    logger.info("wrote " + ldf);
    logger.info("wrote " + blwf);
    logger.info("wrote " + bldf);
    logger.info("wrote " + logf);

    ld.close();
    bd.close();
    bld.close();
    bw.close();
    lw.close();
    blw.close();

    log.close();

}

From source file:crfsvm.svm.org.itc.irst.tcc.sre.util.StemmerFactory.java

public static void main(String args[]) throws Exception {
    String logConfig = System.getProperty("log-config");
    if (logConfig == null)
        logConfig = "log-config.txt";

    PropertyConfigurator.configure(logConfig);

    if (args.length < 2) {
        System.err.println("java -mx512M org.itc.irst.tcc.sre.util.StemmerFactory stemmer word+");
        System.exit(0);/* ww w  .  java 2s.co  m*/
    }

    StemmerFactory stemmerFactory = StemmerFactory.getStemmerFactory();
    Stemmer stemmer = stemmerFactory.getInstance(args[0]);

    for (int i = 1; i < args.length; i++)
        System.out.println(args[i] + " ==> " + stemmer.stem(args[i]));

}

From source file:com.versusoft.packages.jodl.gui.CommandLineGUI.java

public static void main(String args[]) throws SAXException, IOException {

    Handler fh = new FileHandler(LOG_FILENAME_PATTERN);
    fh.setFormatter(new SimpleFormatter());

    //removeAllLoggersHandlers(Logger.getLogger(""));
    Logger.getLogger("").addHandler(fh);
    Logger.getLogger("").setLevel(Level.FINEST);

    Options options = new Options();

    Option option1 = new Option("in", "ODT file (required)");
    option1.setRequired(true);//  w w  w.  j  av a2s. c  o m
    option1.setArgs(1);

    Option option2 = new Option("out", "Output file (required)");
    option2.setRequired(false);
    option2.setArgs(1);

    Option option3 = new Option("pic", "extract pics");
    option3.setRequired(false);
    option3.setArgs(1);

    Option option4 = new Option("page", "enable pagination processing");
    option4.setRequired(false);
    option4.setArgs(0);

    options.addOption(option1);
    options.addOption(option2);
    options.addOption(option3);
    options.addOption(option4);

    CommandLineParser parser = new BasicParser();
    CommandLine cmd = null;

    try {
        cmd = parser.parse(options, args);
    } catch (ParseException e) {
        printHelp();
        return;
    }

    if (cmd.hasOption("help")) {
        printHelp();
        return;
    }

    File outFile = new File(cmd.getOptionValue("out"));

    OdtUtils utils = new OdtUtils();

    utils.open(cmd.getOptionValue("in"));
    //utils.correctionStep();
    utils.saveXML(outFile.getAbsolutePath());

    try {

        if (cmd.hasOption("page")) {
            OdtUtils.paginationProcessing(outFile.getAbsolutePath());
        }

        OdtUtils.correctionProcessing(outFile.getAbsolutePath());

    } catch (ParserConfigurationException ex) {
        logger.log(Level.SEVERE, null, ex);
    } catch (SAXException ex) {
        logger.log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        logger.log(Level.SEVERE, null, ex);
    } catch (TransformerConfigurationException ex) {
        logger.log(Level.SEVERE, null, ex);
    } catch (TransformerException ex) {
        logger.log(Level.SEVERE, null, ex);
    }

    if (cmd.hasOption("pic")) {

        String imageDir = cmd.getOptionValue("pic");
        if (!imageDir.endsWith("/")) {
            imageDir += "/";
        }

        try {

            String basedir = new File(cmd.getOptionValue("out")).getParent().toString()
                    + System.getProperty("file.separator");
            OdtUtils.extractAndNormalizeEmbedPictures(cmd.getOptionValue("out"), cmd.getOptionValue("in"),
                    basedir, imageDir);
        } catch (SAXException ex) {
            logger.log(Level.SEVERE, null, ex);
        } catch (ParserConfigurationException ex) {
            logger.log(Level.SEVERE, null, ex);
        } catch (TransformerConfigurationException ex) {
            logger.log(Level.SEVERE, null, ex);
        } catch (TransformerException ex) {
            logger.log(Level.SEVERE, null, ex);
        }
    }

}

From source file:com.github.jknack.handlebars.server.HbsServer.java

public static void main(final String[] args) throws Exception {
    Options arguments = new Options();
    CmdLineParser parser = new CmdLineParser(arguments);
    try {//from   w w w . j a v a 2 s. co m
        parser.parseArgument(args);
        run(arguments);
    } catch (CmdLineException e) {
        System.err.println(e.getMessage());
        String os = System.getProperty("os.name").toLowerCase();
        System.err.println("Usage:");
        String program = "java -jar handlebars-proto-${version}.jar";
        if (os.contains("win")) {
            program = "handlebars";
        }
        System.err.println("  " + program + " [-option value]");
        System.err.println("Options:");
        parser.printUsage(System.err);
    }
}

From source file:de.unibi.techfak.bibiserv.util.codegen.Main.java

public static void main(String[] args) {
    // check &   validate cmdline options
    OptionGroup opt_g = getCMDLineOptionsGroups();
    Options opt = getCMDLineOptions();/* w  w  w.j a va  2 s .  c o  m*/
    opt.addOptionGroup(opt_g);

    CommandLineParser cli = new DefaultParser();
    try {
        CommandLine cl = cli.parse(opt, args);

        if (cl.hasOption("v")) {
            VerboseOutputFilter.SHOW_VERBOSE = true;
        }

        switch (opt_g.getSelected()) {
        case "V":
            try {
                URL jarUrl = Main.class.getProtectionDomain().getCodeSource().getLocation();
                String jarPath = URLDecoder.decode(jarUrl.getFile(), "UTF-8");
                JarFile jarFile = new JarFile(jarPath);
                Manifest m = jarFile.getManifest();
                StringBuilder versionInfo = new StringBuilder();
                for (Object key : m.getMainAttributes().keySet()) {
                    versionInfo.append(key).append(":").append(m.getMainAttributes().getValue(key.toString()))
                            .append("\n");
                }
                System.out.println(versionInfo.toString());
            } catch (Exception e) {
                log.error("Version info could not be read.");
            }
            break;
        case "h":
            HelpFormatter help = new HelpFormatter();
            String header = ""; //TODO: missing infotext 
            StringBuilder footer = new StringBuilder("Supported configuration properties :");
            help.printHelp("CodeGen -h | -V | -g  [...]", header, opt, footer.toString());
            break;
        case "g":
            // target dir
            if (cl.hasOption("t")) {
                File target = new File(cl.getOptionValue("t"));
                if (target.isDirectory() && target.canExecute() && target.canWrite()) {
                    config.setProperty("target.dir", cl.getOptionValue("t"));
                } else {
                    log.error("Target dir '{}' is inaccessible!", cl.getOptionValue("t"));
                    break;
                }
            } else {
                config.setProperty("target.dir", System.getProperty("java.io.tmpdir"));
            }

            // project dir
            if (cl.hasOption("p")) {
                File project = new File(cl.getOptionValue("p"));
                if (!project.exists()) {
                    if (!project.mkdirs()) {
                        log.error("Project dir '{}' can't be created!", cl.getOptionValue("p"));
                        break;
                    }
                }

                if (project.isDirectory() && project.canExecute() && project.canWrite()) {
                    config.setProperty("project.dir", cl.getOptionValue("p"));
                } else {
                    log.error("Project dir '{}' is inaccessible!", cl.getOptionValue("p"));
                    break;
                }
            }

            generateAppfromXML(cl.getOptionValue("g"));
            break;
        }
    } catch (ParseException e) {
        log.error("ParseException occurred while parsing cmdline arguments!\n{}", e.getLocalizedMessage());
    }

}

From source file:de.huberlin.wbi.cuneiform.cmdline.main.Main.java

public static void main(String[] args)
        throws IOException, ParseException, InterruptedException, NotDerivableException {

    CommandLine cmd;//from  www  . j  a va 2s .c o m
    Options opt;
    BaseRepl repl;
    BaseCreActor cre;
    Path sandbox;
    ExecutorService executor;
    TicketSrcActor ticketSrc;
    JsonSummary summary;
    Path summaryPath;
    Log statLog;
    int nthread;
    Path workDir;

    statLog = LogFactory.getLog("statLogger");

    executor = Executors.newCachedThreadPool();
    try {

        opt = getOptions();
        cmd = parse(args, opt);
        config(cmd);

        if (cmd.hasOption('h')) {

            System.out.println("CUNEIFORM - A Functional Workflow Language\nversion " + BaseRepl.LABEL_VERSION
                    + " build " + BaseRepl.LABEL_BUILD);
            new HelpFormatter().printHelp("java -jar cuneiform.jar [OPTION]*", opt);

            return;
        }

        if (cmd.hasOption('r'))
            Invocation.putLibPath(ForeignLambdaExpr.LANGID_R, cmd.getOptionValue('r'));

        if (cmd.hasOption('y'))
            Invocation.putLibPath(ForeignLambdaExpr.LANGID_PYTHON, cmd.getOptionValue('y'));

        if (cmd.hasOption('l'))
            sandbox = Paths.get(cmd.getOptionValue("l"));
        else
            sandbox = Paths.get(System.getProperty("user.home")).resolve(".cuneiform");

        sandbox = sandbox.toAbsolutePath();

        if (cmd.hasOption('c'))
            LocalThread.deleteIfExists(sandbox);

        if (cmd.hasOption('t'))
            nthread = Integer.valueOf(cmd.getOptionValue('t'));
        else
            nthread = Runtime.getRuntime().availableProcessors();

        if (cmd.hasOption('w'))
            workDir = Paths.get(cmd.getOptionValue('w'));
        else
            workDir = Paths.get(System.getProperty("user.dir"));

        workDir = workDir.toAbsolutePath();

        switch (platform) {

        case PLATFORM_LOCAL:

            if (!Files.exists(sandbox))
                Files.createDirectories(sandbox);

            cre = new LocalCreActor(sandbox, workDir, nthread);
            break;

        case PLATFORM_HTCONDOR:

            if (!Files.exists(sandbox))
                Files.createDirectories(sandbox);

            if (cmd.hasOption('m')) { // MAX_TRANSFER SIZE
                String maxTransferSize = cmd.getOptionValue('m');
                try {
                    cre = new CondorCreActor(sandbox, maxTransferSize);
                } catch (Exception e) {
                    System.out.println("INVALID '-m' option value: " + maxTransferSize
                            + "\n\nCUNEIFORM - A Functional Workflow Language\nversion "
                            + BaseRepl.LABEL_VERSION + " build " + BaseRepl.LABEL_BUILD);
                    new HelpFormatter().printHelp("java -jar cuneiform.jar [OPTION]*", opt);

                    return;
                }
            } else {
                cre = new CondorCreActor(sandbox);
            }

            break;

        default:
            throw new RuntimeException("Platform not recognized.");
        }

        executor.submit(cre);
        ticketSrc = new TicketSrcActor(cre);
        executor.submit(ticketSrc);
        executor.shutdown();

        switch (format) {

        case FORMAT_CF:

            if (cmd.hasOption("i"))
                repl = new InteractiveRepl(ticketSrc, statLog);
            else
                repl = new CmdlineRepl(ticketSrc, statLog);
            break;

        case FORMAT_DAX:
            repl = new DaxRepl(ticketSrc, statLog);
            break;

        default:
            throw new RuntimeException("Format not recognized.");
        }

        if (cmd.hasOption("i")) {

            // run in interactive mode
            BaseRepl.run(repl);

            return;
        }

        // run in quiet mode

        if (inputFileVector.length > 0)

            for (Path f : inputFileVector)
                repl.interpret(readFile(f));

        else
            repl.interpret(readStdIn());

        Thread.sleep(3 * Actor.DELAY);
        while (repl.isBusy())
            Thread.sleep(Actor.DELAY);

        if (cmd.hasOption("s")) {

            summary = new JsonSummary(ticketSrc.getRunId(), sandbox, repl.getAns());
            summaryPath = Paths.get(cmd.getOptionValue("s"));
            summaryPath = summaryPath.toAbsolutePath();
            try (BufferedWriter writer = Files.newBufferedWriter(summaryPath, Charset.forName("UTF-8"))) {

                writer.write(summary.toString());
            }

        }

    } finally {
        executor.shutdownNow();
    }

}