Example usage for org.apache.commons.io FilenameUtils getFullPath

List of usage examples for org.apache.commons.io FilenameUtils getFullPath

Introduction

In this page you can find the example usage for org.apache.commons.io FilenameUtils getFullPath.

Prototype

public static String getFullPath(String filename) 

Source Link

Document

Gets the full path from a full filename, which is the prefix + path.

Usage

From source file:MSUmpire.BaseDataStructure.InstrumentParameter.java

public void WriteParamSerialization(String mzXMLFileName) {
    try {/*ww  w .ja  v  a  2s . com*/
        Logger.getRootLogger().info("Writing parameter to file:" + FilenameUtils.getFullPath(mzXMLFileName)
                + FilenameUtils.getBaseName(mzXMLFileName) + "_params.ser...");
        FileOutputStream fout = new FileOutputStream(FilenameUtils.getFullPath(mzXMLFileName)
                + FilenameUtils.getBaseName(mzXMLFileName) + "_params.ser", false);
        ObjectOutputStream oos = new ObjectOutputStream(fout);
        oos.writeObject(this);
        oos.close();
        fout.close();
    } catch (Exception ex) {
        Logger.getRootLogger().error(ExceptionUtils.getStackTrace(ex));
    }
}

From source file:com.salsaw.msalsa.clustal.ClustalOmegaManager.java

@Override
public void callClustal(String clustalPath, ClustalFileMapper clustalFileMapper)
        throws IOException, InterruptedException, SALSAException {
    // Get program path to execute
    List<String> clustalProcessCommands = new ArrayList<String>();
    clustalProcessCommands.add(clustalPath);

    // Create the name of output files
    String inputFileName = FilenameUtils.getBaseName(clustalFileMapper.getInputFilePath());
    String inputFileFolderPath = FilenameUtils.getFullPath(clustalFileMapper.getInputFilePath());
    Path alignmentFilePath = Paths.get(inputFileFolderPath, inputFileName + "-aln.fasta");
    Path guideTreeFilePath = Paths.get(inputFileFolderPath, inputFileName + "-tree.dnd");

    // Set inside file mapper
    clustalFileMapper.setAlignmentFilePath(alignmentFilePath.toString());
    clustalFileMapper.setGuideTreeFilePath(guideTreeFilePath.toString());
    setClustalFileMapper(clustalFileMapper);

    // Create clustal omega data
    generateClustalArguments(clustalProcessCommands);

    // http://www.rgagnon.com/javadetails/java-0014.html
    ProcessBuilder builder = new ProcessBuilder(clustalProcessCommands);
    builder.redirectErrorStream(true);/*from   w  w  w  .  jav  a2s .c  om*/
    System.out.println(builder.command());
    final Process process = builder.start();
    InputStream is = process.getInputStream();
    InputStreamReader isr = new InputStreamReader(is);
    BufferedReader br = new BufferedReader(isr);

    String line;
    while ((line = br.readLine()) != null) {
        System.out.println(line);
    }
    process.waitFor();

    if (process.exitValue() != 0) {
        throw new SALSAException("Failed clustal omega call");
    }
}

From source file:it.drwolf.ridire.session.JobCleaner.java

