Example usage for java.io File exists

List of usage examples for java.io File exists

Introduction

In this page you can find the example usage for java.io File exists.

Prototype

public boolean exists() 

Source Link

Document

Tests whether the file or directory denoted by this abstract pathname exists.

Usage

From source file:com.google.api.ads.adwords.awreporting.AwReporting.java

/**
 * Main method.// w w w  .  jav a  2  s . c o m
 *
 * @param args the command line arguments.
 */
public static void main(String args[]) {

    // Proxy
    JaxWsProxySelector ps = new JaxWsProxySelector(ProxySelector.getDefault());
    ProxySelector.setDefault(ps);

    Options options = createCommandLineOptions();

    boolean errors = false;
    String propertiesPath = null;

    try {
        CommandLineParser parser = new BasicParser();
        CommandLine cmdLine = parser.parse(options, args);

        // Print full help and quit
        if (cmdLine.hasOption("help")) {
            printHelpMessage(options);
            printSamplePropertiesFile();
            System.exit(0);
        }

        setLogLevel(cmdLine);

        if (cmdLine.hasOption("file")) {
            propertiesPath = cmdLine.getOptionValue("file");
        } else {
            LOGGER.error("Missing required option: 'file'");
            System.exit(0);
        }
        LOGGER.info("Using properties file: " + propertiesPath);

        Set<Long> accountIdsSet = Sets.newHashSet();
        if (cmdLine.hasOption("accountIdsFile")) {
            String accountsFileName = cmdLine.getOptionValue("accountIdsFile");
            addAccountsFromFile(accountIdsSet, accountsFileName);
        }

        boolean forceOnFileProcessor = false;
        if (cmdLine.hasOption("onFileReport")) {
            if (!cmdLine.hasOption("csvReportFile") || !cmdLine.hasOption("startDate")
                    || !cmdLine.hasOption("endDate")) {
                LOGGER.error("Missing one or more of the required options: "
                        + "'csvReportFile', 'startDate' or 'endDate'");
                System.exit(0);
            }
            forceOnFileProcessor = true;
        }
        Properties properties = initApplicationContextAndProperties(propertiesPath, forceOnFileProcessor);

        LOGGER.debug("Creating ReportProcessor bean...");
        ReportProcessor processor = createReportProcessor();
        LOGGER.debug("... success.");

        String mccAccountId = properties.getProperty("mccAccountId").replaceAll("-", "");

        if (cmdLine.hasOption("startDate") && cmdLine.hasOption("endDate")) {
            // Generate Reports
            String dateStart = cmdLine.getOptionValue("startDate");
            String dateEnd = cmdLine.getOptionValue("endDate");

            if (cmdLine.hasOption("onFileReport")) {

                String reportTypeName = cmdLine.getOptionValue("onFileReport");
                String csvReportFile = cmdLine.getOptionValue("csvReportFile");

                File csvFile = new File(csvReportFile);
                if (!csvFile.exists()) {
                    LOGGER.error("Could not find CSV file: " + csvReportFile);
                    System.exit(0);
                }

                ReportProcessorOnFile onFileProcessor = (ReportProcessorOnFile) processor;
                List<File> localFiles = new ArrayList<File>();
                localFiles.add(csvFile);

                LOGGER.info(
                        "Starting report processing for dateStart: " + dateStart + " and dateEnd: " + dateEnd);
                onFileProcessor.processInputFiles(mccAccountId, reportTypeName, localFiles, dateStart, dateEnd,
                        ReportDefinitionDateRangeType.CUSTOM_DATE);

            } else {
                LOGGER.info(
                        "Starting report download for dateStart: " + dateStart + " and dateEnd: " + dateEnd);

                processor.generateReportsForMCC(mccAccountId, ReportDefinitionDateRangeType.CUSTOM_DATE,
                        dateStart, dateEnd, accountIdsSet, properties, null, null);
            }
        } else if (cmdLine.hasOption("dateRange")) {

            ReportDefinitionDateRangeType dateRangeType = ReportDefinitionDateRangeType
                    .fromValue(cmdLine.getOptionValue("dateRange"));

            LOGGER.info("Starting report download for dateRange: " + dateRangeType.name());

            processor.generateReportsForMCC(mccAccountId, dateRangeType, null, null, accountIdsSet, properties,
                    null, null);

        } else {
            errors = true;
            LOGGER.error("Configuration incomplete. Missing options for command line.");
        }

    } catch (IOException e) {
        errors = true;

        if (e.getMessage().contains("Insufficient Permission")) {
            LOGGER.error("Insufficient Permission error accessing the API" + e.getMessage());
        } else {
            LOGGER.error("File not found: " + e.getMessage());
        }

    } catch (ParseException e) {
        errors = true;
        System.err.println("Error parsing the values for the command line options: " + e.getMessage());
    } catch (Exception e) {
        errors = true;
        LOGGER.error("Unexpected error accessing the API: " + e.getMessage());
        e.printStackTrace();
    }

    if (errors) {
        System.exit(1);
    } else {
        System.exit(0);
    }
}

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

/**
 * @param args/*  w  ww  . j  a v a2  s .  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:fr.iphc.grid.jobmanager.JobManager.java

/**
 * @param args//from ww w  .  j  av a  2 s.c  o m
 */
