Example usage for java.io File getName

List of usage examples for java.io File getName

Introduction

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

Prototype

public String getName() 

Source Link

Document

Returns the name of the file or directory denoted by this abstract pathname.

Usage

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 a  2 s  .  c o m*/

    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)
}

From source file:com.mosso.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);/*  w w  w. ja v a  2 s  . co m*/

    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 (IOException err) {
        logger.fatal("IOException : " + err);
        System.err.println("Please see the logs for more details. Error Message: " + err.getMessage());
    } //catch ( IOException err)
}

From source file:edu.msu.cme.rdp.readseq.utils.SequenceTrimmer.java

public static void main(String[] args) throws IOException {
    Options options = new Options();
    options.addOption("r", "ref-seq", true,
            "Trim points are given as positions in a reference sequence from this file");
    options.addOption("i", "inclusive", false, "Trim points are inclusive");
    options.addOption("l", "length", true, "Minimum length of sequence after trimming");
    options.addOption("f", "filled-ratio", true,
            "Minimum ratio of filled model positions of sequence after trimming");
    options.addOption("o", "out", true, "Write sequences to directory (default=cwd)");
    options.addOption("s", "stats", true, "Write stats to file");

    PrintWriter statsOut = new PrintWriter(new NullWriter());
    boolean inclusive = false;
    int minLength = 0;
    int minTrimmedLength = 0;
    int maxNs = 0;
    int maxTrimNs = 0;

    int trimStart = 0;
    int trimStop = 0;
    Sequence refSeq = null;//from  w w w.j av  a 2  s .  com
    float minFilledRatio = 0;

    int expectedModelPos = -1;
    String[] inputFiles = null;
    File outdir = new File(".");
    try {
        CommandLine line = new PosixParser().parse(options, args);

        if (line.hasOption("ref-seq")) {
            refSeq = readRefSeq(new File(line.getOptionValue("ref-seq")));
        }

        if (line.hasOption("inclusive")) {
            inclusive = true;
        }

        if (line.hasOption("length")) {
            minLength = Integer.valueOf(line.getOptionValue("length"));
        }

        if (line.hasOption("filled-ratio")) {
            minFilledRatio = Float.valueOf(line.getOptionValue("filled-ratio"));
        }

        if (line.hasOption("out")) {
            outdir = new File(line.getOptionValue("out"));
            if (!outdir.isDirectory()) {
                outdir = outdir.getParentFile();
                System.err.println("Output option is not a directory, using " + outdir + " instead");
            }
        }

        if (line.hasOption("stats")) {
            statsOut = new PrintWriter(line.getOptionValue("stats"));
        }

        args = line.getArgs();

        if (args.length < 3) {
            throw new Exception("Unexpected number of arguments");
        }

        trimStart = Integer.parseInt(args[0]);
        trimStop = Integer.parseInt(args[1]);
        inputFiles = Arrays.copyOfRange(args, 2, args.length);

        if (refSeq != null) {
            expectedModelPos = SeqUtils.getMaskedBySeqString(refSeq.getSeqString()).length();
            trimStart = translateCoord(trimStart, refSeq, CoordType.seq, CoordType.model);
            trimStop = translateCoord(trimStop, refSeq, CoordType.seq, CoordType.model);
        }

    } catch (Exception e) {
        new HelpFormatter().printHelp("SequenceTrimmer <trim start> <trim stop> <aligned file> ...", options);
        System.err.println("Error: " + e.getMessage());
    }

    System.err.println("Starting sequence trimmer");
    System.err.println("*  Input files:           " + Arrays.asList(inputFiles));
    System.err.println("*  Minimum Length:        " + minLength);
    System.err.println("*  Trim point inclusive?: " + inclusive);
    System.err.println("*  Trim points:           " + trimStart + "-" + trimStop);
    System.err.println("*  Min filled ratio:      " + minFilledRatio);
    System.err.println("*  refSeq:                "
            + ((refSeq == null) ? "model" : refSeq.getSeqName() + " " + refSeq.getDesc()));

    Sequence seq;
    SeqReader reader;
    TrimStats stats;

    writeStatsHeader(statsOut);

    FastaWriter seqWriter;
    File in;
    for (String infile : inputFiles) {
        in = new File(infile);
        reader = new SequenceReader(in);
        seqWriter = new FastaWriter(new File(outdir, "trimmed_" + in.getName()));

        while ((seq = reader.readNextSequence()) != null) {
            if (seq.getSeqName().startsWith("#")) {
                seqWriter.writeSeq(seq.getSeqName(), "", trimMetaSeq(seq.getSeqString(), trimStart, trimStop));
                continue;
            }

            stats = getStats(seq, trimStart, trimStop);
            boolean passed = didSeqPass(stats, minLength, minTrimmedLength, maxNs, maxTrimNs, minFilledRatio);
            writeStats(statsOut, seq.getSeqName(), stats, passed);
            if (passed) {
                seqWriter.writeSeq(seq.getSeqName(), seq.getDesc(), new String(stats.trimmedBases));
            }
        }

        reader.close();
        seqWriter.close();
    }

    statsOut.close();
}