public void clean(List<String> arcFiles, List<String> digests) {
    try {/*w  w  w.  j a  v a 2  s.c o m*/
        List<String> origFiles = new ArrayList<String>();
        List<String> endFiles = new ArrayList<String>();
        for (int i = 0; i < arcFiles.size(); i++) {
            String origFile = FilenameUtils.getFullPath(arcFiles.get(i)).concat(JobMapperMonitor.RESOURCESDIR)
                    .concat(digests.get(i).concat(".txt"));
            File cleanedFile = new File(origFile + ".2");
            origFiles.add(cleanedFile.getAbsolutePath());
            // duplicate orig file
            String cleanedText = this.ridirePlainTextCleaner.getCleanText(new File(origFile));
            FileUtils.writeStringToFile(cleanedFile, cleanedText, "UTF-8");
            String endFile = this.cleanerPath.concat(System.getProperty("file.separator"))
                    .concat(digests.get(i)).concat(".txt.2");
            endFiles.add(endFile);
        }

        // transfer file to process
        JSch jSch = new JSch();
        com.jcraft.jsch.Session session = jSch.getSession(this.perlUser, "127.0.0.1");
        java.util.Properties config = new java.util.Properties();
        config.put("StrictHostKeyChecking", "no");
        session.setConfig(config);
        session.setPassword(this.perlPw);
        session.connect();
        Channel channel = session.openChannel("sftp");
        channel.connect();
        ChannelSftp c = (ChannelSftp) channel;
        int mode = ChannelSftp.OVERWRITE;
        for (int i = 0; i < origFiles.size(); i++) {
            c.put(origFiles.get(i), endFiles.get(i), mode);
        }
        c.disconnect();
        String command = null;
        // execute script
        for (String endFile : endFiles) {
            command = "perl " + this.cleanerPath.concat(System.getProperty("file.separator")) + "cleaner.pl ";
            channel = session.openChannel("exec");
            ByteArrayOutputStream errorStream = new ByteArrayOutputStream();
            ((ChannelExec) channel).setErrStream(errorStream);
            command += endFile;
            ((ChannelExec) channel).setCommand(command);
            channel.setInputStream(null);
            InputStream inputStream = channel.getInputStream();
            channel.connect();
            byte[] tmp = new byte[1024];
            while (true) {
                while (inputStream.available() > 0) {
                    int i = inputStream.read(tmp, 0, 1024);
                    if (i < 0) {
                        break;
                    }
                }
                if (channel.isClosed()) {
                    break;
                }
                try {
                    Thread.sleep(200);
                } catch (Exception ee) {
                }
            }
        }
        channel.disconnect();
        // get new files
        channel = session.openChannel("sftp");
        channel.connect();
        c = (ChannelSftp) channel;
        List<File> newFiles = new ArrayList<File>();
        for (String endFile : endFiles) {
            File newFile = File.createTempFile("cleanedFile", null);
            newFiles.add(newFile);
            c.get(endFile + ".tmp", newFile.getAbsolutePath());
        }
        c.disconnect();
        // delete files from working directory
        channel = session.openChannel("exec");
        command = "rm " + this.cleanerPath.concat(System.getProperty("file.separator")) + "*.2 "
                + this.cleanerPath.concat(System.getProperty("file.separator")) + "*.2.tmp";
        ((ChannelExec) channel).setCommand(command);
        channel.setInputStream(null);
        channel.connect();
        channel.disconnect();
        session.disconnect();
        for (int i = 0; i < origFiles.size(); i++) {
            File origF = new File(origFiles.get(i));
            FileUtils.deleteQuietly(origF);
            FileUtils.moveFile(newFiles.get(i), origF);
        }
        for (int i = 0; i < origFiles.size(); i++) {
            this.ridireReTagger.retagFile(new File(origFiles.get(i)));
        }
    } catch (JSchException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (SftpException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:de.uzk.hki.da.cb.ShortenFileNamesAction.java

private void deleteEmptyDirsRecursively(String path) {
    String dirPath = FilenameUtils.getFullPath(path);
    File dir = new File(dirPath);
    if (dir.isDirectory() && dir.list().length == 0) {
        dir.delete();//from w  w w. ja v a 2  s  .c o m
        deleteEmptyDirsRecursively(dir.getAbsolutePath());
    }
}

From source file:com.skcraft.launcher.swing.InstanceTableModel.java

@Override
public Object getValueAt(final int rowIndex, final int columnIndex) {
    final Instance instance = instances.get(rowIndex);
    switch (columnIndex) {
    case 0:// ww  w .jav  a2s.  c  o  m
        if (rowIndex == 0)
            return welcomeIcon;
        InstanceIcon instanceIcon = instanceIcons.get(rowIndex);
        if (instanceIcon == null) {
            // freshly-requested icon. First set some defaults
            Icon iconLocal = SwingHelper.createIcon(Launcher.class, "instance_icon.png", 96, 64);
            instanceIcon = new InstanceIcon();
            instanceIcon.setIconLocal(iconLocal);
            try {
                instanceIcon.setIconRemote(
                        buildDownloadIcon(ImageIO.read(Launcher.class.getResource("instance_icon.png"))));
            } catch (IOException e) {
                e.printStackTrace();
            }
            instanceIcons.put(rowIndex, instanceIcon);
        }
        final InstanceIcon instanceIconLoaded = instanceIcons.get(rowIndex);

        if (!instanceIcon.isLoaded()) {
            // attempt to load instance-specific icon
            instanceIconLoaded.setLoaded(true);
            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    String modpackUrlDir = FilenameUtils.getFullPath(instance.getManifestURL().toString());
                    URL instanceIconUrl = null;
                    try {
                        instanceIconUrl = new URL(modpackUrlDir + "icon.png");
                        //HttpURLConnection conn = (HttpURLConnection) instanceIconUrl.openConnection();
                        //conn.setDoOutput(false);
                        //BufferedImage downloadedIcon = ImageIO.read(conn.getInputStream());
                        BufferedImage downloadedIcon = ImageIO.read(instanceIconUrl);
                        instanceIconLoaded.setIconLocal(new ImageIcon(downloadedIcon));
                        instanceIconLoaded.setIconRemote(buildDownloadIcon(downloadedIcon));
                        fireTableDataChanged();
                    } catch (IOException e) {
                        log.warning("Could not download remote icon for instance '" + instance.getName()
                                + "' from " + instanceIconUrl.toString());
                    }
                }
            });
        }
        if (instance.isLocal()) {
            return instanceIcon.getIconLocal();
        } else {
            return instanceIcon.getIconRemote();
        }
    case 1:
        return instance.getTitle();
    default:
        return null;
    }
}

