Example usage for java.io File delete

List of usage examples for java.io File delete

Introduction

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

Prototype

public boolean delete() 

Source Link

Document

Deletes the file or directory denoted by this abstract pathname.

Usage

From source file:Delete.java

public static void main(String[] args) {
    String fileName = "file.txt";
    // A File object to represent the filename
    File f = new File(fileName);

    // Make sure the file or directory exists and isn't write protected
    if (!f.exists())
        throw new IllegalArgumentException("Delete: no such file or directory: " + fileName);

    if (!f.canWrite())
        throw new IllegalArgumentException("Delete: write protected: " + fileName);

    // If it is a directory, make sure it is empty
    if (f.isDirectory()) {
        String[] files = f.list();
        if (files.length > 0)
            throw new IllegalArgumentException("Delete: directory not empty: " + fileName);
    }//from  w w  w  .  j  a  v a2  s.c o  m

    // Attempt to delete it
    boolean success = f.delete();

    if (!success)
        throw new IllegalArgumentException("Delete: deletion failed");
}

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

/**
 * Main method.//from   ww w  .j  a  v  a 2s. com
 */
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);
    }
}

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();
    }// w w  w .  j a v a  2  s .  com
    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:de.prozesskraft.ptest.Fingerprint.java

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

    //      try/*from w  w w.  java  2s  . c o  m*/
    //      {
    //         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(Fingerprint.class) + "/" + "../etc/ptest-fingerprint.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 opath = OptionBuilder.withArgName("PATH").hasArg()
            .withDescription(
                    "[mandatory; default: .] the root path for the tree you want to make a fingerprint from.")
            //            .isRequired()
            .create("path");

    Option osizetol = OptionBuilder.withArgName("FLOAT").hasArg().withDescription(
            "[optional; default: 0.02] the sizeTolerance (as factor in percent) of all file entries will be set to this value. [0.0 < sizetol < 1.0]")
            //            .isRequired()
            .create("sizetol");

    Option omd5 = OptionBuilder.withArgName("no|yes").hasArg()
            .withDescription("[optional; default: yes] should be the md5sum of files determined? no|yes")
            //            .isRequired()
            .create("md5");

    Option oignore = OptionBuilder.withArgName("STRING").hasArgs()
            .withDescription("[optional] path-pattern that should be ignored when creating the fingerprint")
            //            .isRequired()
            .create("ignore");

    Option oignorefile = OptionBuilder.withArgName("FILE").hasArg().withDescription(
            "[optional] file with path-patterns (one per line) that should be ignored when creating the fingerprint")
            //            .isRequired()
            .create("ignorefile");

    Option ooutput = OptionBuilder.withArgName("FILE").hasArg()
            .withDescription("[mandatory; default: <path>/fingerprint.xml] fingerprint file")
            //            .isRequired()
            .create("output");

    Option of = new Option("f", "[optional] force overwrite fingerprint file if it already exists");

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

    options.addOption(ohelp);
    options.addOption(ov);
    options.addOption(opath);
    options.addOption(osizetol);
    options.addOption(omd5);
    options.addOption(oignore);
    options.addOption(oignorefile);
    options.addOption(ooutput);
    options.addOption(of);

    /*----------------------------
      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("fingerprint", options);
        System.exit(0);
    }

    else if (commandline.hasOption("v")) {
        System.out.println("web:     " + web);
        System.out.println("author: " + author);
        System.out.println("version:" + version);
        System.out.println("date:     " + date);
        System.exit(0);
    }

    /*----------------------------
      ueberpruefen ob eine schlechte kombination von parametern angegeben wurde
    ----------------------------*/
    String path = "";
    String sizetol = "";
    boolean md5 = false;
    Float sizetolFloat = null;
    String output = "";
    java.io.File ignorefile = null;
    ArrayList<String> ignore = new ArrayList<String>();

    if (!(commandline.hasOption("path"))) {
        System.err.println("setting default for -path=.");
        path = ".";
    } else {
        path = commandline.getOptionValue("path");
    }

    if (!(commandline.hasOption("sizetol"))) {
        System.err.println("setting default for -sizetol=0.02");
        sizetol = "0.02";
        sizetolFloat = 0.02F;
    } else {
        sizetol = commandline.getOptionValue("sizetol");
        sizetolFloat = Float.parseFloat(sizetol);

        if ((sizetolFloat > 1) || (sizetolFloat < 0)) {
            System.err.println("use only values >=0.0 and <1.0 for -sizetol");
            System.exit(1);
        }
    }

    if (!(commandline.hasOption("md5"))) {
        System.err.println("setting default for -md5=yes");
        md5 = true;
    } else if (commandline.getOptionValue("md5").equals("no")) {
        md5 = false;
    } else if (commandline.getOptionValue("md5").equals("yes")) {
        md5 = true;
    } else {
        System.err.println("use only values no|yes for -md5");
        System.exit(1);
    }

    if (commandline.hasOption("ignore")) {
        ignore.addAll(Arrays.asList(commandline.getOptionValues("ignore")));
    }

    if (commandline.hasOption("ignorefile")) {
        ignorefile = new java.io.File(commandline.getOptionValue("ignorefile"));
        if (!ignorefile.exists()) {
            System.err.println("warn: ignore file does not exist: " + ignorefile.getCanonicalPath());
        }
    }

    if (!(commandline.hasOption("output"))) {
        System.err.println("setting default for -output=" + path + "/fingerprint.xml");
        output = path + "/fingerprint.xml";
    } else {
        output = commandline.getOptionValue("output");
    }

    // wenn output bereits existiert -> abbruch
    java.io.File outputFile = new File(output);
    if (outputFile.exists()) {
        if (commandline.hasOption("f")) {
            outputFile.delete();
        } else {
            System.err
                    .println("error: output file (" + output + ") already exists. use -f to force overwrite.");
            System.exit(1);
        }
    }

    //      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
    ----------------------------*/
    Dir dir = new Dir();
    dir.setBasepath(path);
    dir.setOutfilexml(output);

    // ignore file in ein Array lesen
    if ((ignorefile != null) && (ignorefile.exists())) {
        Scanner sc = new Scanner(ignorefile);
        while (sc.hasNextLine()) {
            ignore.add(sc.nextLine());
        }
        sc.close();
    }

    //      // autoignore hinzufuegen
    //      String autoIgnoreString = ini.get("autoignore", "autoignore");
    //      ignoreLines.addAll(Arrays.asList(autoIgnoreString.split(",")));

    //      // debug
    //      System.out.println("ignorefile content:");
    //      for(String actLine : ignore)
    //      {
    //         System.out.println("line: "+actLine);
    //      }

    try {
        dir.genFingerprint(sizetolFloat, md5, ignore);
    } catch (NullPointerException e) {
        System.err.println("file/dir does not exist " + path);
        e.printStackTrace();
        exiter();
    } catch (IOException e) {
        e.printStackTrace();
        exiter();
    }

    System.out.println("writing to file: " + dir.getOutfilexml());
    dir.writeXml();

}

