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:it.drwolf.ridire.session.async.WordCounter.java

@Asynchronous
public void countWords(Integer jobId) {
    try {/*from  w  w w  .  ja va  2s. c o m*/
        this.userTx = (UserTransaction) org.jboss.seam.Component
                .getInstance("org.jboss.seam.transaction.transaction");
        String resourcesDir = null;
        if (!this.userTx.isActive()) {
            this.userTx.begin();
        }
        this.entityManager.joinTransaction();
        String dir = this.entityManager.find(Parameter.class, Parameter.JOBS_DIR.getKey()).getValue();
        Job curJ = this.entityManager.find(Job.class, jobId);
        if (curJ.getChildJobName() != null && !curJ.isMappedResources()) {
            resourcesDir = dir + JobMapperMonitor.FILE_SEPARATOR + curJ.getChildJobName()
                    + JobMapperMonitor.FILE_SEPARATOR + "arcs" + JobMapperMonitor.FILE_SEPARATOR
                    + JobMapperMonitor.RESOURCESDIR;
        } else {
            resourcesDir = dir + JobMapperMonitor.FILE_SEPARATOR + curJ.getName()
                    + JobMapperMonitor.FILE_SEPARATOR + "arcs" + JobMapperMonitor.FILE_SEPARATOR
                    + JobMapperMonitor.RESOURCESDIR;
        }

        // back compatibility with Heritrix 2
        File resourcesDirFile = new File(resourcesDir);
        if (resourcesDirFile == null || !resourcesDirFile.isDirectory()) {
            resourcesDir = "completed-" + resourcesDir;
        }
        this.entityManager.flush();
        this.userTx.commit();
        Integer jobWords = 0;
        for (CrawledResource cr : curJ.getCrawledResources()) {
            if (!this.userTx.isActive()) {
                this.userTx.begin();
            }
            this.entityManager.joinTransaction();
            this.entityManager.refresh(cr);
            String digest = cr.getDigest();
            if (digest != null) {
                File posFile = new File(resourcesDir + JobMapperMonitor.FILE_SEPARATOR + digest + ".txt.pos");
                if (posFile != null && posFile.exists() && posFile.canRead()) {
                    try {
                        Integer countWordsFromPoSTagResource = this.countWordsFromPoSTagResource(posFile);
                        jobWords += countWordsFromPoSTagResource;
                        cr.setWordsNumber(countWordsFromPoSTagResource);
                        File f = new File(FilenameUtils.getFullPath(cr.getArcFile())
                                + JobMapperMonitor.RESOURCESDIR + cr.getDigest() + ".txt");
                        if (f.exists() && f.canRead()) {
                            cr.setExtractedTextHash(MD5DigestCreator.getMD5Digest(f));
                        }
                        this.entityManager.merge(cr);
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } catch (NoSuchAlgorithmException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }
            this.entityManager.flush();
            this.userTx.commit();
        }
        if (!this.userTx.isActive()) {
            this.userTx.begin();
        }
        this.entityManager.joinTransaction();
        Job j = this.entityManager.find(Job.class, jobId);
        j.setWordsNumber(jobWords);
        this.entityManager.persist(j);
        this.entityManager.flush();
        this.userTx.commit();
    } catch (NotSupportedException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } catch (SystemException e1) {
        // TODO Auto-generated catch block
        e1.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();
    }
}

From source file:com.notesrender.templatej.TemplateProcessor.java

public void process(String filePath) {
    try {/*ww w.jav  a  2 s . c  o  m*/
        XMLReader rd = XMLReaderFactory.createXMLReader();
        rd.setContentHandler(this);
        rd.parse(new InputSource(new FileInputStream(filePath)));

        String fullFilePath = new File(filePath).getAbsolutePath();
        String dir = FilenameUtils.getFullPath(fullFilePath);
        String tplFullFilePath = new File(dir, _ref).getAbsolutePath();
        String outFullFilePath = new File(dir, _out).getAbsolutePath();

        _writer = new PrintWriter(new BufferedWriter(new FileWriter(outFullFilePath)));
        rd.parse(new InputSource(new FileInputStream(tplFullFilePath)));
        _writer.close();
    } catch (SAXException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:de.uzk.hki.da.convert.TiffConversionStrategy.java

@Override
public List<Event> convertFile(WorkArea wa, ConversionInstruction ci) {

    List<Event> resultEvents = new ArrayList<Event>();

    String input = wa.toFile(ci.getSource_file()).getAbsolutePath();
    String[] commandAsArray;//from  w w w.  j  av a2 s.c  o  m
    String prunedError = "";
    FormatCmdLineExecutor cle = new FormatCmdLineExecutor(cliConnector, knownErrors);
    try {
        // Codec identification is done by subformatidentification
        ImageMagickSubformatIdentifier imsf = new ImageMagickSubformatIdentifier();
        imsf.setKnownFormatCommandLineErrors(knownErrors);
        imsf.setCliConnector(cliConnector);

        if (imsf.identify(new File(input), prune).indexOf("None") >= 0)
            return resultEvents;

        // create subfolder if necessary
        Path.make(wa.dataPath(), object.getNameOfLatestBRep(), ci.getTarget_folder()).toFile().mkdirs();

        commandAsArray = new String[] { "convert", "+compress", input, generateTargetFilePath(wa, ci) };

        logger.debug("Try to Execute conversion command: " + StringUtils.join(commandAsArray, ","));

        cle.setPruneExceptions(prune);
        try {
            cle.execute(commandAsArray);
        } catch (UserFileFormatException ufe) {
            if (!ufe.isWasPruned())
                throw ufe;
            prunedError = " " + ufe.getKnownError().getError_name() + " ISSUED WAS PRUNED BY USER!";
        }
    } catch (IOException e1) {
        throw new RuntimeException(e1);
    }

    File result = new File(generateTargetFilePath(wa, ci));

    String baseName = FilenameUtils.getBaseName(result.getAbsolutePath());
    String extension = FilenameUtils.getExtension(result.getAbsolutePath());
    logger.info("Finding files matching wildcard expression \"" + baseName + "*." + extension
            + "\" in order to check them and test if conversion was successful");
    List<File> results = findFilesWithWildcard(new File(FilenameUtils.getFullPath(result.getAbsolutePath())),
            baseName + "*." + extension);

    for (File f : results) {
        DAFile daf = new DAFile(object.getNameOfLatestBRep(),
                StringUtilities.slashize(ci.getTarget_folder()) + f.getName());
        logger.debug("new dafile:" + daf);

        Event e = new Event();
        e.setType("CONVERT");

        e.setDetail(StringUtilities.createString(commandAsArray) + prunedError);
        e.setSource_file(ci.getSource_file());
        e.setTarget_file(daf);
        e.setDate(new Date());

        resultEvents.add(e);
    }

    return resultEvents;
}

From source file:eu.esdihumboldt.hale.io.html.HtmlMappingExporter.java

@Override
protected IOReport execute(ProgressIndicator progress, IOReporter reporter)
        throws IOProviderConfigurationException, IOException {
    this.reporter = reporter;

    context = new VelocityContext();
    cellIds = new Identifiers<Cell>(Cell.class, false);

    alignment = getAlignment();/*from   w  w  w  .ja  v  a  2s  .c  o m*/

    URL headlinePath = this.getClass().getResource("bg-headline.png"); //$NON-NLS-1$
    URL cssPath = this.getClass().getResource("style.css"); //$NON-NLS-1$
    URL linkPath = this.getClass().getResource("int_link.png"); //$NON-NLS-1$
    URL tooltipIcon = this.getClass().getResource("tooltip.gif"); //$NON-NLS-1$
    final String filesSubDir = FilenameUtils
            .removeExtension(FilenameUtils.getName(getTarget().getLocation().getPath())) + "_files"; //$NON-NLS-1$
    final File filesDir = new File(FilenameUtils.getFullPath(getTarget().getLocation().getPath()), filesSubDir);

    filesDir.mkdirs();
    context.put(FILE_DIRECTORY, filesSubDir);

    try {
        init();
    } catch (Exception e) {
        return reportError(reporter, "Initializing error", e);
    }
    File cssOutputFile = new File(filesDir, "style.css");
    FileUtils.copyFile(getInputFile(cssPath), cssOutputFile);

    // create headline picture
    File headlineOutputFile = new File(filesDir, "bg-headline.png"); //$NON-NLS-1$
    FileUtils.copyFile(getInputFile(headlinePath), headlineOutputFile);

    File linkOutputFile = new File(filesDir, "int_link.png"); //$NON-NLS-1$
    FileUtils.copyFile(getInputFile(linkPath), linkOutputFile);

    File tooltipIconFile = new File(filesDir, "tooltip.png"); //$NON-NLS-1$
    FileUtils.copyFile(getInputFile(tooltipIcon), tooltipIconFile);

    File htmlExportFile = new File(getTarget().getLocation().getPath());
    if (projectInfo != null) {
        Date date = new Date();
        DateFormat dfm = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT);

        // associate variables with information data
        String exportDate = dfm.format(date);
        context.put(EXPORT_DATE, exportDate);

        if (projectInfo.getCreated() != null) {
            String created = dfm.format(projectInfo.getCreated());
            context.put(CREATED_DATE, created);
        }

        context.put(PROJECT_INFO, projectInfo);
    }

    if (alignment != null) {
        Collection<TypeCellInfo> typeCellInfos = new ArrayList<TypeCellInfo>();
        Collection<? extends Cell> cells = alignment.getTypeCells();
        Iterator<? extends Cell> it = cells.iterator();
        while (it.hasNext()) {
            final Cell cell = it.next();
            // this is the collection of type cell info
            TypeCellInfo typeCellInfo = new TypeCellInfo(cell, alignment, cellIds, filesSubDir);
            typeCellInfos.add(typeCellInfo);
        }
        // put the full collection of type cell info to the context (for the
        // template)
        context.put(TYPE_CELL_INFOS, typeCellInfos);
        createImages(filesDir);
    }

    context.put(TOOLTIP, getParameter(TOOLTIP).as(boolean.class));

    Template template;
    try {
        template = velocityEngine.getTemplate(templateFile.getName(), "UTF-8");
    } catch (Exception e) {
        return reportError(reporter, "Could not load template", e);
    }

    FileWriter fileWriter = new FileWriter(htmlExportFile);
    template.merge(context, fileWriter);
    fileWriter.close();

    reporter.setSuccess(true);
    return reporter;
}

From source file:ch.unibas.charmmtools.gui.step1.mdAssistant.CHARMM_GUI_InputAssistant.java

private File convertWithBabel(File xyz) {
    String parent = FilenameUtils.getFullPath(xyz.getAbsolutePath());
    String basename = FilenameUtils.getBaseName(xyz.getAbsolutePath());

    File pdbOut = new File(parent + basename + ".pdb");

    BabelConverterAPI babelc = new BabelConverterAPI("xyz", "pdb");
    babelc.convert(xyz, pdbOut);//from w ww.  j av a2s. co  m

    if (pdbOut.exists()) {
        try {
            logger.info("Content of pdb file obtained from babel : \n"
                    + Files.readAllBytes(Paths.get(pdbOut.getAbsolutePath())));
        } catch (IOException ex) {
        }
    }

    return pdbOut;
}

From source file:de.uzk.hki.da.format.PublishImageConversionStrategy.java

/**
 *//*from ww  w .jav  a2s  .c o m*/
@Override
public List<Event> convertFile(ConversionInstruction ci) throws FileNotFoundException {
    if (cliConnector == null)
        throw new IllegalStateException("cliConnector not set");
    if (ci.getConversion_routine() == null)
        throw new IllegalStateException("conversionRoutine not set");
    if (ci.getConversion_routine().getTarget_suffix() == null
            || ci.getConversion_routine().getTarget_suffix().isEmpty())
        throw new IllegalStateException("target suffix in conversionRoutine not set");

    List<Event> results = new ArrayList<Event>();

    // connect dafile to package

    String input = ci.getSource_file().toRegularFile().getAbsolutePath();

    // Convert 
    ArrayList<String> commandAsList = null;
    for (String audience : audiences) {

        Path.makeFile(object.getDataPath(), pips, audience.toLowerCase(), ci.getTarget_folder()).mkdirs();

        commandAsList = new ArrayList<String>();
        commandAsList.add("convert");
        commandAsList.add(ci.getSource_file().toRegularFile().getAbsolutePath());
        logger.debug(commandAsList.toString());
        commandAsList = assembleResizeDimensionsCommand(commandAsList, audience);
        commandAsList = assembleWatermarkCommand(commandAsList, audience);
        commandAsList = assembleFooterTextCommand(commandAsList, audience,
                ci.getSource_file().toRegularFile().getAbsolutePath());

        DAFile target = new DAFile(pkg, pips + "/" + audience.toLowerCase(),
                Utilities.slashize(ci.getTarget_folder()) + FilenameUtils.getBaseName(input) + "."
                        + ci.getConversion_routine().getTarget_suffix());
        commandAsList.add(target.toRegularFile().getAbsolutePath());

        logger.debug(commandAsList.toString());
        String[] commandAsArray = new String[commandAsList.size()];
        commandAsArray = commandAsList.toArray(commandAsArray);
        if (!cliConnector.execute(commandAsArray))
            throw new RuntimeException("convert did not succeed: " + Arrays.toString(commandAsArray));

        // In order to support multipage tiffs, we check for files by wildcard expression
        String extension = FilenameUtils.getExtension(target.toRegularFile().getAbsolutePath());
        List<File> wild = findFilesWithRegex(
                new File(FilenameUtils.getFullPath(target.toRegularFile().getAbsolutePath())),
                Pattern.quote(FilenameUtils.getBaseName(target.getRelative_path())) + "-\\d+\\." + extension);
        if (!target.toRegularFile().exists() && !wild.isEmpty()) {
            for (File f : wild) {
                DAFile multipageTarget = new DAFile(pkg, pips + "/" + audience.toLowerCase(),
                        Utilities.slashize(ci.getTarget_folder()) + f.getName());

                Event e = new Event();
                e.setDetail(Utilities.createString(commandAsList));
                e.setSource_file(ci.getSource_file());
                e.setTarget_file(multipageTarget);
                e.setType("CONVERT");
                e.setDate(new Date());
                results.add(e);
            }
        } else {
            Event e = new Event();
            e.setDetail(Utilities.createString(commandAsList));
            e.setSource_file(ci.getSource_file());
            e.setTarget_file(target);
            e.setType("CONVERT");
            e.setDate(new Date());
            results.add(e);
        }
    }

    return results;
}

From source file:de.mpg.imeji.logic.storage.util.MediaUtils.java

/**
 * Remove the files created by imagemagick.
 * //from w  ww  .j  a  v  a 2  s  .c  om
 * @param path
 */
private static void removeFilesCreatedByImageMagick(String path) {
    int count = 0;
    String dir = FilenameUtils.getFullPath(path);
    String pathBase = FilenameUtils.getBaseName(path);
    File f = new File(dir + pathBase + "-" + count + ".jpg");
    while (f.exists()) {
        String newPath = f.getAbsolutePath().replace("-" + count, "-" + Integer.valueOf(count + 1));
        f.delete();
        f = new File(newPath);
        count++;
    }
}

From source file:com.seagate.kinetic.KineticTestSimulator.java

/**
 *
 * Create test simulator.// ww w  . ja  va 2s.  co m
 *
 * @param clearExistingDatabase
 *            If clear existing data, set true, if not, set false.
 * @param serverConfiguration
 *            Using different configuration to generate different simulator.
 *
 * @throws KineticException
 *             if any internal error occurred.
 * @throws IOException
 *             if any IO error occurred
 * @throws InterruptedException
 *             if any Interrupt error occurred
 *
 * @see SimulatorConfiguration
 */
public KineticTestSimulator(boolean clearExistingDatabase, SimulatorConfiguration serverConfiguration)
        throws IOException, InterruptedException, KineticException {
    javaServerConfiguration = serverConfiguration;

    String kineticPath = System.getProperty("KINETIC_PATH");
    String kineticHost = System.getProperty("KINETIC_HOST");

    int requestedPort = Integer.parseInt(System.getProperty("KINETIC_PORT", "8123"));

    if (!Boolean.parseBoolean(System.getProperty("RUN_AGAINST_EXTERNAL"))) {
        port = 8123;
        LOG.fine("Starting java simulator on port " + port);
        host = "localhost";
        serverConfiguration.setPort(port);

        if (clearExistingDatabase) {
            deleteJavaServerAuxilaryData();

            String defaultHome = System.getProperty("user.home") + File.separator + "leafcutter";

            String leafcutterHome = serverConfiguration.getProperty(SimulatorConfiguration.KINETIC_HOME,
                    defaultHome);

            FileUtils.deleteQuietly(new File(leafcutterHome));
        }

        // set nio services thread pool size
        serverConfiguration.setNioServiceBossThreads(1);
        serverConfiguration.setNioServiceWorkerThreads(1);

        kineticServer = new KineticSimulator(serverConfiguration);
        externalKineticServer = null;
    } else if (kineticPath != null) {
        port = requestedPort;
        LOG.fine("Running tests against external simulator at " + kineticPath + " using port " + port);
        host = "localhost";
        kineticServer = null;

        FinalizedProcessBuilder finalizedProcessBuilder = new FinalizedProcessBuilder("killall", "-9",
                "kineticd");
        finalizedProcessBuilder.start().waitFor(10 * 1000);
        Thread.sleep(500);

        // Since the cluster version is checked before performing an ISE we
        // need to manually remove
        // the file used to store the cluster version
        if (clearExistingDatabase) {
            final String workingDirectory = FilenameUtils.getFullPath(kineticPath);
            final String clusterStorePath = FilenameUtils.concat(workingDirectory, "cluster_version");
            FileUtils.deleteQuietly(new File(clusterStorePath));
        }

        finalizedProcessBuilder = new FinalizedProcessBuilder(kineticPath);
        finalizedProcessBuilder.directory(new File("."));
        finalizedProcessBuilder.gobbleStreamsWithLogging(true);

        externalKineticServer = finalizedProcessBuilder.start();
        waitForServerReady();
    } else {
        host = kineticHost;
        port = requestedPort;
        LOG.fine("Running tests against " + host + ":" + port);

        kineticServer = null;
        externalKineticServer = null;
    }

    if (clearExistingDatabase) {

        KineticClient kineticClient = buildClient();

        KineticMessage km = MessageFactory.createKineticMessageWithBuilder();
        Command.Builder commandBuillder = (Command.Builder) km.getCommand();

        commandBuillder.getBodyBuilder().getSetupBuilder();

        /**
         * XXX protocol-3.0.0
         */

        //com.seagate.kinetic.proto.Kinetic.Message.Builder builder = com.seagate.kinetic.proto.Kinetic.Message
        //      .newBuilder();
        //builder.getCommandBuilder().getBodyBuilder().getSetupBuilder()
        //.setInstantSecureErase(true);

        commandBuillder.getHeaderBuilder()
                .setMessageType(com.seagate.kinetic.proto.Kinetic.Command.MessageType.SETUP);

        kineticClient.request(km);
        kineticClient.close();
    }
}

From source file:MSUmpire.LCMSPeakStructure.LCMSPeakMS1.java

public String GetDefaultPepXML() {
    return FilenameUtils.separatorsToUnix(FilenameUtils.getFullPath(ScanCollectionName) + "interact-"
            + FilenameUtils.getBaseName(ScanCollectionName) + ".pep.xml");
}

From source file:edu.cornell.med.icb.goby.modes.SplitFastaMode.java

/**
 * Split a fasta / fastq file by (a) readlength and (b) the maximum number of
 * entries per file. This will output the files that are written to stdout
 * @throws IOException error reading / writing files.
 *///from ww w.  j a  v  a2s . c om
@Override
public void execute() throws IOException {
    final FastXReader reader = new FastXReader(inputFile);
    final Int2ObjectMap<PrintStream> outputMap = new Int2ObjectOpenHashMap<PrintStream>();
    final Int2IntMap entriesPerReadLen = new Int2IntOpenHashMap();
    final Int2IntMap filesPerReadLen = new Int2IntOpenHashMap();
    final List<String> removeExt = Arrays.asList("gz", "fa", "mpfa", "fna", "fsa", "fas", "fasta", "fq", "mpfq",
            "fnq", "fsq", "fas", "fastq");
    String inputName = FilenameUtils.getName(inputFile);
    while (true) {
        // Remove the unwanted extensions from the file name
        final String ext = FilenameUtils.getExtension(inputName);
        if (!removeExt.contains(ext)) {
            break;
        }
        inputName = FilenameUtils.getBaseName(inputName);
    }
    final String outputFilenameTemplate = FilenameUtils.getFullPath(inputFile) + inputName
            + "._READLENGTH_._PART_." + reader.getFileType();
    final NumberFormat nf3 = NumberFormat.getInstance();
    nf3.setMinimumIntegerDigits(3);
    final NumberFormat nf2 = NumberFormat.getInstance();
    nf2.setMinimumIntegerDigits(2);
    for (final FastXEntry entry : reader) {
        final int readLen = Math.min(fastxSplitMaxLength, roundReadLen(entry.getReadLength(), splitReadsMod));
        PrintStream out = outputMap.get(readLen);
        if (out == null) {
            filesPerReadLen.put(readLen, 1);
            entriesPerReadLen.put(readLen, 0);
            String outputFilename = outputFilenameTemplate.replaceAll("_READLENGTH_", nf3.format(readLen));
            outputFilename = outputFilename.replaceAll("_PART_", nf2.format(1));
            System.out.println(outputFilename);
            out = new PrintStream(new BufferedOutputStream(new FileOutputStream(outputFilename)));
            outputMap.put(readLen, out);
        }
        int numEntries = entriesPerReadLen.get(readLen);
        if (numEntries == maxReadsPerFile) {
            out.close();
            numEntries = 0;
            int numFiles = filesPerReadLen.get(readLen);
            numFiles++;
            filesPerReadLen.put(readLen, numFiles);
            String outputFilename = outputFilenameTemplate.replaceAll("_READLENGTH_", nf3.format(readLen));
            outputFilename = outputFilename.replaceAll("_PART_", nf2.format(numFiles));
            System.out.println(outputFilename);
            out = new PrintStream(new BufferedOutputStream(new FileOutputStream(outputFilename)));
            outputMap.put(readLen, out);
        }
        out.println(entry.getEntry());
        entriesPerReadLen.put(readLen, numEntries + 1);
    }
    for (final PrintStream out : outputMap.values()) {
        out.close();
    }
    outputMap.clear();
    reader.close();
}