public static void main(String[] args) throws Exception {
    JobManager command = new JobManager();
    CommandLine line = command.parse(args);
    ArrayList<File> JdlList = new ArrayList<File>();
    Global.getOutputexecutor = Executors.newFixedThreadPool(10);
    Initialize init = new Initialize();
    String SetupFile = "setup_vigrid.xml";

    if (line.hasOption(OPT_SETUP)) {
        SetupFile = line.getOptionValue(OPT_SETUP);
    }
    if ((new File(SetupFile).isFile())) {
        init.GlobalSetup(SetupFile);
    }
    // Init Job
    if (line.hasOption(OPT_JOB)) {
        File file = new File(line.getOptionValue(OPT_JOB));
        if ((file.isFile())) {
            JdlList.add(file);
        } else {
            System.err.println("The file " + file + " doesn't exist");
            System.exit(-1);
        }
    } else {
        File file = new File(line.getOptionValue(OPT_FILEJOB));
        if ((file.isFile())) {
            JdlList = init.InitJdl(file);
        } else {
            System.err.println("The file " + file + " doesn't exist");
            System.exit(-1);
        }
    }
    if (line.hasOption(OPT_WAIT)) {
        Global.TIMEOUTWAIT = Integer.parseInt(line.getOptionValue(OPT_WAIT));
    }
    if (line.hasOption(OPT_RUN)) {
        Global.TIMEOUTRUN = Integer.parseInt(line.getOptionValue(OPT_RUN));
    }
    if (line.hasOption(OPT_END)) {
        Global.TIMEOUTEND = Integer.parseInt(line.getOptionValue(OPT_END));
    }
    if (line.hasOption(OPT_LOGDISPLAY)) {
        Global.SEUILDISPLAYLOG = Float.parseFloat(line.getOptionValue(OPT_LOGDISPLAY));
    }
    init.InitJob(JdlList);
    // Init Url Ce
    if (line.hasOption(OPT_QUEUE)) {
        Global.file = new File(line.getOptionValue(OPT_QUEUE));
    }
    if (line.hasOption(OPT_BAD)) {
        Global.BadCe = new File(line.getOptionValue(OPT_BAD));
    }
    if (line.hasOption(OPT_OPTIMIZETIMEOUTRUN)) {
        Global.OPTTIMEOUTRUN = false;
    }
    if (line.hasOption(OPT_CWD)) {
        File theDir = new File(line.getOptionValue(OPT_CWD));
        if (!theDir.exists()) {
            if (!theDir.mkdirs()) {
                System.err.println("Working directory create failed: " + line.getOptionValue(OPT_CWD));
                System.exit(-1);
            }
        }
        Global.Cwd = line.getOptionValue(OPT_CWD);
    } else {
        Global.Cwd = System.getProperty("user.dir");
    }
    if (!(new File(Global.Cwd)).canWrite()) {
        System.err.println(" Write permission denied : " + Global.Cwd);
        System.exit(-1);
    }
    System.out.println("Current working directory : " + Global.Cwd);
    Date start = new Date();
    init.PrintGlobalSetup();
    init.InitUrl(Global.file);
    init.InitSosCe();
    init.rmLoadFailed(Global.Cwd + "/loadFailed.txt");
    System.out.println("CE: " + Global.ListUrl.size() + " Nb JOB: " + Global.ListJob.size() + " " + new Date());
    if (Global.ListJob.size() < 6) { // pour obtenir rapport de 0.8
        Global.OPTTIMEOUTRUN = false;
    }
    // check if we can connect to the grid
    try {
        SessionFactory.createSession(true);
    } catch (NoSuccessException e) {
        System.err.println("Could not connect to the grid at all (" + e.getMessage() + ")");
        System.err.println("Aborting");
        System.exit(0);

    }
    // Launch Tread Job
    JobThread st = new JobThread(Global.ListJob, Global.ListUrl);
    st.start();
    LoggingThread logst = new LoggingThread(Global.ListJob, Global.ListUrl, Global.SEUILDISPLAYLOG);
    logst.start();
    // create Thread Hook intercept kill +CNTL+C
    Thread hook = new Thread() {
        public void run() {
            try {
                for (Jdl job : Global.ListJob) {
                    if (job.getJobId() != null) {
                        JobThread.jobCancel(job.getJobId());
                    }
                }
            } catch (Exception e) {
                System.err.println("Thread Hook:\n" + e.getMessage());
            }
            // give it a change to display final job state
            try {
                sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    };
    Runtime.getRuntime().addShutdownHook(hook);

    //      Integer timer = 180 * 60 * 1000;
    Date now = new Date();

    //      Boolean Fin = false;
    while ((!Global.END) && ((now.getTime() - start.getTime()) < Global.TIMEOUTEND * 60 * 1000)) { // TOEND
        // en
        // minutes
        now = new Date();
        // int mb = 1024*1024;
        // Getting the runtime reference from system
        // Runtime runtime = Runtime.getRuntime();
        // System.out.println("##### Heap utilization statistics [MB]
        // #####");
        // Print used memory
        // System.out.println("Used Memory:"
        // + (runtime.totalMemory() - runtime.freeMemory()) / mb);

        // Print free memory
        // System.out.println("Free Memory:"
        // + runtime.freeMemory() / mb);

        // Print total available memory
        // System.out.println("Total Memory:" + runtime.totalMemory() / mb);

        // Print Maximum available memory
        // System.out.println("Max Memory:" + runtime.maxMemory() / mb);
        // // System.out.println("NB: "+nb_end);
        // if ((float)(runtime.totalMemory() -
        // runtime.freeMemory())/(float)runtime.maxMemory() > (float)0.3){
        // System.out.println ("GC: "+(float)(runtime.totalMemory() -
        // runtime.freeMemory())/runtime.maxMemory());
        // System.gc();
        // };
        sleep(15 * 1000); // in ms

        // System.gc();
        // Fin=true;
        // for (Jdl job : Global.ListJob) {
        // if (job.getJob() != null) {
        // System.out.println("JOB: "+job.getId()+"\t"+job.getStatus());
        // if (job.getStatus().compareTo("END")==0){
        // ((JobImpl) job.getJob()).postStagingAndCleanup();
        // System.out.println("END JOB: "+job.getId());
        // job.setStatus("END");
        // }
        // if (job.getStatus().compareTo("END")!=0){
        // Fin=false;
        // }
        // System.out.println("JOB: "+job.getId()+"\t"+job.getStatus() +
        // "\t"+job.getFail()+"\t"+job.getNodeCe());
        // }
        // }
        // while ((Global.END==0) && ((new
        // Date().getTime()-start.getTime())<timer)){
    }
    // Boolean end_load=false;
    // while (!end_load){
    // end_load=true;
    // for(Jdl job:Global.ListJob){
    // if (job.getStatus().equals("LOAD")){
    // end_load=false;
    // }
    // }
    // }
    System.out.println("END JOB: " + now);
    st.halt();
    logst.halt();
    Iterator<Url> k = Global.ListUrl.iterator();
    while (k.hasNext()) {
        Url url = k.next();
        System.out.println("URL: " + url.getUrl());
    }
    Iterator<Jdl> m = Global.ListJob.iterator();
    while (m.hasNext()) {
        Jdl job = m.next();
        System.out.println(
                "JOB: " + job.getId() + "\t" + job.getFail() + "\t" + job.getStatus() + "\t" + job.getNodeCe());
    }
    System.out.println(start + " " + new Date());
    System.exit(0);
}

From source file:io.apicurio.studio.tools.release.ReleaseTool.java

/**
 * Main method.//from   w  w  w . jav a  2s . co  m
 * @param args
 */
public static void main(String[] args) throws Exception {
    Options options = new Options();
    options.addOption("n", "release-name", true, "The name of the new release.");
    options.addOption("p", "prerelease", false, "Indicate that this is a pre-release.");
    options.addOption("t", "release-tag", true, "The tag name of the new release.");
    options.addOption("o", "previous-tag", true, "The tag name of the previous release.");
    options.addOption("g", "github-pat", true, "The GitHub PAT (for authentication/authorization).");
    options.addOption("a", "artifact", true, "The binary release artifact (full path).");
    options.addOption("d", "output-directory", true, "Where to store output file(s).");

    CommandLineParser parser = new DefaultParser();
    CommandLine cmd = parser.parse(options, args);

    if (!cmd.hasOption("n") || !cmd.hasOption("t") || !cmd.hasOption("o") || !cmd.hasOption("g")
            || !cmd.hasOption("a")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("release-studio", options);
        System.exit(1);
    }

    // Arguments (command line)
    String releaseName = cmd.getOptionValue("n");
    boolean isPrerelease = cmd.hasOption("p");
    String releaseTag = cmd.getOptionValue("t");
    String oldReleaseTag = cmd.getOptionValue("o");
    String githubPAT = cmd.getOptionValue("g");
    String artifact = cmd.getOptionValue("a");
    File outputDir = new File("");
    if (cmd.hasOption("d")) {
        outputDir = new File(cmd.getOptionValue("d"));
        if (!outputDir.exists()) {
            outputDir.mkdirs();
        }
    }

    File releaseArtifactFile = new File(artifact);
    File releaseArtifactSigFile = new File(artifact + ".asc");

    String releaseArtifact = releaseArtifactFile.getName();
    String releaseArtifactSig = releaseArtifactSigFile.getName();

    if (!releaseArtifactFile.isFile()) {
        System.err.println("Missing file: " + releaseArtifactFile.getAbsolutePath());
        System.exit(1);
    }
    if (!releaseArtifactSigFile.isFile()) {
        System.err.println("Missing file: " + releaseArtifactSigFile.getAbsolutePath());
        System.exit(1);
    }

    System.out.println("=========================================");
    System.out.println("Creating Release: " + releaseTag);
    System.out.println("Previous Release: " + oldReleaseTag);
    System.out.println("            Name: " + releaseName);
    System.out.println("        Artifact: " + releaseArtifact);
    System.out.println("     Pre-Release: " + isPrerelease);
    System.out.println("=========================================");

    String releaseNotes = "";

    // Step #1 - Generate Release Notes
    //   * Grab info about the previous release (extract publish date)
    //   * Query all Issues for ones closed since that date
    //   * Generate Release Notes from the resulting Issues
    try {
        System.out.println("Getting info about release " + oldReleaseTag);
        HttpResponse<JsonNode> response = Unirest
                .get("https://api.github.com/repos/apicurio/apicurio-studio/releases/tags/v" + oldReleaseTag)
                .header("Accept", "application/json").header("Authorization", "token " + githubPAT).asJson();
        if (response.getStatus() != 200) {
            throw new Exception("Failed to get old release info: " + response.getStatusText());
        }
        JsonNode body = response.getBody();
        String publishedDate = body.getObject().getString("published_at");
        if (publishedDate == null) {
            throw new Exception("Could not find Published Date for previous release " + oldReleaseTag);
        }
        System.out.println("Release " + oldReleaseTag + " was published on " + publishedDate);

        List<JSONObject> issues = getIssuesForRelease(publishedDate, githubPAT);
        System.out.println("Found " + issues.size() + " issues closed in release " + releaseTag);
        System.out.println("Generating Release Notes");

        releaseNotes = generateReleaseNotes(releaseName, releaseTag, issues);
        System.out.println("------------ Release Notes --------------");
        System.out.println(releaseNotes);
        System.out.println("-----------------------------------------");
    } catch (Exception e) {
        e.printStackTrace();
        System.exit(1);
    }

    String assetUploadUrl = null;

    // Step #2 - Create a GitHub Release
    try {
        System.out.println("\nCreating GitHub Release " + releaseTag);
        JSONObject body = new JSONObject();
        body.put("tag_name", "v" + releaseTag);
        body.put("name", releaseName);
        body.put("body", releaseNotes);
        body.put("prerelease", isPrerelease);

        HttpResponse<JsonNode> response = Unirest
                .post("https://api.github.com/repos/apicurio/apicurio-studio/releases")
                .header("Accept", "application/json").header("Content-Type", "application/json")
                .header("Authorization", "token " + githubPAT).body(body).asJson();
        if (response.getStatus() != 201) {
            throw new Exception("Failed to create release in GitHub: " + response.getStatusText());
        }

        assetUploadUrl = response.getBody().getObject().getString("upload_url");
        if (assetUploadUrl == null || assetUploadUrl.trim().isEmpty()) {
            throw new Exception("Failed to get Asset Upload URL for newly created release!");
        }
    } catch (Exception e) {
        e.printStackTrace();
        System.exit(1);
    }

    // Step #3 - Upload Release Artifact (zip file)
    System.out.println("\nUploading Quickstart Artifact: " + releaseArtifact);
    try {
        String artifactUploadUrl = createUploadUrl(assetUploadUrl, releaseArtifact);
        byte[] artifactData = loadArtifactData(releaseArtifactFile);
        System.out.println("Uploading artifact asset: " + artifactUploadUrl);
        HttpResponse<JsonNode> response = Unirest.post(artifactUploadUrl).header("Accept", "application/json")
                .header("Content-Type", "application/zip").header("Authorization", "token " + githubPAT)
                .body(artifactData).asJson();
        if (response.getStatus() != 201) {
            throw new Exception("Failed to upload asset: " + releaseArtifact,
                    new Exception(response.getStatus() + "::" + response.getStatusText()));
        }

        Thread.sleep(1000);

        artifactUploadUrl = createUploadUrl(assetUploadUrl, releaseArtifactSig);
        artifactData = loadArtifactData(releaseArtifactSigFile);
        System.out.println("Uploading artifact asset: " + artifactUploadUrl);
        response = Unirest.post(artifactUploadUrl).header("Accept", "application/json")
                .header("Content-Type", "text/plain").header("Authorization", "token " + githubPAT)
                .body(artifactData).asJson();
        if (response.getStatus() != 201) {
            throw new Exception("Failed to upload asset: " + releaseArtifactSig,
                    new Exception(response.getStatus() + "::" + response.getStatusText()));
        }
    } catch (Exception e) {
        e.printStackTrace();
        System.exit(1);
    }

    Thread.sleep(1000);

    // Step #4 - Download Latest Release JSON for inclusion in the project web site
    try {
        System.out.println("Getting info about the release.");
        HttpResponse<JsonNode> response = Unirest
                .get("https://api.github.com/repos/apicurio/apicurio-studio/releases/latest")
                .header("Accept", "application/json").asJson();
        if (response.getStatus() != 200) {
            throw new Exception("Failed to get release info: " + response.getStatusText());
        }
        JsonNode body = response.getBody();
        String publishedDate = body.getObject().getString("published_at");
        if (publishedDate == null) {
            throw new Exception("Could not find Published Date for release.");
        }
        String fname = publishedDate.replace(':', '-');
        File outFile = new File(outputDir, fname + ".json");

        System.out.println("Writing latest release info to: " + outFile.getAbsolutePath());

        String output = body.getObject().toString(4);
        try (FileOutputStream fos = new FileOutputStream(outFile)) {
            fos.write(output.getBytes("UTF-8"));
            fos.flush();
        }

        System.out.println("Release info successfully written.");
    } catch (Exception e) {
        e.printStackTrace();
        System.exit(1);
    }

    System.out.println("=========================================");
    System.out.println("All Done!");
    System.out.println("=========================================");
}

From source file:de.mycrobase.jcloudapp.Main.java

public static void main(String[] args) throws Exception {
    try {/*from   w  w  w  .  jav a  2s  .c  o  m*/
        // borrowed from https://github.com/cmur2/gloudapp
        ImageNormal = ImageIO.read(Main.class.getResourceAsStream("gloudapp.png"));
        ImageWorking = ImageIO.read(Main.class.getResourceAsStream("gloudapp_working.png"));
        IconNormal = new ImageIcon(ImageNormal.getScaledInstance(64, 64, Image.SCALE_SMOOTH));
        IconLarge = new ImageIcon(ImageNormal);
    } catch (IOException ex) {
        showErrorDialog("Could not load images!\n" + ex);
        System.exit(1);
    }

    URI serviceUrl = URI.create("http://my.cl.ly:80/");
    File storage = getStorageFile();

    if (storage.exists() && storage.isFile()) {
        Yaml yaml = new Yaml();
        try {
            Map<String, String> m = (Map<String, String>) yaml.load(new FileInputStream(storage));
            // avoid NPE by implicitly assuming the presence of a service URL
            if (m.containsKey("service_url")) {
                serviceUrl = URI.create(m.get("service_url"));
            }
        } catch (IOException ex) {
            showErrorDialog("Loading settings from .cloudapp-cli failed: " + ex);
            System.exit(1);
        }
    }

    Main app = new Main(serviceUrl);
    app.login(args);
    app.run();
}

From source file:de.prozesskraft.pkraft.Perlcode.java

public static void main(String[] args) throws org.apache.commons.cli.ParseException, IOException {

    //      try/*from  w ww .j a va 2s .  com*/
    //      {
    //         if (args.length != 3)
    //         {
    //            System.out.println("Please specify processdefinition file (xml) and an outputfilename");
    //         }
    //         
    //      }
    //      catch (ArrayIndexOutOfBoundsException e)
    //      {
    //         System.out.println("***ArrayIndexOutOfBoundsException: Please specify processdefinition.xml, openoffice_template.od*, newfile_for_processdefinitions.odt\n" + e.toString());
    //      }

    /*----------------------------
      get options from ini-file
    ----------------------------*/
    File inifile = new java.io.File(
            WhereAmI.getInstallDirectoryAbsolutePath(Perlcode.class) + "/" + "../etc/pkraft-perlcode.ini");

    if (inifile.exists()) {
        try {
            ini = new Ini(inifile);
        } catch (InvalidFileFormatException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
    } else {
        System.err.println("ini file does not exist: " + inifile.getAbsolutePath());
        System.exit(1);
    }

    /*----------------------------
      create boolean options
    ----------------------------*/
    Option ohelp = new Option("help", "print this message");
    Option ov = new Option("v", "prints version and build-date");

    /*----------------------------
      create argument options
    ----------------------------*/
    Option ostep = OptionBuilder.withArgName("STEPNAME").hasArg().withDescription(
            "[optional] stepname of step to generate a script for. if this parameter is omitted, a script for the process will be generated.")
            //            .isRequired()
            .create("step");

    Option ooutput = OptionBuilder.withArgName("DIR").hasArg()
            .withDescription("[mandatory] directory for generated files. must not exist when calling.")
            //            .isRequired()
            .create("output");

    Option odefinition = OptionBuilder.withArgName("FILE").hasArg()
            .withDescription("[mandatory] process definition file.")
            //            .isRequired()
            .create("definition");

    Option onolist = OptionBuilder.withArgName("")
            //            .hasArg()
            .withDescription(
                    "[optional] with this parameter the multiple use of multi-optionis is forced. otherwise it is possible to use an integrated comma-separeated list.")
            //            .isRequired()
            .create("nolist");

    /*----------------------------
      create options object
    ----------------------------*/
    Options options = new Options();

    options.addOption(ohelp);
    options.addOption(ov);
    options.addOption(ostep);
    options.addOption(ooutput);
    options.addOption(odefinition);
    options.addOption(onolist);

    /*----------------------------
      create the parser
    ----------------------------*/
    CommandLineParser parser = new GnuParser();
    try {
        // parse the command line arguments
        commandline = parser.parse(options, args);
    } catch (Exception exp) {
        // oops, something went wrong
        System.err.println("Parsing failed. Reason: " + exp.getMessage());
        exiter();
    }

    /*----------------------------
      usage/help
    ----------------------------*/
    if (commandline.hasOption("help")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("perlcode", options);
        System.exit(0);
    }

    else if (commandline.hasOption("v")) {
        System.out.println("web:     www.prozesskraft.de");
        System.out.println("version: [% version %]");
        System.out.println("date:    [% date %]");
        System.exit(0);
    }

    /*----------------------------
      ueberpruefen ob eine schlechte kombination von parametern angegeben wurde
    ----------------------------*/
    if (!(commandline.hasOption("definition"))) {
        System.err.println("option -definition is mandatory.");
        exiter();
    }

    if (!(commandline.hasOption("output"))) {
        System.err.println("option -output is mandatory.");
        exiter();
    }

    /*----------------------------
      die lizenz ueberpruefen und ggf abbrechen
    ----------------------------*/

    // check for valid license
    ArrayList<String> allPortAtHost = new ArrayList<String>();
    allPortAtHost.add(ini.get("license-server", "license-server-1"));
    allPortAtHost.add(ini.get("license-server", "license-server-2"));
    allPortAtHost.add(ini.get("license-server", "license-server-3"));

    MyLicense lic = new MyLicense(allPortAtHost, "1", "user-edition", "0.1");

    // lizenz-logging ausgeben
    for (String actLine : (ArrayList<String>) lic.getLog()) {
        System.err.println(actLine);
    }

    // abbruch, wenn lizenz nicht valide
    if (!lic.isValid()) {
        System.exit(1);
    }

    /*----------------------------
      die eigentliche business logic
    ----------------------------*/
    Process p1 = new Process();
    java.io.File outputDir = new java.io.File(commandline.getOptionValue("output"));
    java.io.File outputDirProcessScript = new java.io.File(commandline.getOptionValue("output"));
    java.io.File outputDirBin = new java.io.File(commandline.getOptionValue("output") + "/bin");
    java.io.File outputDirLib = new java.io.File(commandline.getOptionValue("output") + "/lib");
    boolean nolist = false;
    if (commandline.hasOption("nolist")) {
        nolist = true;
    }

    if (outputDir.exists()) {
        System.err.println("fatal: directory already exists: " + outputDir.getCanonicalPath());
        exiter();
    } else {
        outputDir.mkdir();
    }

    p1.setInfilexml(commandline.getOptionValue("definition"));
    System.err.println("info: reading process definition " + commandline.getOptionValue("definition"));
    Process p2 = null;
    try {
        p2 = p1.readXml();
    } catch (JAXBException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        System.err.println("error");
        exiter();
    }

    // perlcode generieren fuer einen bestimmten step
    if (commandline.hasOption("step")) {
        outputDirBin.mkdir();
        String stepname = commandline.getOptionValue("step");
        writeStepAsPerlcode(p2, stepname, outputDirBin, nolist);
    }

    // perlcode generieren fuer den gesamten process
    else {
        outputDirBin.mkdir();
        writeProcessAsPerlcode(p2, outputDirProcessScript, outputDirBin, nolist);

        // copy all perllibs from the lib directory
        outputDirLib.mkdir();
        final Path source = Paths.get(WhereAmI.getInstallDirectoryAbsolutePath(Perlcode.class) + "/../perllib");
        final Path target = Paths.get(outputDirLib.toURI());

        copyDirectoryTree.copyDirectoryTree(source, target);
    }
}

From source file:it.isislab.dmason.util.SystemManagement.Worker.thrower.DMasonWorkerWithGui.java

public static void main(String[] args) {
    RuntimeMXBean bean = ManagementFactory.getRuntimeMXBean();

    ///* w  ww  .  j  a  v  a  2  s.co  m*/
    // Get name representing the running Java virtual machine.
    // It returns something like 6460@AURORA. Where the value
    // before the @ symbol is the PID.
    //
    String jvmName = bean.getName();

    //Used for log4j properties
    System.setProperty("logfile.name", "worker" + jvmName);

    //Used for log4j properties
    System.setProperty("steplog.name", "workerStep" + jvmName);

    DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd_HH_mm_ss_SS");
    Date date = new Date();
    dateFormat.format(date);

    System.setProperty("timestamp", date.toLocaleString());

    System.setProperty("paramsfile.name", "params");
    try {
        File logPath = new File("Logs/workers");
        if (logPath.exists())
            FileUtils.cleanDirectory(logPath);
    } catch (IOException e) {
        //not a problem
    }

    logger = Logger.getLogger(DMasonWorker.class.getCanonicalName());
    logger.debug("StartWorker " + VERSION);

    autoStart = false;

    String ip = null;
    String port = null;
    String topic = "";
    updated = false;
    isBatch = false;
    topicPrefix = "";

    // ip, post, autoconnect
    if (args.length == 3) {
        ip = args[0];
        port = args[1];
        if (args[2].equals("autoconnect")) {
            autoStart = true;
        }
    }
    // ip, post, topic, event 
    if (args.length == 4) {
        autoStart = true;
        if (args[3].equals("update")) {
            updated = true;
        }
        if (args[3].equals("reset")) {
            updated = false;
            isBatch = false;
        }
        if (args[3].contains("Batch")) {
            updated = false;
            isBatch = true;
            topicPrefix = args[3];
        }
        ip = args[0];
        port = args[1];
        topic = args[2];
    }

    /*if(args.length == 2 && args[0].equals("auto"))
    {   autoStart = true;
       updated = true;
       topic = args[1];
    }
    if(args.length == 1 && args[0].equals("auto"))
    {   autoStart = true;
    }*/
    new DMasonWorkerWithGui(autoStart, updated, isBatch, topic, ip, port);
}

From source file:craterdog.marketplace.DigitalMarketplaceCli.java

static public void main(String[] args) {
    logger.entry((Object) args);//w  w w. ja v  a2  s.  co  m

    logger.debug("Ensuring the data directory exists...");
    File directory = new File(dataDirectory);
    if (!directory.exists() && !directory.mkdir()) {
        logger.error("Unable to create ~/.cdt/ directory, exiting...");
        System.exit(1);
    }

    logger.debug("Configuring the CLI...");
    String digitalMarketplaceUriString = defaultDigitalAccountantUri;
    if (args.length > 0) {
        digitalMarketplaceUriString = args[0];
    }
    URI digitalMarketplaceUri = URI.create(digitalMarketplaceUriString);
    DigitalMarketplaceCli cli = new DigitalMarketplaceCli(digitalMarketplaceUri);

    logger.debug("Running the CLI...");
    int status = cli.run();

    logger.exit(status);
}

From source file:de.tudarmstadt.ukp.experiments.dip.wp1.documents.Step8GoldDataAggregator.java

public static void main(String[] args) throws Exception {
    String inputDir = args[0] + "/";
    // output dir
    File outputDir = new File(args[1]);
    File turkersConfidence = new File(args[2]);
    if (outputDir.exists()) {
        outputDir.delete();//from  w  w  w .j ava  2  s  . c  om
    }
    outputDir.mkdir();

    List<String> annotatorsIDs = new ArrayList<>();
    //        for (File f : FileUtils.listFiles(new File(inputDir), new String[] { "xml" }, false)) {
    //            QueryResultContainer queryResultContainer = QueryResultContainer
    //                    .fromXML(FileUtils.readFileToString(f, "utf-8"));
    //            for (QueryResultContainer.SingleRankedResult rankedResults : queryResultContainer.rankedResults) {
    //                for (QueryResultContainer.MTurkRelevanceVote relevanceVote : rankedResults.mTurkRelevanceVotes) {
    //                    if (!annotatorsIDs.contains(relevanceVote.turkID))
    //                        annotatorsIDs.add(relevanceVote.turkID);
    //                }
    //            }
    //        }
    HashMap<String, Integer> countVotesForATurker = new HashMap<>();
    // creates temporary file with format for mace
    // Hashmap annotations: key is the id of a document and a sentence
    // Value is an array votes[] of turkers decisions: true or false (relevant or not)
    // the length of this array equals the number of annotators in List<String> annotatorsIDs.
    // If an annotator worked on the task his decision is written in the array otherwise the value is NULL

    // key: queryID + clueWebID + sentenceID
    // value: true and false annotations
    TreeMap<String, Annotations> annotations = new TreeMap<>();

    for (File f : FileUtils.listFiles(new File(inputDir), new String[] { "xml" }, false)) {
        QueryResultContainer queryResultContainer = QueryResultContainer
                .fromXML(FileUtils.readFileToString(f, "utf-8"));
        System.out.println("Reading " + f.getName());
        for (QueryResultContainer.SingleRankedResult rankedResults : queryResultContainer.rankedResults) {
            String documentID = rankedResults.clueWebID;
            for (QueryResultContainer.MTurkRelevanceVote relevanceVote : rankedResults.mTurkRelevanceVotes) {
                Integer turkerID;
                if (!annotatorsIDs.contains(relevanceVote.turkID)) {
                    annotatorsIDs.add(relevanceVote.turkID);
                    turkerID = annotatorsIDs.size() - 1;
                } else {
                    turkerID = annotatorsIDs.indexOf(relevanceVote.turkID);
                }
                Integer count = countVotesForATurker.get(relevanceVote.turkID);
                if (count == null) {
                    count = 0;
                }
                count++;
                countVotesForATurker.put(relevanceVote.turkID, count);

                String id;
                List<Integer> trueVotes;
                List<Integer> falseVotes;
                for (QueryResultContainer.SingleSentenceRelevanceVote singleSentenceRelevanceVote : relevanceVote.singleSentenceRelevanceVotes)
                    if (!"".equals(singleSentenceRelevanceVote.sentenceID)) {

                        id = f.getName() + "_" + documentID + "_" + singleSentenceRelevanceVote.sentenceID;
                        Annotations turkerVotes = annotations.get(id);
                        if (turkerVotes == null) {
                            trueVotes = new ArrayList<>();
                            falseVotes = new ArrayList<>();
                            turkerVotes = new Annotations(trueVotes, falseVotes);
                        }
                        trueVotes = turkerVotes.trueAnnotations;
                        falseVotes = turkerVotes.falseAnnotations;
                        if ("true".equals(singleSentenceRelevanceVote.relevant)) {
                            // votes[turkerID] = true;
                            trueVotes.add(turkerID);
                        } else if ("false".equals(singleSentenceRelevanceVote.relevant)) {
                            //   votes[turkerID] = false;
                            falseVotes.add(turkerID);
                        } else {
                            throw new IllegalStateException("Annotation value of sentence "
                                    + singleSentenceRelevanceVote.sentenceID + " in " + rankedResults.clueWebID
                                    + " equals " + singleSentenceRelevanceVote.relevant);
                        }
                        try {
                            int allVotesCount = trueVotes.size() + falseVotes.size();
                            if (allVotesCount > 5) {
                                System.err.println(id + " doesn't have 5 annotators: true: " + trueVotes.size()
                                        + " false: " + falseVotes.size());

                                // nasty hack, we're gonna strip some data; true votes first
                                /* we can't do that, it breaks something down the line
                                int toRemove = allVotesCount - 5;
                                if (trueVotes.size() >= toRemove) {
                                trueVotes = trueVotes
                                        .subList(0, trueVotes.size() - toRemove);
                                }
                                else if (
                                    falseVotes.size() >= toRemove) {
                                falseVotes = falseVotes
                                        .subList(0, trueVotes.size() - toRemove);
                                }
                                */
                                System.err.println("Adjusted: " + id + " doesn't have 5 annotators: true: "
                                        + trueVotes.size() + " false: " + falseVotes.size());
                            }
                        } catch (IllegalStateException e) {
                            e.printStackTrace();
                        }
                        turkerVotes.trueAnnotations = trueVotes;
                        turkerVotes.falseAnnotations = falseVotes;
                        annotations.put(id, turkerVotes);
                    } else {
                        throw new IllegalStateException(
                                "Empty Sentence ID in " + f.getName() + " for turker " + turkerID);
                    }

            }
        }

    }
    File tmp = printHashMap(annotations, annotatorsIDs.size());

    String file = TEMP_DIR + "/" + tmp.getName();
    MACE.main(new String[] { "--prefix", file });

    //gets the keys of the documents and sentences
    ArrayList<String> lines = (ArrayList<String>) FileUtils.readLines(new File(file + ".prediction"));
    int i = 0;
    TreeMap<String, TreeMap<String, ArrayList<HashMap<String, String>>>> ids = new TreeMap<>();
    ArrayList<HashMap<String, String>> sentences;
    if (lines.size() != annotations.size()) {
        throw new IllegalStateException(
                "The size of prediction file is " + lines.size() + "but expected " + annotations.size());
    }
    for (Map.Entry entry : annotations.entrySet()) { //1001.xml_clueweb12-1905wb-13-07360_8783
        String key = (String) entry.getKey();
        String[] IDs = key.split("_");
        if (IDs.length > 2) {
            String queryID = IDs[0];
            String clueWebID = IDs[1];
            String sentenceID = IDs[2];
            TreeMap<String, ArrayList<HashMap<String, String>>> clueWebIDs = ids.get(queryID);
            if (clueWebIDs == null) {
                clueWebIDs = new TreeMap<>();
            }
            sentences = clueWebIDs.get(clueWebID);
            if (sentences == null) {
                sentences = new ArrayList<>();
            }
            HashMap<String, String> sentence = new HashMap<>();
            sentence.put(sentenceID, lines.get(i));
            sentences.add(sentence);
            clueWebIDs.put(clueWebID, sentences);
            ids.put(queryID, clueWebIDs);
        } else {
            throw new IllegalStateException("Wrong ID " + key);
        }

        i++;
    }

    for (Map.Entry entry : ids.entrySet()) {
        TreeMap<Integer, String> value = (TreeMap<Integer, String>) entry.getValue();
        String queryID = (String) entry.getKey();
        QueryResultContainer queryResultContainer = QueryResultContainer
                .fromXML(FileUtils.readFileToString(new File(inputDir, queryID), "utf-8"));
        for (QueryResultContainer.SingleRankedResult rankedResults : queryResultContainer.rankedResults) {
            for (Map.Entry val : value.entrySet()) {
                String clueWebID = (String) val.getKey();
                if (clueWebID.equals(rankedResults.clueWebID)) {
                    List<QueryResultContainer.SingleSentenceRelevanceVote> goldEstimatedLabels = new ArrayList<>();
                    List<QueryResultContainer.SingleSentenceRelevanceVote> turkersVotes = new ArrayList<>();
                    int size = 0;
                    int hitSize = 0;
                    String hitID = "";
                    for (QueryResultContainer.MTurkRelevanceVote vote : rankedResults.mTurkRelevanceVotes) {
                        if (!hitID.equals(vote.hitID)) {
                            hitID = vote.hitID;
                            hitSize = vote.singleSentenceRelevanceVotes.size();
                            size = size + hitSize;
                            turkersVotes.addAll(vote.singleSentenceRelevanceVotes);
                        } else {
                            if (vote.singleSentenceRelevanceVotes.size() != hitSize) {
                                hitSize = vote.singleSentenceRelevanceVotes.size();
                                size = size + hitSize;
                                turkersVotes.addAll(vote.singleSentenceRelevanceVotes);
                            }
                        }
                    }
                    ArrayList<HashMap<String, String>> sentenceList = (ArrayList<HashMap<String, String>>) val
                            .getValue();
                    if (sentenceList.size() != turkersVotes.size()) {
                        try {
                            throw new IllegalStateException("Expected size of annotations is "
                                    + turkersVotes.size() + "but found " + sentenceList.size()
                                    + " for document " + rankedResults.clueWebID + " in " + queryID);
                        } catch (IllegalStateException ex) {
                            ex.printStackTrace();
                        }
                    }
                    for (QueryResultContainer.SingleSentenceRelevanceVote s : turkersVotes) {
                        String valSentence = null;
                        for (HashMap<String, String> anno : sentenceList) {
                            if (anno.keySet().contains(s.sentenceID)) {
                                valSentence = anno.get(s.sentenceID);
                            }
                        }
                        QueryResultContainer.SingleSentenceRelevanceVote singleSentenceVote = new QueryResultContainer.SingleSentenceRelevanceVote();
                        singleSentenceVote.sentenceID = s.sentenceID;
                        if (("false").equals(valSentence)) {
                            singleSentenceVote.relevant = "false";
                        } else if (("true").equals(valSentence)) {
                            singleSentenceVote.relevant = "true";
                        } else {
                            throw new IllegalStateException("Annotation value of sentence "
                                    + singleSentenceVote.sentenceID + " equals " + val.getValue());
                        }
                        goldEstimatedLabels.add(singleSentenceVote);
                    }
                    rankedResults.goldEstimatedLabels = goldEstimatedLabels;
                }
            }
        }
        File outputFile = new File(outputDir, queryID);
        FileUtils.writeStringToFile(outputFile, queryResultContainer.toXML(), "utf-8");
        System.out.println("Finished " + outputFile);
    }

    ArrayList<String> annotators = (ArrayList<String>) FileUtils.readLines(new File(file + ".competence"));
    FileWriter fileWriter;
    StringBuilder sb = new StringBuilder();
    for (int j = 0; j < annotatorsIDs.size(); j++) {
        String[] s = annotators.get(0).split("\t");
        Float score = Float.parseFloat(s[j]);
        String turkerID = annotatorsIDs.get(j);
        System.out.println(turkerID + " " + score + " " + countVotesForATurker.get(turkerID));
        sb.append(turkerID).append(" ").append(score).append(" ").append(countVotesForATurker.get(turkerID))
                .append("\n");
    }
    fileWriter = new FileWriter(turkersConfidence);
    fileWriter.append(sb.toString());
    fileWriter.close();

}

From source file:au.com.jwatmuff.eventmanager.Main.java

/**
 * Main method.//from w  ww  . j  a va 2s . c  o  m
 */
public static void main(String args[]) {
    LogUtils.setupUncaughtExceptionHandler();

    /* Set timeout for RMI connections - TODO: move to external file */
    System.setProperty("sun.rmi.transport.tcp.handshakeTimeout", "2000");
    updateRmiHostName();

    /*
     * Set up menu bar for Mac
     */
    System.setProperty("apple.laf.useScreenMenuBar", "true");
    System.setProperty("com.apple.mrj.application.apple.menu.about.name", "Event Manager");

    /*
     * Set look and feel to 'system' style
     */
    try {
        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
    } catch (Exception e) {
        log.info("Failed to set system look and feel");
    }

    /*
     * Set workingDir to a writable folder for storing competitions, settings etc.
     */
    String applicationData = System.getenv("APPDATA");
    if (applicationData != null) {
        workingDir = new File(applicationData, "EventManager");
        if (workingDir.exists() || workingDir.mkdirs()) {
            // redirect logging to writable folder
            LogUtils.reconfigureFileAppenders("log4j.properties", workingDir);
        } else {
            workingDir = new File(".");
        }
    }

    // log version for debugging
    log.info("Running version: " + VISIBLE_VERSION + " (Internal: " + VERSION + ")");

    /*
     * Copy license if necessary
     */
    File license1 = new File("license.lic");
    File license2 = new File(workingDir, "license.lic");
    if (license1.exists() && !license2.exists()) {
        try {
            FileUtils.copyFile(license1, license2);
        } catch (IOException e) {
            log.warn("Failed to copy license from " + license1 + " to " + license2, e);
        }
    }
    if (license1.exists() && license2.exists()) {
        if (license1.lastModified() > license2.lastModified()) {
            try {
                FileUtils.copyFile(license1, license2);
            } catch (IOException e) {
                log.warn("Failed to copy license from " + license1 + " to " + license2, e);
            }
        }
    }

    /*
     * Check if run lock exists, if so ask user if it is ok to continue
     */
    if (!obtainRunLock(false)) {
        int response = JOptionPane.showConfirmDialog(null,
                "Unable to obtain run-lock.\nPlease ensure that no other instances of EventManager are running before continuing.\nDo you wish to continue?",
                "Run-lock detected", JOptionPane.YES_NO_OPTION);
        if (response == JOptionPane.YES_OPTION)
            obtainRunLock(true);
        else
            System.exit(0);
    }

    try {
        LoadWindow loadWindow = new LoadWindow();
        loadWindow.setVisible(true);

        loadWindow.addMessage("Reading settings..");

        /*
         * Read properties from file
         */
        final Properties props = new Properties();
        try {
            Properties defaultProps = PropertiesLoaderUtils
                    .loadProperties(new ClassPathResource("eventmanager.properties"));
            props.putAll(defaultProps);
        } catch (IOException ex) {
            log.error(ex);
        }

        props.putAll(System.getProperties());

        File databaseStore = new File(workingDir, "comps");
        int rmiPort = Integer.parseInt(props.getProperty("eventmanager.rmi.port"));

        loadWindow.addMessage("Loading Peer Manager..");
        log.info("Loading Peer Manager");

        ManualDiscoveryService manualDiscoveryService = new ManualDiscoveryService();
        JmDNSRMIPeerManager peerManager = new JmDNSRMIPeerManager(rmiPort, new File(workingDir, "peerid.dat"));
        peerManager.addDiscoveryService(manualDiscoveryService);

        monitorNetworkInterfaceChanges(peerManager);

        loadWindow.addMessage("Loading Database Manager..");
        log.info("Loading Database Manager");

        DatabaseManager databaseManager = new SQLiteDatabaseManager(databaseStore, peerManager);
        LicenseManager licenseManager = new LicenseManager(workingDir);

        loadWindow.addMessage("Loading Load Competition Dialog..");
        log.info("Loading Load Competition Dialog");

        LoadCompetitionWindow loadCompetitionWindow = new LoadCompetitionWindow(databaseManager, licenseManager,
                peerManager);
        loadCompetitionWindow.setTitle(WINDOW_TITLE);

        loadWindow.dispose();
        log.info("Starting Load Competition Dialog");

        while (true) {
            // reset permission checker to use our license
            licenseManager.updatePermissionChecker();

            GUIUtils.runModalJFrame(loadCompetitionWindow);

            if (loadCompetitionWindow.getSuccess()) {
                DatabaseInfo info = loadCompetitionWindow.getSelectedDatabaseInfo();

                if (!databaseManager.checkLock(info.id)) {
                    String message = "EventManager did not shut down correctly the last time this competition was open. To avoid potential data corruption, you are advised to take the following steps:\n"
                            + "1) Do NOT open this competition\n" + "2) Create a backup of this competition\n"
                            + "3) Delete the competition from this computer\n"
                            + "4) If possible, reload this competition from another computer on the network\n"
                            + "5) Alternatively, you may manually load the backup onto all computers on the network, ensuring the 'Preserve competition ID' option is checked.";
                    String title = "WARNING: Potential Data Corruption Detected";

                    int status = JOptionPane.showOptionDialog(null, message, title, JOptionPane.YES_NO_OPTION,
                            JOptionPane.ERROR_MESSAGE, null,
                            new Object[] { "Cancel (recommended)", "Open anyway" }, "Cancel (recommended)");

                    if (status == 0)
                        continue; // return to load competition window
                }

                SynchronizingWindow syncWindow = new SynchronizingWindow();
                syncWindow.setVisible(true);
                long t = System.nanoTime();
                DistributedDatabase database = databaseManager.activateDatabase(info.id, info.passwordHash);
                long dt = System.nanoTime() - t;
                log.debug(String.format("Initial sync in %dms",
                        TimeUnit.MILLISECONDS.convert(dt, TimeUnit.NANOSECONDS)));
                syncWindow.dispose();

                if (loadCompetitionWindow.isNewDatabase()) {
                    GregorianCalendar calendar = new GregorianCalendar();
                    Date today = calendar.getTime();
                    calendar.set(Calendar.MONTH, Calendar.DECEMBER);
                    calendar.set(Calendar.DAY_OF_MONTH, 31);
                    Date endOfYear = new java.sql.Date(calendar.getTimeInMillis());

                    CompetitionInfo ci = new CompetitionInfo();
                    ci.setName(info.name);
                    ci.setStartDate(today);
                    ci.setEndDate(today);
                    ci.setAgeThresholdDate(endOfYear);
                    //ci.setPasswordHash(info.passwordHash);
                    License license = licenseManager.getLicense();
                    if (license != null) {
                        ci.setLicenseName(license.getName());
                        ci.setLicenseType(license.getType().toString());
                        ci.setLicenseContact(license.getContactPhoneNumber());
                    }
                    database.add(ci);
                }

                // Set PermissionChecker to use database's license type
                String competitionLicenseType = database.get(CompetitionInfo.class, null).getLicenseType();
                PermissionChecker.setLicenseType(LicenseType.valueOf(competitionLicenseType));

                TransactionNotifier notifier = new TransactionNotifier();
                database.setListener(notifier);

                MainWindow mainWindow = new MainWindow();
                mainWindow.setDatabase(database);
                mainWindow.setNotifier(notifier);
                mainWindow.setPeerManager(peerManager);
                mainWindow.setLicenseManager(licenseManager);
                mainWindow.setManualDiscoveryService(manualDiscoveryService);
                mainWindow.setTitle(WINDOW_TITLE);
                mainWindow.afterPropertiesSet();

                TestUtil.setActivatedDatabase(database);

                // show main window (modally)
                GUIUtils.runModalJFrame(mainWindow);

                // shutdown procedures

                // System.exit();

                database.shutdown();
                databaseManager.deactivateDatabase(1500);

                if (mainWindow.getDeleteOnExit()) {
                    for (File file : info.localDirectory.listFiles())
                        if (!file.isDirectory())
                            file.delete();
                    info.localDirectory.deleteOnExit();
                }
            } else {
                // This can cause an RuntimeException - Peer is disconnected
                peerManager.stop();
                System.exit(0);
            }
        }
    } catch (Throwable e) {
        log.error("Error in main function", e);
        String message = e.getMessage();
        if (message == null)
            message = "";
        if (message.length() > 100)
            message = message.substring(0, 97) + "...";
        GUIUtils.displayError(null,
                "An unexpected error has occured.\n\n" + e.getClass().getSimpleName() + "\n" + message);
        System.exit(0);
    }
}