From source file:DIA_Umpire_To_Skyline.FileThread.java

private void ChangeScanTitlePepXML() throws FileNotFoundException, IOException {
    File fileEntry = new File(FilenameUtils.getFullPath(mzXMLFile));
    String basename = FilenameUtils.getBaseName(mzXMLFile);
    for (File file : fileEntry.listFiles()) {
        if (file.isFile() && file.getAbsoluteFile().toString().toLowerCase().endsWith("pep.xml")) {
            String pepxmlbase = file.getName().split("\\.")[0];
            if (pepxmlbase.equals(basename + "_Q1") || pepxmlbase.equals(basename + "_Q2")
                    || pepxmlbase.equals(basename + "_Q3")) {
                BufferedReader reader = new BufferedReader(new FileReader(file));
                String outputname = file.getName().replace("_Q", ".ForLibQ");
                Logger.getRootLogger()
                        .info("Writing new pepXML files and correct the scan titles: " + outputname);
                FileWriter writer = new FileWriter(FilenameUtils.getFullPath(mzXMLFile)
                        + FilenameUtils.getBaseName(mzXMLFile) + "_Skyline/" + outputname);
                String line = "";
                while ((line = reader.readLine()) != null) {
                    writer.write(line.replaceAll(basename + "_Q", basename + ".ForLibQ") + "\n");
                }/*from  ww  w.  j  a  v  a  2 s. c  o  m*/
                writer.close();
            }
        }
    }
}

From source file:MSUmpire.SeqUtility.FastaParser.java

public boolean FasterSerialzationWrite(String Filename) throws FileNotFoundException {
    try {//from   w w  w . j  a v  a2 s.  c  om
        org.apache.log4j.Logger.getRootLogger().info("Writing fasta serialization to file:"
                + FilenameUtils.getFullPath(Filename) + FilenameUtils.getBaseName(Filename) + ".FastaSer...");
        FileOutputStream fout = new FileOutputStream(
                FilenameUtils.getFullPath(Filename) + FilenameUtils.getBaseName(Filename) + ".FastaSer", false);
        FSTObjectOutput out = new FSTObjectOutput(fout);
        out.writeObject(this);
        out.close();
        fout.close();
    } catch (Exception ex) {
        org.apache.log4j.Logger.getRootLogger().error(ExceptionUtils.getStackTrace(ex));
        return false;
    }
    return true;
}

From source file:context.ui.misc.FileHandler.java

/**
 *
 * @param path//from   w  w  w .j  a  v  a 2 s.  co  m
 * @return
 */