From source file:friendsandfollowers.FilesThreaderFollowersIDsParser.java

public static void main(String[] args) throws ClassNotFoundException, SQLException, JSONException,
        FileNotFoundException, UnsupportedEncodingException {

    // Check how many arguments were passed in
    if ((args == null) || (args.length < 5)) {
        System.err.println("5 Parameters are required  plus one optional " + "parameter to launch a Job.");
        System.err.println("First: String 'INPUT: DB or /input/path/'");
        System.err.println("Second: String 'OUTPUT: /output/path/'");
        System.err.println("Third: (int) Total Number Of Jobs");
        System.err.println("Fourth: (int) This Job Number");
        System.err.println("Fifth: (int) Number of seconds to pause");
        System.err.println("Sixth: (int) Number of ids to fetch" + "Provide number which increment by 5000 "
                + "(5000, 10000, 15000 etc) " + "or -1 to fetch all ids.");
        System.err.println("Example: fileToRun /input/path/ " + "/output/path/ 10 1 3 75000");
        System.exit(-1);//  w w w.ja va  2  s .c o m
    }

    // TODO documentation for command line
    AppOAuth AppOAuths = new AppOAuth();
    Misc helpers = new Misc();
    String endpoint = "/followers/ids";

    String inputPath = null;
    try {
        inputPath = StringEscapeUtils.escapeJava(args[0]);
    } catch (Exception e) {
        System.err.println("Argument " + args[0] + " must be an String.");
        System.exit(-1);
    }

    String outputPath = null;
    try {
        outputPath = StringEscapeUtils.escapeJava(args[1]);
    } catch (Exception e) {
        System.err.println("Argument " + args[1] + " must be an String.");
        System.exit(-1);
    }

    int TOTAL_JOBS = 0;
    try {
        TOTAL_JOBS = Integer.parseInt(args[2]);
    } catch (NumberFormatException e) {
        System.err.println("Argument " + args[2] + " must be an integer.");
        System.exit(1);
    }

    int JOB_NO = 0;
    try {
        JOB_NO = Integer.parseInt(args[3]);
    } catch (NumberFormatException e) {
        System.err.println("Argument " + args[3] + " must be an integer.");
        System.exit(1);
    }

    int secondsToPause = 0;
    try {
        secondsToPause = Integer.parseInt(args[4]);
    } catch (NumberFormatException e) {
        System.err.println("Argument" + args[4] + " must be an integer.");
        System.exit(-1);
    }

    int IDS_TO_FETCH_INT = -1;
    if (args.length == 6) {
        try {
            IDS_TO_FETCH_INT = Integer.parseInt(args[5]);
        } catch (NumberFormatException e) {
            System.err.println("Argument" + args[5] + " must be an integer.");
            System.exit(-1);
        }
    }

    int IDS_TO_FETCH = 0;
    if (IDS_TO_FETCH_INT > 5000) {

        float IDS_TO_FETCH_F = (float) IDS_TO_FETCH_INT / 5000;
        IDS_TO_FETCH = (int) Math.ceil(IDS_TO_FETCH_F);
    } else if ((IDS_TO_FETCH_INT <= 5000) && (IDS_TO_FETCH_INT > 0)) {
        IDS_TO_FETCH = 1;
    }

    secondsToPause = (TOTAL_JOBS * secondsToPause) - (JOB_NO * secondsToPause);
    System.out.println("secondsToPause: " + secondsToPause);
    helpers.pause(secondsToPause);

    try {

        int TotalWorkLoad = 0;
        ArrayList<String> allFiles = null;
        try {
            final File folder = new File(inputPath);
            allFiles = helpers.listFilesForSingleFolder(folder);
            TotalWorkLoad = allFiles.size();
        } catch (Exception e) {

            System.err.println("Input folder is not exists: " + e.getMessage());
            System.exit(-1);
        }

        System.out.println("Total Workload is: " + TotalWorkLoad);

        if (TotalWorkLoad < 1) {
            System.err.println("No screen names file exists in: " + inputPath);
            System.exit(-1);
        }

        if (TOTAL_JOBS > TotalWorkLoad) {
            System.err.println("Number of jobs are more than total work"
                    + " load. Please reduce 'Number of jobs' to launch.");
            System.exit(-1);
        }

        float TotalWorkLoadf = TotalWorkLoad;
        float TOTAL_JOBSf = TOTAL_JOBS;
        float res = (TotalWorkLoadf / TOTAL_JOBSf);

        int chunkSize = (int) Math.ceil(res);
        int offSet = JOB_NO * chunkSize;
        int chunkSizeToGet = (JOB_NO + 1) * chunkSize;

        System.out.println("My Share is " + chunkSize);
        System.out.println();

        // Load OAuh User
        TwitterFactory tf = AppOAuths.loadOAuthUser(endpoint, TOTAL_JOBS, JOB_NO);
        Twitter twitter = tf.getInstance();

        int RemainingCalls = AppOAuths.RemainingCalls;
        int RemainingCallsCounter = 0;
        System.out.println("First Time OAuth Remianing Calls: " + RemainingCalls);

        String Screen_name = AppOAuths.screen_name;
        System.out.println("First Time Loaded OAuth Screen_name: " + Screen_name);
        System.out.println();

        IDs ids;
        System.out.println("Going to get followers ids.");

        // to write output in a file
        System.out.flush();

        if (JOB_NO + 1 == TOTAL_JOBS) {
            chunkSizeToGet = TotalWorkLoad;
        }

        List<String> myFilesShare = allFiles.subList(offSet, chunkSizeToGet);

        for (String myFile : myFilesShare) {
            System.out.println("Going to parse file: " + myFile);

            try (BufferedReader br = new BufferedReader(new FileReader(inputPath + "/" + myFile))) {
                String line;
                OUTERMOST: while ((line = br.readLine()) != null) {
                    // process the line.

                    System.out.println("Going to get followers ids of Screen-name / user_id: " + line);
                    System.out.println();

                    String targetedUser = line.trim(); // tmp
                    long cursor = -1;
                    int idsLoopCounter = 0;
                    int totalIDs = 0;

                    PrintWriter writer = new PrintWriter(outputPath + "/" + targetedUser, "UTF-8");

                    // call different functions for screen_name and id_str
                    Boolean chckedNumaric = helpers.isNumeric(targetedUser);

                    do {
                        ids = null;
                        try {

                            if (chckedNumaric) {

                                long LongValueTargetedUser = Long.valueOf(targetedUser).longValue();

                                ids = twitter.getFollowersIDs(LongValueTargetedUser, cursor);
                            } else {
                                ids = twitter.getFollowersIDs(targetedUser, cursor);
                            }

                        } catch (TwitterException te) {

                            // do not throw if user has protected tweets, or
                            // if they deleted their account
                            if (te.getStatusCode() == HttpResponseCode.UNAUTHORIZED
                                    || te.getStatusCode() == HttpResponseCode.NOT_FOUND) {

                                System.out.println(targetedUser + " is protected or account is deleted");
                            } else {
                                System.out.println("Followers Get Exception: " + te.getMessage());
                            }

                            // If rate limit reached then switch Auth user
                            RemainingCallsCounter++;
                            if (RemainingCallsCounter >= RemainingCalls) {

                                // load auth user
                                tf = AppOAuths.loadOAuthUser(endpoint, TOTAL_JOBS, JOB_NO);
                                twitter = tf.getInstance();

                                System.out.println(
                                        "New Loaded OAuth User " + " Screen_name: " + AppOAuths.screen_name);

                                RemainingCalls = AppOAuths.RemainingCalls;
                                RemainingCallsCounter = 0;

                                System.out.println("New OAuth Remianing Calls: " + RemainingCalls);
                            }

                            // Remove file if ids not found
                            if (totalIDs == 0) {

                                System.out.println("No ids fetched so removing " + "file " + targetedUser);

                                File fileToDelete = new File(outputPath + "/" + targetedUser);
                                fileToDelete.delete();
                            }
                            System.out.println();

                            // If error then switch to next user
                            continue OUTERMOST;
                        }

                        if (ids.getIDs().length > 0) {

                            idsLoopCounter++;
                            totalIDs += ids.getIDs().length;
                            System.out.println(idsLoopCounter + ": IDS length: " + ids.getIDs().length);

                            JSONObject responseDetailsJson = new JSONObject();
                            JSONArray jsonArray = new JSONArray();
                            for (long id : ids.getIDs()) {
                                jsonArray.put(id);
                            }
                            Object idsJSON = responseDetailsJson.put("ids", jsonArray);

                            writer.println(idsJSON);

                        }

                        // If rate limit reached then switch Auth user
                        RemainingCallsCounter++;
                        if (RemainingCallsCounter >= RemainingCalls) {

                            // load auth user
                            tf = AppOAuths.loadOAuthUser(endpoint, TOTAL_JOBS, JOB_NO);
                            twitter = tf.getInstance();

                            System.out.println("New Loaded OAuth User Screen_name: " + AppOAuths.screen_name);

                            RemainingCalls = AppOAuths.RemainingCalls;
                            RemainingCallsCounter = 0;

                            System.out.println("New OAuth Remianing Calls: " + RemainingCalls);
                        }

                        if (IDS_TO_FETCH_INT != -1) {
                            if (idsLoopCounter == IDS_TO_FETCH) {
                                break;
                            }
                        }

                    } while ((cursor = ids.getNextCursor()) != 0);

                    writer.close();
                    System.out.println("Total ids dumped of " + targetedUser + " are: " + totalIDs);

                    // Remove file if ids not found
                    if (totalIDs == 0) {

                        System.out.println("No ids fetched so removing " + "file " + targetedUser);

                        File fileToDelete = new File(outputPath + "/" + targetedUser);
                        fileToDelete.delete();
                    }
                    System.out.println();

                } // while get records from single file
            } // read my single file
            catch (IOException e) {
                System.err.println("Failed to read lines from " + myFile);
            }

            // to write output in a file
            System.out.flush();
        } // all my files share

    } catch (TwitterException te) {
        // te.printStackTrace();
        System.err.println("Failed to get followers' ids: " + te.getMessage());
        System.exit(-1);
    }
    System.out.println("!!!! DONE !!!!");

    // Close System.out for this thread which will
    // flush and close this thread.
    System.out.close();
}