From source file:com.chaordicsystems.sstableconverter.SSTableConverter.java

public static void main(String[] args) throws Exception {
    LoaderOptions options = LoaderOptions.parseArgs(args);
    OutputHandler handler = new OutputHandler.SystemOutput(options.verbose, options.debug);

    File srcDir = options.sourceDir;
    File dstDir = options.destDir;
    IPartitioner srcPart = options.srcPartitioner;
    IPartitioner dstPart = options.dstPartitioner;
    String keyspace = options.ks;
    String cf = options.cf;//w  ww.  j  av a2 s  .  co m

    if (keyspace == null) {
        keyspace = srcDir.getParentFile().getName();
    }
    if (cf == null) {
        cf = srcDir.getName();
    }

    CFMetaData metadata = new CFMetaData(keyspace, cf, ColumnFamilyType.Standard, BytesType.instance, null);
    Collection<SSTableReader> originalSstables = readSSTables(srcPart, srcDir, metadata, handler);

    handler.output(
            String.format("Converting sstables of ks[%s], cf[%s], from %s to %s. Src dir: %s. Dest dir: %s.",
                    keyspace, cf, srcPart.getClass().getName(), dstPart.getClass().getName(),
                    srcDir.getAbsolutePath(), dstDir.getAbsolutePath()));

    SSTableSimpleUnsortedWriter destWriter = new SSTableSimpleUnsortedWriter(dstDir, dstPart, keyspace, cf,
            AsciiType.instance, null, 64);

    for (SSTableReader reader : originalSstables) {
        handler.output("Reading: " + reader.getFilename());
        SSTableIdentityIterator row;
        SSTableScanner scanner = reader.getDirectScanner(null);

        // collecting keys to export
        while (scanner.hasNext()) {
            row = (SSTableIdentityIterator) scanner.next();

            destWriter.newRow(row.getKey().key);
            while (row.hasNext()) {
                IColumn col = (IColumn) row.next();
                destWriter.addColumn(col.name(), col.value(), col.timestamp());
            }
        }
        scanner.close();
    }

    // Don't forget to close!
    destWriter.close();

    System.exit(0);
}

From source file:com.hp.test.framework.Reporting.Utlis.java