public static String getDirOrParentDir(String path) {
    File file = new File(path);
    if (!file.exists()) {
        System.out.println("The path not exist: " + path);
        return path;
    } else if (file.isDirectory()) {
        return path;
    } else if (file.isFile()) {
        return FilenameUtils.getFullPath(path);
    }
    return null;
}

From source file:context.ui.control.codebooknetwork.CodebookNetworkController.java

/**
 *
 * @param event/*from   w  w  w  . j  a va2s  .  c  o m*/
 */
@Override
public void handleStep3RunButton(ActionEvent event) {
    if (!this.validateInputOutput()) {
        return;
    }
    CodebookApplicationTaskInstance instance = (CodebookApplicationTaskInstance) getTaskInstance();
    CodebookNetworkConfigurationController confController = (CodebookNetworkConfigurationController) configurationController;
    StringProperty inputPath = basicInputViewController.getSelectedItemLabel().textProperty();
    StringProperty inputname = basicInputViewController.getSelectedCorpusName();
    CorpusData input = new CorpusData(inputname, inputPath);
    instance.setInput(input);

    final StringProperty outputPath = basicOutputViewController.getOutputDirTextField().textProperty();

    final String subdirectory = outputPath.get() + "/CB-Results/";
    FileHandler.createDirectory(subdirectory);
    System.out.println("Created sub dir: " + subdirectory);

    FileList output = new FileList(NamingPolicy.generateOutputName(inputname.get(), outputPath.get(), instance),
            subdirectory);
    instance.setTextOutput(output);

    StringProperty tabularName = NamingPolicy.generateTabularName(inputname.get(), outputPath.get(), instance);
    StringProperty csvTabularPath = NamingPolicy.generateTabularPath(inputname.get(), outputPath.get(),
            instance);
    StringProperty gexfTabularPath = NamingPolicy.generateTabularPath(inputname.get(), outputPath.get(),
            instance, ".gexf");

    csvTabularPath.set(FilenameUtils.getFullPath(csvTabularPath.get()) + "CorpusNetwork.csv");
    gexfTabularPath.set(FilenameUtils.getFullPath(gexfTabularPath.get()) + "CorpusNetwork.gexf");
    System.out.println("CSV Path: " + csvTabularPath.get() + "\nGexF Path: " + gexfTabularPath.get());

    List<TabularData> td = new ArrayList<TabularData>();
    td.add(0, new TabularData(tabularName, csvTabularPath));
    td.add(1, new TabularData(new SimpleStringProperty(tabularName.get() + "-gexf"), gexfTabularPath));

    instance.setTabularOutput(td);

    instance.setCodebookFile(confController.getCodebookFile());
    instance.setDistance(confController.getDistance());
    instance.setIsDrop(confController.getCodebookMode());
    instance.setIsNormal(confController.getCodebookMethod());
    if (confController.getAggregationType() == 0) { // per document
        instance.setNetInputCorpus(false);
    } else { //per corpus
        instance.setNetInputCorpus(true);
    }
    instance.setNetOutputCSV(true);
    instance.setNetOutputGEXF(true);
    instance.setNetOutputType(confController.getNetworkType());
    instance.setNetwork(true);
    instance.setSeparator(confController.getUnitOfAnalysis());
    instance.setCustomTag(confController.getCustomTag());

    CTask task = new CodebookApplicationTask(this.getProgress(), this.getProgressMessage());
    task.setTaskInstance(instance);
    task.setOnSucceeded(new EventHandler<WorkerStateEvent>() {
        @Override
        public void handle(WorkerStateEvent t) {
            activeAllControls();
            nextStepsViewController = new CodebookNetworkNextStepsController(
                    NamingPolicy.generateTaskName(CodebookApplicationTaskInstance.class).get());
            nextStepsViewController.setParent(CodebookNetworkController.this);
            nextStepsViewController.setOutputDir(outputPath.get());
            nextStepsViewController.setTabular(getTaskInstance().getTabularOutput(0));
            nextStepsViewController.setFilelist((FileList) getTaskInstance().getTextOutput());
            nextStepsViewController.init();
            ProjectManager.getThisProject().addResult(getTaskInstance().getTabularOutput(0));
            ProjectManager.getThisProject().addData(getTaskInstance().getTextOutput());
            //                ProjectManager.getThisProject().addResult(getTaskInstance().getTabularOutput(1));
            if (isNew()) {
                ProjectManager.getThisProject().addTask(getTaskInstance());
                setNew(false);
            }
            showNextStepPane(nextStepsViewController);
        }
    });
    getProgressBar().setVisible(true);
    deactiveAllControls();
    task.start();

    setTaskInstance(task.getTaskInstance());

}