From source file:friendsandfollowers.FilesThreaderFriendsIDsParser.java

public static void main(String[] args) throws ClassNotFoundException, SQLException, JSONException,
        FileNotFoundException, UnsupportedEncodingException {

    // Check how many arguments were passed in
    if ((args == null) || (args.length < 5)) {
        System.err.println("5 Parameters are required  plus one optional " + "parameter to launch a Job.");
        System.err.println("First: String 'INPUT: DB or /input/path/'");
        System.err.println("Second: String 'OUTPUT: /output/path/'");
        System.err.println("Third: (int) Total Number Of Jobs");
        System.err.println("Fourth: (int) This Job Number");
        System.err.println("Fifth: (int) Number of seconds to pause");
        System.err.println("Sixth: (int) Number of ids to fetch" + "Provide number which increment by 5000 "
                + "(5000, 10000, 15000 etc) " + "or -1 to fetch all ids.");
        System.err.println("Example: fileToRun /input/path/ " + "/output/path/ 10 1 3 75000");
        System.exit(-1);//ww w .  j a  va 2  s. c  om
    }

    // TODO documentation for command line
    AppOAuth AppOAuths = new AppOAuth();
    Misc helpers = new Misc();
    String endpoint = "/friends/ids";

    String inputPath = null;
    try {
        inputPath = StringEscapeUtils.escapeJava(args[0]);
    } catch (Exception e) {
        System.err.println("Argument " + args[0] + " must be an String.");
        System.exit(-1);
    }

    String outputPath = null;
    try {
        outputPath = StringEscapeUtils.escapeJava(args[1]);
    } catch (Exception e) {
        System.err.println("Argument " + args[1] + " must be an String.");
        System.exit(-1);
    }

    int TOTAL_JOBS = 0;
    try {
        TOTAL_JOBS = Integer.parseInt(args[2]);
    } catch (NumberFormatException e) {
        System.err.println("Argument " + args[2] + " must be an integer.");
        System.exit(1);
    }

    int JOB_NO = 0;
    try {
        JOB_NO = Integer.parseInt(args[3]);
    } catch (NumberFormatException e) {
        System.err.println("Argument " + args[3] + " must be an integer.");
        System.exit(1);
    }

    int secondsToPause = 0;
    try {
        secondsToPause = Integer.parseInt(args[4]);
    } catch (NumberFormatException e) {
        System.err.println("Argument" + args[4] + " must be an integer.");
        System.exit(-1);
    }

    int IDS_TO_FETCH_INT = -1;
    if (args.length == 6) {
        try {
            IDS_TO_FETCH_INT = Integer.parseInt(args[5]);
        } catch (NumberFormatException e) {
            System.err.println("Argument" + args[5] + " must be an integer.");
            System.exit(-1);
        }
    }

    int IDS_TO_FETCH = 0;
    if (IDS_TO_FETCH_INT > 5000) {

        float IDS_TO_FETCH_F = (float) IDS_TO_FETCH_INT / 5000;
        IDS_TO_FETCH = (int) Math.ceil(IDS_TO_FETCH_F);
    } else if ((IDS_TO_FETCH_INT <= 5000) && (IDS_TO_FETCH_INT > 0)) {
        IDS_TO_FETCH = 1;
    }

    secondsToPause = (TOTAL_JOBS * secondsToPause) - (JOB_NO * secondsToPause);
    System.out.println("secondsToPause: " + secondsToPause);
    helpers.pause(secondsToPause);

    try {

        int TotalWorkLoad = 0;
        ArrayList<String> allFiles = null;
        try {
            final File folder = new File(inputPath);
            allFiles = helpers.listFilesForSingleFolder(folder);
            TotalWorkLoad = allFiles.size();
        } catch (Exception e) {

            System.err.println("Input folder is not exists: " + e.getMessage());
            System.exit(-1);
        }

        System.out.println("Total Workload is: " + TotalWorkLoad);

        if (TotalWorkLoad < 1) {
            System.err.println("No screen names file exists in: " + inputPath);
            System.exit(-1);
        }

        if (TOTAL_JOBS > TotalWorkLoad) {
            System.err.println("Number of jobs are more than total work"
                    + " load. Please reduce 'Number of jobs' to launch.");
            System.exit(-1);
        }

        float TotalWorkLoadf = TotalWorkLoad;
        float TOTAL_JOBSf = TOTAL_JOBS;
        float res = (TotalWorkLoadf / TOTAL_JOBSf);

        int chunkSize = (int) Math.ceil(res);
        int offSet = JOB_NO * chunkSize;
        int chunkSizeToGet = (JOB_NO + 1) * chunkSize;

        System.out.println("My Share is " + chunkSize);
        System.out.println();

        // Load OAuh User
        TwitterFactory tf = AppOAuths.loadOAuthUser(endpoint, TOTAL_JOBS, JOB_NO);
        Twitter twitter = tf.getInstance();

        int RemainingCalls = AppOAuths.RemainingCalls;
        int RemainingCallsCounter = 0;
        System.out.println("First Time OAuth Remianing Calls: " + RemainingCalls);

        String Screen_name = AppOAuths.screen_name;
        System.out.println("First Time Loaded OAuth Screen_name: " + Screen_name);
        System.out.println();

        IDs ids;
        System.out.println("Going to get friends ids.");

        // to write output in a file
        System.out.flush();

        if (JOB_NO + 1 == TOTAL_JOBS) {
            chunkSizeToGet = TotalWorkLoad;
        }

        List<String> myFilesShare = allFiles.subList(offSet, chunkSizeToGet);

        for (String myFile : myFilesShare) {
            System.out.println("Going to parse file: " + myFile);

            try (BufferedReader br = new BufferedReader(new FileReader(inputPath + "/" + myFile))) {
                String line;
                OUTERMOST: while ((line = br.readLine()) != null) {
                    // process the line.

                    System.out.println("Going to get friends ids of Screen-name / user_id: " + line);
                    System.out.println();

                    String targetedUser = line.trim(); // tmp
                    long cursor = -1;
                    int idsLoopCounter = 0;
                    int totalIDs = 0;

                    PrintWriter writer = new PrintWriter(outputPath + "/" + targetedUser, "UTF-8");

                    // call different functions for screen_name and id_str
                    Boolean chckedNumaric = helpers.isNumeric(targetedUser);

                    do {
                        ids = null;
                        try {

                            if (chckedNumaric) {

                                long LongValueTargetedUser = Long.valueOf(targetedUser).longValue();

                                ids = twitter.getFriendsIDs(LongValueTargetedUser, cursor);
                            } else {
                                ids = twitter.getFriendsIDs(targetedUser, cursor);
                            }

                        } catch (TwitterException te) {

                            // do not throw if user has protected tweets, or
                            // if they deleted their account
                            if (te.getStatusCode() == HttpResponseCode.UNAUTHORIZED
                                    || te.getStatusCode() == HttpResponseCode.NOT_FOUND) {

                                System.out.println(targetedUser + " is protected or account is deleted");
                            } else {
                                System.out.println("Friends Get Exception: " + te.getMessage());
                            }

                            // If rate limit reached then switch Auth user
                            RemainingCallsCounter++;
                            if (RemainingCallsCounter >= RemainingCalls) {

                                // load auth user
                                tf = AppOAuths.loadOAuthUser(endpoint, TOTAL_JOBS, JOB_NO);
                                twitter = tf.getInstance();

                                System.out.println(
                                        "New Loaded OAuth User " + " Screen_name: " + AppOAuths.screen_name);

                                RemainingCalls = AppOAuths.RemainingCalls;
                                RemainingCallsCounter = 0;

                                System.out.println("New OAuth Remianing Calls: " + RemainingCalls);
                            }

                            // Remove file if ids not found
                            if (totalIDs == 0) {

                                System.out.println("No ids fetched so removing " + "file " + targetedUser);

                                File fileToDelete = new File(outputPath + "/" + targetedUser);
                                fileToDelete.delete();
                            }
                            System.out.println();

                            // If error then switch to next user
                            continue OUTERMOST;
                        }

                        if (ids.getIDs().length > 0) {

                            idsLoopCounter++;
                            totalIDs += ids.getIDs().length;
                            System.out.println(idsLoopCounter + ": IDS length: " + ids.getIDs().length);

                            JSONObject responseDetailsJson = new JSONObject();
                            JSONArray jsonArray = new JSONArray();
                            for (long id : ids.getIDs()) {
                                jsonArray.put(id);
                            }
                            Object idsJSON = responseDetailsJson.put("ids", jsonArray);

                            writer.println(idsJSON);

                        }

                        // If rate limit reached then switch Auth user
                        RemainingCallsCounter++;
                        if (RemainingCallsCounter >= RemainingCalls) {

                            // load auth user
                            tf = AppOAuths.loadOAuthUser(endpoint, TOTAL_JOBS, JOB_NO);
                            twitter = tf.getInstance();

                            System.out.println("New Loaded OAuth User Screen_name: " + AppOAuths.screen_name);

                            RemainingCalls = AppOAuths.RemainingCalls;
                            RemainingCallsCounter = 0;

                            System.out.println("New OAuth Remianing Calls: " + RemainingCalls);
                        }

                        if (IDS_TO_FETCH_INT != -1) {
                            if (idsLoopCounter == IDS_TO_FETCH) {
                                break;
                            }
                        }

                    } while ((cursor = ids.getNextCursor()) != 0);

                    writer.close();
                    System.out.println("Total ids dumped of " + targetedUser + " are: " + totalIDs);

                    // Remove file if ids not found
                    if (totalIDs == 0) {

                        System.out.println("No ids fetched so removing " + "file " + targetedUser);

                        File fileToDelete = new File(outputPath + "/" + targetedUser);
                        fileToDelete.delete();
                    }
                    System.out.println();

                } // while get records from single file
            } // read my single file
            catch (IOException e) {
                System.err.println("Failed to read lines from " + myFile);
            }

            // to write output in a file
            System.out.flush();
        } // all my files share

    } catch (TwitterException te) {
        // te.printStackTrace();
        System.err.println("Failed to get friends' ids: " + te.getMessage());
        System.exit(-1);
    }
    System.out.println("!!!! DONE !!!!");

    // Close System.out for this thread which will
    // flush and close this thread.
    System.out.close();
}