public static void main(String ar[]) throws IOException {

    ArrayList<String> runs_list = new ArrayList<String>();
    String basepath = replacelogs();
    String path = basepath + "ATU Reports\\Results";
    File directory = new File(path);
    File[] subdirs = directory.listFiles((FileFilter) DirectoryFileFilter.DIRECTORY);
    String htmlReport = basepath + "HTML_Design_Files\\CSS\\HtmlReport.html";
    for (File dir : subdirs) {

        runs_list.add(dir.getName());
    }// w w  w.j a v a 2 s .c o  m
    String Reports_path = basepath + "ATU Reports\\";
    int LatestRun = Utlis.getLastRun(Reports_path);
    String Last_run_path = Reports_path + "Results\\Run_" + String.valueOf(LatestRun) + "\\";

    HtmlParse.replaceMainTable(false, new File(Last_run_path + "/CurrentRun.html"));
    HtmlParse.replaceCountsinJSFile(new File("HTML_Design_Files/JS/3dChart.js"), Last_run_path);
    UpdateTestCaseDesciption.basepath = Last_run_path;
    UpdateTestCaseDesciption.getTestCaseHtmlPath(Last_run_path + "/CurrentRun.html");
    UpdateTestCaseDesciption.replaceDetailsTable(Last_run_path + "/CurrentRun.html");
    //   GenerateFailReport.genarateFailureReport(new File(htmlReport), Reports_path + "Results\\Run_" + String.valueOf(LatestRun));
    genarateFailureReport(new File(htmlReport), Reports_path + "Results\\");
    Map<String, List<String>> runCounts = GetCountsrunsWise(runs_list, path);

    int success = replaceCounts(runCounts, path);

    if (success == 0) {
        File SourceFile = new File(path + "\\lineChart_temp.js");
        File RenameFile = new File(path + "\\lineChart.js");

        renameOriginalFile(SourceFile, RenameFile);

        File SourceFile1 = new File(path + "\\barChart_temp.js");
        File RenameFile1 = new File(path + "\\barChart.js");

        renameOriginalFile(SourceFile1, RenameFile1);

        Utlis.getpaths(Reports_path + "\\Results\\Run_" + String.valueOf(LatestRun));
        try {
            Utlis.replaceMainTable(false, new File(Reports_path + "index.html"));
            Utlis.replaceMainTable(true, new File(Reports_path + "results\\" + "ConsolidatedPage.html"));
            Utlis.replaceMainTable(true,
                    new File(Reports_path + "Results\\Run_" + String.valueOf(LatestRun) + "CurrentRun.html"));

            fileList.add(
                    new File(Reports_path + "\\Results\\Run_" + String.valueOf(LatestRun) + "CurrentRun.html"));
            for (File f : fileList) {
                Utlis.replaceMainTable(true, f);
            }

        } catch (Exception ex) {
            log.info("Error in updating Report format" + ex.getMessage());
        }

        Last_run_path = Reports_path + "Results\\Run_" + String.valueOf(LatestRun) + "\\";

        //   HtmlParse.replaceMainTable(false, new File(Last_run_path + "/CurrentRun.html"));
        //   HtmlParse.replaceCountsinJSFile(new File("../HTML_Design_Files/JS/3dChart.js"), Last_run_path);
        ArrayList<String> to_list = new ArrayList<String>();
        ReportingProperties reportingproperties = new ReportingProperties();
        String temp_eml = reportingproperties.getProperty("TOLIST");
        String JenkinsURL = reportingproperties.getProperty("JENKINSURL");

        String ScreenShotsDir = reportingproperties.getProperty("ScreenShotsDirectory");
        Boolean cleanScreenshotsDir = Boolean.valueOf(reportingproperties.getProperty("CleanPreScreenShots"));
        Boolean generatescreenshots = Boolean.valueOf(reportingproperties.getProperty("GenerateScreenShots"));
        String HtmlreportFilePrefix = reportingproperties.getProperty("HtmlreportFilePrefix");

        if (cleanScreenshotsDir) {
            if (!CleanFilesinDir(ScreenShotsDir)) {
                log.error("Not able to Clean the Previous Run Details in the paht" + ScreenShotsDir);
            } else {
                log.info("Cleaning Previous Run Details in the paht" + ScreenShotsDir + "Sucess");
            }
        }
        List<String> scr_fileList;
        List<String> html_fileList;
        if (generatescreenshots) {
            scr_fileList = GetFileListinDir(ScreenShotsDir, "png");

            int len = scr_fileList.size();
            len = len + 1;

            screenshot.generatescreenshot(Last_run_path + "CurrentRun.html",
                    ScreenShotsDir + "screenshot_" + len + ".png");
            File source = new File(Reports_path + "Results\\HtmlReport.html");
            File dest = new File(ScreenShotsDir + HtmlreportFilePrefix + "_HtmlReport.html");
            //  Files.copy(f.toPath(), (new File((ScreenShotsDir+HtmlreportFilePrefix+"_HtmlReport.html").toPath(),StandardCopyOption.REPLACE_EXISTING);
            FileUtils.copyFile(source, dest);
            scr_fileList.clear();

        }

        scr_fileList = GetFileListinDir(ScreenShotsDir, "png");
        html_fileList = GetFileListinDir(ScreenShotsDir, "html");

        if (temp_eml.length() > 1) {
            String[] to_list_temp = temp_eml.split(",");

            if (to_list_temp.length > 0) {
                for (String to_list_temp1 : to_list_temp) {
                    to_list.add(to_list_temp1);
                }
            }
            if (to_list.size() > 0) {
                screenshot.generatescreenshot(Last_run_path + "CurrentRun.html",
                        Last_run_path + "screenshot.png");

                //    cleanTempDir.cleanandCreate(Reports_path, LatestRun);
                // ZipUtils.ZipFolder(Reports_path + "temp", Reports_path + "ISTF_Reports.zip");
                if (generatescreenshots) {
                    SendingEmail.sendmail(to_list, JenkinsURL, scr_fileList, html_fileList);
                } else {
                    SendingEmail.sendmail(to_list, JenkinsURL, Reports_path + "/Results/HtmlReport.html",
                            Last_run_path + "screenshot.png");
                }

                //  FileUtils.deleteQuietly(new File(Reports_path + "ISTF_Reports.zip"));
                // FileUtils.deleteDirectory(new File(Reports_path + "temp"));
            }
        }
    }
}