From source file:it.drwolf.ridire.util.fixingpos.AsyncPosFixer.java

@SuppressWarnings("unchecked")
@Asynchronous//from w  w  w  . j a  v a 2s  .  c o m
public void doAsyncFix(PosFixerData posFixerData) {
    StrTokenizer strTokenizer = new StrTokenizer("\t");
    File destDir = new File(posFixerData.getDestDir());
    File reverseDestDir = new File(posFixerData.getReverseDestDir());
    if (!destDir.exists() || !destDir.isDirectory() || !reverseDestDir.exists()
            || !reverseDestDir.isDirectory()) {
        System.err.println("Not valid destination folder.");
        return;
    }
    this.ridireReTagger = new RIDIREReTagger(null);
    try {
        this.entityManager = (EntityManager) Component.getInstance("entityManager");
        this.userTx = (UserTransaction) org.jboss.seam.Component
                .getInstance("org.jboss.seam.transaction.transaction");
        this.userTx.setTransactionTimeout(1000 * 10 * 60);
        if (!this.userTx.isActive()) {
            this.userTx.begin();
        }
        this.entityManager.joinTransaction();
        String treeTaggerBin = this.entityManager
                .find(CommandParameter.class, CommandParameter.TREETAGGER_EXECUTABLE_KEY).getCommandValue();
        this.ridireReTagger.setTreetaggerBin(treeTaggerBin);
        this.entityManager.flush();
        this.entityManager.clear();
        this.userTx.commit();
        List<String> lines = FileUtils.readLines(new File(posFixerData.getFile()));
        int count = 0;
        for (String l : lines) {
            if (l == null || l.trim().length() < 1) {
                continue;
            }
            String digest = l.replaceAll("\\./", "").replaceAll("\\.vrt", "");
            if (!this.userTx.isActive()) {
                this.userTx.begin();
            }
            this.entityManager.joinTransaction();
            List<CrawledResource> crs = this.entityManager
                    .createQuery("from CrawledResource cr where cr.digest=:digest")
                    .setParameter("digest", digest).getResultList();
            if (crs.size() != 1) {
                System.err.println("PosFixer: " + l + " resource not found.");
            } else {
                CrawledResource cr = crs.get(0);
                String origFile = FilenameUtils.getFullPath(cr.getArcFile())
                        .concat(JobMapperMonitor.RESOURCESDIR).concat(digest.concat(".txt"));
                File toBeRetagged = new File(origFile);
                if (toBeRetagged.exists() && toBeRetagged.canRead()) {
                    String retaggedFile = this.ridireReTagger.retagFile(toBeRetagged);
                    int wordsNumber = this.wordCounter.countWordsFromPoSTagResource(new File(retaggedFile));
                    cr.setWordsNumber(wordsNumber);
                    this.entityManager.persist(cr);
                    this.vrtFilesBuilder.createVRTFile(retaggedFile, strTokenizer, cr, destDir);
                    String vrtFileName = destDir + System.getProperty("file.separator") + digest + ".vrt";
                    File vrtFile = new File(vrtFileName);
                    this.vrtFilesBuilder.reverseFile(reverseDestDir, vrtFile);
                }
            }
            this.userTx.commit();
            System.out.println(" Processed " + (++count) + " of " + lines.size());
        }
    } catch (SystemException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (NotSupportedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (SecurityException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IllegalStateException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (RollbackException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (HeuristicMixedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (HeuristicRollbackException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
        try {
            if (this.userTx != null && this.userTx.isActive()) {
                this.userTx.rollback();
            }
        } catch (IllegalStateException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (SecurityException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (SystemException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
    }
}