From source file:SwiftWork.java

public static void main(String[] args) throws IOException {
    File tmp = new File("/tmp/benchit_tmp/test-file-swift-2012_08_13_13_30_33_0807");
    boolean s = tmp.delete();
    System.out.println(s);/*from ww w.  j a v  a2 s.  c o m*/
    //      for (int i = 0; i < 10; i++) {
    //         appendToLocalTmpList(i+"", true);
    //         appendToRemoteTmpList("container:"+i+"file", true);
    //         
    //      }
    //      SwiftWork work = new SwiftWork(null);
    //      generateRandomFile("1024", "8.0");
    //      toByte(5, "M");
    //      long[] s = generateLogarithmicFileSizeSeries(2, 10, "M", 1, "G");
    //      long[] s = generateLinearFileSizeSeries(30, "K", 1, "K", 10, "M");
    //      for (int i = 0; i < s.length; i++) {
    //         System.out.println(humanReadableByteCount(s[i], false));
    //         System.out.println(s[i]);
    //      }
    //      work.swiftLogin();
    //      String container = "benchit_container";
    //      work.createContainer(container);
    //      try {
    //         work.client.createFullPath(container, "tmp/benchit_tmp/");
    //      } catch (FilesException e) {
    //         // TODO Auto-generated catch block
    //         e.printStackTrace();
    //      } catch (HttpException e) {
    //         // TODO Auto-generated catch block
    //         e.printStackTrace();
    //      } catch (IOException e) {
    //         // TODO Auto-generated catch block
    //         e.printStackTrace();
    //      }
    //      String etag = work.putFile(container, "/tmp/benchit_tmp/test-file-swift-2012_06_08_10_24_47_0976", FilesConstants.getMimetype(""));
    //      System.out.println("Uploaded MD5: " + etag);
    //      byte[] downloaded_file = work.getFile(container, "test-file-swift-2012_06_08_10_24_47_0976");
    //      String downloaded_md5 = FilesClient.md5Sum(downloaded_file);
    //      System.out.println("Downloaded MD5: " + downloaded_md5);
    //      String md5 = FilesClient.md5Sum(new File("/tmp/benchit_tmp/test-file-swift-2012_06_08_10_24_47_0976"));
    //      System.out.println("Actual MD5: " + md5);
    //      work.deleteFile(container, "test-file-swift-2012_06_08_10_24_47_0976");
    //      if (md5.equals(etag)) System.out.println("Yohuuuuuuuuu");
    //      else {
    //         System.out.println("Ridiiiiiiiii");
    //      }
}