From source file:Pathway2Rdf.java

public static void main(String[] args) {
    // The identifer of the pathway under scrutiny

    // Initiate the model
    Model model = ModelFactory.createDefaultModel();
    try {/*  w  w  w .j a v  a  2 s  .c om*/
        File fileName = new File("/tmp/WpGPML/WP1531_45011.gpml");
        String gpml = FileUtils.readFileToString(fileName);
        String wpIdentifier = fileName.getName().substring(0, fileName.getName().indexOf("_"));
        String wpRevision = fileName.getName().substring(fileName.getName().indexOf("_") + 1,
                fileName.getName().indexOf("."));
        addPathway2Rdf(wpIdentifier, wpRevision, gpml);
        System.out.println(FOAF.NS);
        // FileOutputStream fout;
        // fout = new FileOutputStream("/tmp/" + wpIdentifier + ".rdf");
        // model.write(fout, "N-TRIPLE");
    } catch (DOMException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } catch (XPathExpressionException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } catch (ServiceException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } catch (ConverterException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } catch (ParserConfigurationException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } catch (SAXException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:at.spardat.xma.xdelta.JarPatcher.java

/**
 * Main method to make {@link #applyDelta(ZipFile, ZipFile, ZipArchiveOutputStream, BufferedReader)} available at
 * the command line.<br>//from   w ww  . ja  va2s .  c  o m
 * usage JarPatcher source patch output
 *
 * @param args the arguments
 * @throws IOException Signals that an I/O exception has occurred.
 */
public static void main(String[] args) throws IOException {
    String patchName = null;
    String outputName = null;
    String sourceName = null;
    if (args.length == 0) {
        System.err.println("usage JarPatcher patch [output [source]]");
        System.exit(1);
    } else {
        patchName = args[0];
        if (args.length > 1) {
            outputName = args[1];
            if (args.length > 2) {
                sourceName = args[2];
            }
        }
    }
    ZipFile patch = new ZipFile(patchName);
    ZipArchiveEntry listEntry = patch.getEntry("META-INF/file.list");
    if (listEntry == null) {
        System.err.println("Invalid patch - list entry 'META-INF/file.list' not found");
        System.exit(2);
    }
    BufferedReader list = new BufferedReader(new InputStreamReader(patch.getInputStream(listEntry)));
    String next = list.readLine();
    if (sourceName == null) {
        sourceName = next;
    }
    next = list.readLine();
    if (outputName == null) {
        outputName = next;
    }
    int ignoreSourcePaths = Integer.parseInt(System.getProperty("patcher.ignoreSourcePathElements", "0"));
    int ignoreOutputPaths = Integer.parseInt(System.getProperty("patcher.ignoreOutputPathElements", "0"));
    Path sourcePath = Paths.get(sourceName);
    Path outputPath = Paths.get(outputName);
    if (ignoreOutputPaths >= outputPath.getNameCount()) {
        patch.close();
        StringBuilder b = new StringBuilder().append("Not enough path elements to ignore in output (")
                .append(ignoreOutputPaths).append(" in ").append(outputName).append(")");
        throw new IOException(b.toString());
    }
    if (ignoreSourcePaths >= sourcePath.getNameCount()) {
        patch.close();
        StringBuilder b = new StringBuilder().append("Not enough path elements to ignore in source (")
                .append(sourcePath).append(" in ").append(sourceName).append(")");
        throw new IOException(b.toString());
    }
    sourcePath = sourcePath.subpath(ignoreSourcePaths, sourcePath.getNameCount());
    outputPath = outputPath.subpath(ignoreOutputPaths, outputPath.getNameCount());
    File sourceFile = sourcePath.toFile();
    File outputFile = outputPath.toFile();
    if (!(outputFile.getAbsoluteFile().getParentFile().mkdirs()
            || outputFile.getAbsoluteFile().getParentFile().exists())) {
        patch.close();
        throw new IOException("Failed to create " + outputFile.getAbsolutePath());
    }
    new JarPatcher(patchName, sourceFile.getName()).applyDelta(patch, new ZipFile(sourceFile),
            new ZipArchiveOutputStream(new FileOutputStream(outputFile)), list);
    list.close();
}

From source file:languages.TabFile.java

public static void main(String[] args) {
    if (args[0].equals("optimize")) {
        Scanner sc = new Scanner(System.in);
        String targetPath;/*w ww  .j a v a 2s  . c  o m*/
        String originPath;

        System.out.println("Please enter the path of the original *.tab-files:");

        originPath = sc.nextLine();

        System.out.println(
                "Please enter the path where you wish to save the optimized *.tab-files (Directories will be created, existing files with same filenames will be overwritten):");

        targetPath = sc.nextLine();

        sc.close();

        File folder = new File(originPath);
        File[] listOfFiles = folder.listFiles();

        assert listOfFiles != null;
        for (File file : listOfFiles) {
            if (!file.getName().equals("LICENSE")) {
                TabFile origin;
                try {
                    String originFileName = file.getAbsolutePath();
                    System.out.print("Reading file '" + originFileName + "'...");
                    origin = new TabFile(originFileName);
                    System.out.println("Done!");
                    System.out.print("Optimizing file...");
                    TabFile res = TabFile.optimizeDictionaries(origin, 2, true);
                    System.out.println("Done!");

                    String targetFileName = targetPath + File.separator + file.getName();

                    System.out.println("Saving new file as '" + targetFileName + "'...");
                    res.save(targetFileName);
                    System.out.println("Done!");
                } catch (IOException e) {
                    FOKLogger.log(TabFile.class.getName(), Level.SEVERE, "An error occurred", e);
                }
            }
        }
    } else if (args[0].equals("merge")) {
        System.err.println(
                "Merging dictionaries is not supported anymore. Please checkout commit 1a6fa16 to merge dictionaries.");
    }
}

From source file:edu.cornell.med.icb.goby.reads.ColorSpaceConverter.java

public static void main(final String[] args) throws JSAPException, IOException {
    final JSAP jsap = new JSAP();

    final FlaggedOption sequenceOption = new FlaggedOption("input");
    sequenceOption.setRequired(true);//from w  w w. j  a v  a  2s  .  c o m
    sequenceOption.setLongFlag("input");
    sequenceOption.setShortFlag('i');
    sequenceOption.setStringParser(FileStringParser.getParser().setMustBeFile(true).setMustExist(true));
    sequenceOption.setHelp("The input file (in Fasta format) to convert");
    jsap.registerParameter(sequenceOption);

    final FlaggedOption outputOption = new FlaggedOption("output");
    outputOption.setRequired(false);
    outputOption.setLongFlag("output");
    outputOption.setShortFlag('o');
    outputOption.setStringParser(FileStringParser.getParser().setMustBeFile(true));
    outputOption.setHelp("The output file to write to (default = stdout)");
    jsap.registerParameter(outputOption);

    final FlaggedOption titleOption = new FlaggedOption("title");
    titleOption.setRequired(false);
    titleOption.setLongFlag("title");
    titleOption.setShortFlag('t');
    titleOption.setHelp("Title for this conversion");
    jsap.registerParameter(titleOption);

    final Switch verboseOption = new Switch("verbose");
    verboseOption.setLongFlag("verbose");
    verboseOption.setShortFlag('v');
    verboseOption.setHelp("Verbose output");
    jsap.registerParameter(verboseOption);

    final Switch helpOption = new Switch("help");
    helpOption.setLongFlag("help");
    helpOption.setShortFlag('h');
    helpOption.setHelp("Print this message");
    jsap.registerParameter(helpOption);

    jsap.setUsage("Usage: " + ColorSpaceConverter.class.getName() + " " + jsap.getUsage());

    final JSAPResult result = jsap.parse(args);

    if (result.getBoolean("help")) {
        System.out.println(jsap.getHelp());
        System.exit(0);
    }

    if (!result.success()) {
        final Iterator<String> errors = result.getErrorMessageIterator();
        while (errors.hasNext()) {
            System.err.println(errors.next());
        }
        System.err.println(jsap.getUsage());
        System.exit(1);
    }

    final boolean verbose = result.getBoolean("verbose");

    final File sequenceFile = result.getFile("input");
    if (verbose) {
        System.out.println("Reading sequence from: " + sequenceFile);
    }

    // extract the title to use for the output header
    final String title;
    if (result.contains("title")) {
        title = result.getString("title");
    } else {
        title = sequenceFile.getName();
    }

    Reader inputReader = null;
    PrintWriter outputWriter = null;

    try {
        if ("gz".equals(FilenameUtils.getExtension(sequenceFile.getName()))) {
            inputReader = new InputStreamReader(new GZIPInputStream(FileUtils.openInputStream(sequenceFile)));
        } else {
            inputReader = new FileReader(sequenceFile);
        }
        final FastaParser fastaParser = new FastaParser(inputReader);

        final File outputFile = result.getFile("output");
        final OutputStream outputStream;
        if (outputFile != null) {
            outputStream = FileUtils.openOutputStream(outputFile);
            if (verbose) {
                System.out.println("Writing sequence : " + outputFile);
            }
        } else {
            outputStream = System.out;
        }
        outputWriter = new PrintWriter(outputStream);

        // write the header portion of the output
        outputWriter.print("# ");
        outputWriter.print(new Date());
        outputWriter.print(' ');
        outputWriter.print(ColorSpaceConverter.class.getName());
        for (final String arg : args) {
            outputWriter.print(' ');
            outputWriter.print(arg);
        }
        outputWriter.println();
        outputWriter.print("# Cwd: ");
        outputWriter.println(new File(".").getCanonicalPath());
        outputWriter.print("# Title: ");
        outputWriter.println(title);

        // now parse the input sequence
        long sequenceCount = 0;
        final MutableString descriptionLine = new MutableString();
        final MutableString sequence = new MutableString();
        final MutableString colorSpaceSequence = new MutableString();

        while (fastaParser.hasNext()) {
            fastaParser.next(descriptionLine, sequence);
            outputWriter.print('>');
            outputWriter.println(descriptionLine);

            convert(sequence, colorSpaceSequence);
            CompactToFastaMode.writeSequence(outputWriter, colorSpaceSequence);

            sequenceCount++;
            if (verbose && sequenceCount % 10000 == 0) {
                System.out.println("Converted " + sequenceCount + " entries");
            }
        }

        if (verbose) {
            System.out.println("Conversion complete!");
        }
    } finally {
        IOUtils.closeQuietly(inputReader);
        IOUtils.closeQuietly(outputWriter);
    }
}

From source file:GIST.IzbirkomExtractor.IzbirkomExtractor.java

/**
 * @param args//w ww . j av  a2 s. co m
 */
public static void main(String[] args) {

    // process command-line options
    Options options = new Options();
    options.addOption("n", "noaddr", false, "do not do any address matching (for testing)");
    options.addOption("i", "info", false, "create and populate address information table");
    options.addOption("h", "help", false, "this message");

    // database connection
    options.addOption("s", "server", true, "database server to connect to");
    options.addOption("d", "database", true, "OSM database name");
    options.addOption("u", "user", true, "OSM database user name");
    options.addOption("p", "pass", true, "OSM database password");

    // logging options
    options.addOption("l", "logdir", true, "log file directory (default './logs')");
    options.addOption("e", "loglevel", true, "log level (default 'FINEST')");

    // automatically generate the help statement
    HelpFormatter help_formatter = new HelpFormatter();

    // database URI for connection
    String dburi = null;

    // Information message for help screen
    String info_msg = "IzbirkomExtractor [options] <html_directory>";

    try {
        CommandLineParser parser = new GnuParser();
        CommandLine cmd = parser.parse(options, args);

        if (cmd.hasOption('h') || cmd.getArgs().length != 1) {
            help_formatter.printHelp(info_msg, options);
            System.exit(1);
        }

        /* prohibit n and i together */
        if (cmd.hasOption('n') && cmd.hasOption('i')) {
            System.err.println("Options 'n' and 'i' cannot be used together.");
            System.exit(1);
        }

        /* require database arguments without -n */
        if (cmd.hasOption('n')
                && (cmd.hasOption('s') || cmd.hasOption('d') || cmd.hasOption('u') || cmd.hasOption('p'))) {
            System.err.println("Options 'n' and does not need any databse parameters.");
            System.exit(1);
        }

        /* require all 4 database options to be used together */
        if (!cmd.hasOption('n')
                && !(cmd.hasOption('s') && cmd.hasOption('d') && cmd.hasOption('u') && cmd.hasOption('p'))) {
            System.err.println(
                    "For database access all of the following arguments have to be specified: server, database, user, pass");
            System.exit(1);
        }

        /* useful variables */
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'kk:mm");
        String dateString = formatter.format(new Date());

        /* setup logging */
        File logdir = new File(cmd.hasOption('l') ? cmd.getOptionValue('l') : "logs");
        FileUtils.forceMkdir(logdir);
        File log_file_name = new File(
                logdir + "/" + IzbirkomExtractor.class.getName() + "-" + formatter.format(new Date()) + ".log");
        FileHandler log_file = new FileHandler(log_file_name.getPath());

        /* create "latest" link to currently created log file */
        Path latest_log_link = Paths.get(logdir + "/latest");
        Files.deleteIfExists(latest_log_link);
        Files.createSymbolicLink(latest_log_link, Paths.get(log_file_name.getName()));

        log_file.setFormatter(new SimpleFormatter());
        LogManager.getLogManager().reset(); // prevents logging to console
        logger.addHandler(log_file);
        logger.setLevel(cmd.hasOption('e') ? Level.parse(cmd.getOptionValue('e')) : Level.FINEST);

        // open directory with HTML files and create file list
        File dir = new File(cmd.getArgs()[0]);
        if (!dir.isDirectory()) {
            System.err.println("Unable to find directory '" + cmd.getArgs()[0] + "', exiting");
            System.exit(1);
        }
        PathMatcher pmatcher = FileSystems.getDefault()
                .getPathMatcher("glob:?  * ?*.html");
        ArrayList<File> html_files = new ArrayList<>();
        for (Path file : Files.newDirectoryStream(dir.toPath()))
            if (pmatcher.matches(file.getFileName()))
                html_files.add(file.toFile());
        if (html_files.size() == 0) {
            System.err.println("No matching HTML files found in '" + dir.getAbsolutePath() + "', exiting");
            System.exit(1);
        }

        // create csvResultSink
        FileOutputStream csvout_file = new FileOutputStream("parsed_addresses-" + dateString + ".csv");
        OutputStreamWriter csvout = new OutputStreamWriter(csvout_file, "UTF-8");
        ResultSink csvResultSink = new CSVResultSink(csvout, new CSVStrategy('|', '"', '#'));

        // Connect to DB and osmAddressMatcher
        AddressMatcher osmAddressMatcher;
        DBSink dbSink = null;
        DBInfoSink dbInfoSink = null;
        if (cmd.hasOption('n')) {
            osmAddressMatcher = new DummyAddressMatcher();
        } else {
            dburi = "jdbc:postgresql://" + cmd.getOptionValue('s') + "/" + cmd.getOptionValue('d');
            Connection con = DriverManager.getConnection(dburi, cmd.getOptionValue('u'),
                    cmd.getOptionValue('p'));
            osmAddressMatcher = new OsmAddressMatcher(con);
            dbSink = new DBSink(con);
            if (cmd.hasOption('i'))
                dbInfoSink = new DBInfoSink(con);
        }

        /* create resultsinks */
        SinkMultiplexor sm = SinkMultiplexor.newSinkMultiplexor();
        sm.addResultSink(csvResultSink);
        if (dbSink != null) {
            sm.addResultSink(dbSink);
            if (dbInfoSink != null)
                sm.addResultSink(dbInfoSink);
        }

        // create tableExtractor
        TableExtractor te = new TableExtractor(osmAddressMatcher, sm);

        // TODO: printout summary of options: processing date/time, host, directory of HTML files, jdbc uri, command line with parameters

        // iterate through files
        logger.info("Start processing " + html_files.size() + " files in " + dir);
        for (int i = 0; i < html_files.size(); i++) {
            System.err.println("Parsing #" + i + ": " + html_files.get(i));
            te.processHTMLfile(html_files.get(i));
        }

        System.err.println("Processed " + html_files.size() + " HTML files");
        logger.info("Finished processing " + html_files.size() + " files in " + dir);

    } catch (ParseException e1) {
        System.err.println("Failed to parse CLI: " + e1.getMessage());
        help_formatter.printHelp(info_msg, options);
        System.exit(1);
    } catch (IOException e) {
        System.err.println("I/O Exception: " + e.getMessage());
        e.printStackTrace();
        System.exit(1);
    } catch (SQLException e) {
        System.err.println("Database '" + dburi + "': " + e.getMessage());
        System.exit(1);
    } catch (ResultSinkException e) {
        System.err.println("Failed to initialize ResultSink: " + e.getMessage());
        System.exit(1);
    } catch (TableExtractorException e) {
        System.err.println("Failed to initialize Table Extractor: " + e.getMessage());
        System.exit(1);
    } catch (CloneNotSupportedException | IllegalAccessException | InstantiationException e) {
        System.err.println("Something really odd happened: " + e.getMessage());
        e.printStackTrace();
        System.exit(1);
    }
}