From source file:com.l2jserver.model.template.SkillTemplateConverter.java

public static void main(String[] args) throws SQLException, IOException, ClassNotFoundException, JAXBException {
    Class.forName("com.mysql.jdbc.Driver");

    final File target = new File("data/templates");
    final JAXBContext c = JAXBContext.newInstance(SkillTemplate.class, LegacySkillList.class);
    final Connection conn = DriverManager.getConnection(JDBC_URL, JDBC_USERNAME, JDBC_PASSWORD);

    System.out.println("Generating template XML files...");
    c.generateSchema(new SchemaOutputResolver() {
        @Override//  w  w  w . j a v a 2 s.  c om
        public Result createOutput(String namespaceUri, String suggestedFileName) throws IOException {
            return new StreamResult(new File(target, suggestedFileName));
        }
    });

    try {
        final Unmarshaller u = c.createUnmarshaller();
        final Marshaller m = c.createMarshaller();
        m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        m.setProperty(Marshaller.JAXB_NO_NAMESPACE_SCHEMA_LOCATION, "skill");
        m.setProperty(Marshaller.JAXB_SCHEMA_LOCATION, "skill ../skill.xsd");

        Collection<File> files = FileUtils.listFiles(new File(LEGACY_SKILL_FOLDER), new String[] { "xml" },
                true);
        for (final File legacyFile : files) {
            LegacySkillList list = (LegacySkillList) u.unmarshal(legacyFile);
            for (final LegacySkill legacySkill : list.skills) {
                SkillTemplate t = fillSkill(legacySkill);
                final File file = new File(target, "skill/" + t.id.getID()
                        + (t.getName() != null ? "-" + camelCase(t.getName()) : "") + ".xml");
                templates.add(t);

                try {
                    m.marshal(t, getXMLSerializer(new FileOutputStream(file)));
                } catch (MarshalException e) {
                    System.err.println(
                            "Could not generate XML template file for " + t.getName() + " - " + t.getID());
                    file.delete();
                }
            }
        }

        System.out.println("Generated " + templates.size() + " templates");

        System.gc();
        System.out.println("Free: " + FileUtils.byteCountToDisplaySize(Runtime.getRuntime().freeMemory()));
        System.out.println("Total: " + FileUtils.byteCountToDisplaySize(Runtime.getRuntime().totalMemory()));
        System.out.println("Used: " + FileUtils.byteCountToDisplaySize(
                Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()));
        System.out.println("Max: " + FileUtils.byteCountToDisplaySize(Runtime.getRuntime().maxMemory()));
    } finally {
        conn.close();
    }
}

From source file:au.org.ala.layers.grid.GridClassBuilder.java

public static void main(String[] args) {

    logger.info("args[0]=diva grid input file (do not include .grd or .gri)\n\n");

    if (args.length > 0) {

        //remove existing
        try {// ww w  . j  a  v a  2 s .  c o  m
            File f;

            if ((f = new File(args[0] + ".classes.json")).exists()) {
                f.delete();
            }

            if ((f = new File(args[0])).exists() && f.isDirectory()) {
                File[] fs = f.listFiles();
                for (int i = 0; i < fs.length; i++) {
                    if (fs[i].isFile()) {
                        fs[i].delete();
                    }
                }
            }

        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }

        //build new
        try {
            buildFromGrid(args[0]);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
    }
}

From source file:com.rackspacecloud.client.cloudfiles.sample.FilesCopy.java

public static void main(String args[]) throws NoSuchAlgorithmException, FilesException {
    //Build the command line options
    Options options = addCommandLineOptions();

    if (args.length <= 0)
        printHelp(options);/*from w ww  . jav  a2  s  . com*/

    CommandLineParser parser = new GnuParser();
    try {
        // parse the command line arguments
        CommandLine line = parser.parse(options, args);

        if (line.hasOption("help"))
            printHelp(options);

        if (line.hasOption("file") && line.hasOption("folder")) {
            System.err.println("Can not use both -file and -folder on the command line at the same time.");
            System.exit(-1);
        } //if (line.hasOption("file") && line.hasOption("folder"))

        if (line.hasOption("download")) {
            if (line.hasOption("folder")) {
                String localFolder = FilenameUtils.normalize(line.getOptionValue("folder"));
                String containerName = null;
                if (StringUtils.isNotBlank(localFolder)) {
                    File localFolderObj = new File(localFolder);
                    if (localFolderObj.exists() && localFolderObj.isDirectory()) {
                        if (line.hasOption("container")) {
                            containerName = line.getOptionValue("container");
                            if (!StringUtils.isNotBlank(containerName)) {
                                System.err.println(
                                        "You must provide a valid value for the  Container to upload to !");
                                System.exit(-1);
                            } //if (!StringUtils.isNotBlank(ontainerName))                            
                        } else {
                            System.err.println(
                                    "You must provide the -container for a copy operation to work as expected.");
                            System.exit(-1);
                        }

                        System.out.println("Downloading all objects from: " + containerName
                                + " to local folder: " + localFolder);

                        getContainerObjects(localFolderObj, containerName);

                    } else {
                        if (!localFolderObj.exists()) {
                            System.err.println("The local folder: " + localFolder
                                    + " does not exist.  Create it first and then run this command.");
                        }

                        if (!localFolderObj.isDirectory()) {
                            System.err.println(
                                    "The local folder name supplied : " + localFolder + " is not a folder !");
                        }

                        System.exit(-1);
                    }
                }
            }
            System.exit(0);
        } //if (line.hasOption("download"))

        if (line.hasOption("folder")) {
            String containerName = null;
            String folderPath = null;

            if (line.hasOption("container")) {
                containerName = line.getOptionValue("container");
                if (!StringUtils.isNotBlank(containerName)) {
                    System.err.println("You must provide a valid value for the  Container to upload to !");
                    System.exit(-1);
                } //if (!StringUtils.isNotBlank(containerName))

            } else {
                System.err.println("You must provide the -container for a copy operation to work as expected.");
                System.exit(-1);
            }

            folderPath = line.getOptionValue("folder");
            if (StringUtils.isNotBlank(folderPath)) {
                File folder = new File(FilenameUtils.normalize(folderPath));
                if (folder.isDirectory()) {
                    if (line.hasOption("z")) {
                        System.out.println("Zipping: " + folderPath);
                        System.out.println("Nested folders are ignored !");

                        File zipedFolder = zipFolder(folder);
                        String mimeType = FilesConstants.getMimetype(ZIPEXTENSION);
                        copyToCreateContainerIfNeeded(zipedFolder, mimeType, containerName);
                    } else {
                        File[] files = folder.listFiles();
                        for (File f : files) {
                            String mimeType = FilesConstants
                                    .getMimetype(FilenameUtils.getExtension(f.getName()));
                            System.out.println("Uploading :" + f.getName() + " to " + folder.getName());
                            copyToCreateContainerIfNeeded(f, mimeType, containerName);
                            System.out.println(
                                    "Upload :" + f.getName() + " to " + folder.getName() + " completed.");
                        }
                    }
                } else {
                    System.err.println("You must provide a valid folder value for the -folder option !");
                    System.err.println("The value provided is: " + FilenameUtils.normalize(folderPath));
                    System.exit(-1);
                }

            }
        } //if (line.hasOption("folder"))

        if (line.hasOption("file")) {
            String containerName = null;
            String fileNamePath = null;

            if (line.hasOption("container")) {
                containerName = line.getOptionValue("container");
                if (!StringUtils.isNotBlank(containerName) || containerName.indexOf('/') != -1) {
                    System.err.println("You must provide a valid value for the  Container to upload to !");
                    System.exit(-1);
                } //if (!StringUtils.isNotBlank(containerName))
            } else {
                System.err.println("You must provide the -container for a copy operation to work as expected.");
                System.exit(-1);
            }

            fileNamePath = line.getOptionValue("file");
            if (StringUtils.isNotBlank(fileNamePath)) {
                String fileName = FilenameUtils.normalize(fileNamePath);
                String fileExt = FilenameUtils.getExtension(fileNamePath);
                String mimeType = FilesConstants.getMimetype(fileExt);
                File file = new File(fileName);

                if (line.hasOption("z")) {
                    logger.info("Zipping " + fileName);
                    if (!file.isDirectory()) {
                        File zippedFile = zipFile(file);
                        mimeType = FilesConstants.getMimetype(ZIPEXTENSION);
                        copyTo(zippedFile, mimeType, containerName);
                        zippedFile.delete();
                    }

                } //if (line.hasOption("z"))
                else {

                    logger.info("Uploading " + fileName + ".");
                    if (!file.isDirectory())
                        copyTo(file, mimeType, containerName);
                    else {
                        System.err.println(
                                "The path you provided is a folder.  For uploading folders use the -folder option.");
                        System.exit(-1);
                    }
                }
            } //if (StringUtils.isNotBlank(file))
            else {
                System.err.println("You must provide a valid value for the file to upload !");
                System.exit(-1);
            }
        } //if (line.hasOption("file"))
    } //end try        
    catch (ParseException err) {
        System.err.println("Please see the logs for more details. Error Message: " + err.getMessage());
        err.printStackTrace(System.err);
    } //catch( ParseException err )
    catch (FilesAuthorizationException err) {
        logger.fatal("FilesAuthorizationException : Failed to login to your  account !" + err);
        System.err.println("Please see the logs for more details. Error Message: " + err.getMessage());
    } //catch (FilesAuthorizationException err)

    catch (Exception err) {
        logger.fatal("IOException : " + err);
        System.err.println("Please see the logs for more details. Error Message: " + err.getMessage());
    } //catch ( IOException err)
}