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:edu.ur.ir.ir_export.service.DefaultCollectionExportService.java

/**
 * Export the specified institutional collection.
 * //from  w  w  w  . j av a 2  s. c  o  m
 * @param collection - collection to export
 * @param includeChildren - if true children should be exported
 * @param zipFileDestination - zip file destination to store the collection information
 * @throws IOException 
 */
public void export(InstitutionalCollection collection, boolean includeChildren, File zipFileDestination)
        throws IOException {

    // create the path if it doesn't exist
    String path = FilenameUtils.getPath(zipFileDestination.getCanonicalPath());
    if (!path.equals("")) {
        File pathOnly = new File(FilenameUtils.getFullPath(zipFileDestination.getCanonicalPath()));
        FileUtils.forceMkdir(pathOnly);
    }

    List<InstitutionalCollection> collections = new LinkedList<InstitutionalCollection>();
    collections.add(collection);
    File collectionXmlFile = temporaryFileCreator.createTemporaryFile(extension);
    Set<FileInfo> allPictures = createXmlFile(collectionXmlFile, collections, includeChildren);

    FileOutputStream out = new FileOutputStream(zipFileDestination);
    ArchiveOutputStream os = null;
    try {
        os = new ArchiveStreamFactory().createArchiveOutputStream("zip", out);
        os.putArchiveEntry(new ZipArchiveEntry("collection.xml"));

        FileInputStream fis = null;
        try {
            log.debug("adding xml file");
            fis = new FileInputStream(collectionXmlFile);
            IOUtils.copy(fis, os);
        } finally {
            if (fis != null) {
                fis.close();
                fis = null;
            }
        }

        log.debug("adding pictures size " + allPictures.size());
        for (FileInfo fileInfo : allPictures) {
            File f = new File(fileInfo.getFullPath());
            String name = FilenameUtils.getName(fileInfo.getFullPath());
            name = name + '.' + fileInfo.getExtension();
            log.debug(" adding name " + name);
            os.putArchiveEntry(new ZipArchiveEntry(name));
            try {
                log.debug("adding input stream");
                fis = new FileInputStream(f);
                IOUtils.copy(fis, os);
            } finally {
                if (fis != null) {
                    fis.close();
                    fis = null;
                }
            }
        }

        os.closeArchiveEntry();
        out.flush();
    } catch (ArchiveException e) {
        throw new IOException(e);
    } finally {
        if (os != null) {
            os.close();
            os = null;
        }
    }

    FileUtils.deleteQuietly(collectionXmlFile);

}

From source file:de.uzk.hki.da.grid.IrodsFederatedGridFacade.java

@Override
public boolean putToReplDir(File file, String address_dest, StoragePolicy sp, String checksum)
        throws IOException {
    IrodsCommandLineConnector iclc = new IrodsCommandLineConnector();
    String destCollection = FilenameUtils.getFullPath(address_dest);
    if (!iclc.exists(destCollection)) {
        logger.debug("creating Coll " + destCollection);
        iclc.mkCollection(destCollection);
    }/*from w w w . ja va 2  s . co m*/

    logger.debug("dest recource " + sp.getWorkingResource());

    if (iclc.put(file, address_dest, sp.getWorkingResource())) {
        logger.debug("set destination resource " + sp.getWorkingResource());
        String checksumAfterPut = iclc.getChecksum(address_dest);

        if (StringUtilities.isNotSet(checksumAfterPut)) {
            throw new IOException("iRODS found no checksum for " + address_dest);
        }

        if (!StringUtilities.isNotSet(checksum)) {
            if (!checksumAfterPut.equals(checksum)) {
                logger.error("Given Checksum of Package has to be " + checksum);
                logger.error("Checksum is " + checksumAfterPut);
                throw new IOException("Checksum not correct on put!");
            }
        }
        return true;
    } else {
        logger.debug("Unable to put the aip file to irods repl directory");
        return false;
    }
}

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

/**
 * Search for the first non blank image generated by imagemagick, based on commandline: convert image.jpg -shave
 * 1%x1% -resize 40% -fuzz 10% -trim +repage info: | grep ' 1x1 '
 * /*from  w  w w. j  a v  a  2 s.co m*/
 * @param path
 * @return
 * @throws IOException
 * @throws URISyntaxException
 * @throws InterruptedException
 * @throws IM4JavaException
 */
private static int getNonBlankFrame(String path)
        throws IOException, URISyntaxException, InterruptedException, IM4JavaException {
    ConvertCmd cmd = getConvert();
    int count = 0;
    String dir = FilenameUtils.getFullPath(path);
    String pathBase = FilenameUtils.getBaseName(path);
    File f = new File(dir + pathBase + "-" + count + ".jpg");
    while (f.exists()) {
        IMOperation op = new IMOperation();
        op.addImage();
        op.shave(1, 1, true);
        op.fuzz(10.0, true);
        op.trim();
        op.addImage();
        File trim = File.createTempFile("trim", ".jpg");
        try {
            cmd.run(op, f.getAbsolutePath(), trim.getAbsolutePath());
            Info info = new Info(trim.getAbsolutePath());
            if (!info.getImageGeometry().contains("1x1"))
                return count;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            String newPath = f.getAbsolutePath().replace("-" + count, "-" + Integer.valueOf(count + 1));
            f = new File(newPath);
            count++;
            trim.delete();
        }
    }
    return -1;
}

From source file:MSUmpire.BaseDataStructure.InstrumentParameter.java

public static InstrumentParameter ReadParametersSerialization(String filepath) {
    if (!new File(FilenameUtils.getFullPath(filepath) + FilenameUtils.getBaseName(filepath) + "_params.ser")
            .exists()) {//from   w  w w. j  a  va  2s  . c  o  m
        return null;
    }
    try {
        Logger.getRootLogger().info("Reading parameters from file:" + FilenameUtils.getFullPath(filepath)
                + FilenameUtils.getBaseName(filepath) + "_params.ser...");

        FileInputStream fileIn = new FileInputStream(
                FilenameUtils.getFullPath(filepath) + FilenameUtils.getBaseName(filepath) + "_params.ser");
        ObjectInputStream in = new ObjectInputStream(fileIn);
        InstrumentParameter params = (InstrumentParameter) in.readObject();
        in.close();
        fileIn.close();
        return params;

    } catch (Exception ex) {
        Logger.getRootLogger().error(ExceptionUtils.getStackTrace(ex));
        return null;
    }
}

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

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

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

    String input = ci.getSource_file().toRegularFile().getAbsolutePath();
    if (getEncoding(input).equals("None"))
        return resultEvents;

    // create subfolder if necessary
    Path.make(object.getPath("newest"), ci.getTarget_folder()).toFile().mkdirs();

    String[] commandAsArray = new String[] { "convert", "+compress", input, generateTargetFilePath(ci) };
    logger.info("Executing conversion command: {}", commandAsArray);
    ProcessInformation pi = CommandLineConnector.runCmdSynchronously(commandAsArray);
    if (pi.getExitValue() != 0) {
        logger.error(/*from   w w  w .ja va  2 s. c o  m*/
                this.getClass() + ": Recieved return code from terminal based command: " + pi.getExitValue());
        throw new RuntimeException("cli conversion failed!\n\nstdOut: ------ \n\n\n" + pi.getStdOut()
                + "\n\n ----- end of stdOut\n\nstdErr: ------ \n\n\n" + pi.getStdErr()
                + "\n\n ----- end of stdErr");
    }

    File result = new File(generateTargetFilePath(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(pkg, object.getPath("newest").getLastElement(),
                Utilities.slashize(ci.getTarget_folder()) + f.getName());
        logger.debug("new dafile:" + daf);

        Event e = new Event();
        e.setType("CONVERT");
        e.setDetail(Utilities.createString(commandAsArray));
        e.setSource_file(ci.getSource_file());
        e.setTarget_file(daf);
        e.setDate(new Date());

        resultEvents.add(e);
    }

    return resultEvents;
}

From source file:cross.io.InputDataFactory.java

/**
 * Create a collection of files from the given string resource paths.
 *
 * @param input the string resource paths
 * @return a collection of files// w  w w . ja  va 2  s . c om
 */
@Override
public Collection<File> getInputFiles(String[] input) {
    LinkedHashSet<File> files = new LinkedHashSet<>();
    for (String inputString : input) {
        log.debug("Processing input string {}", inputString);
        //separate wildcards from plain files
        String name = FilenameUtils.getName(inputString);
        boolean isWildcard = name.contains("?") || name.contains("*");
        String fullPath = FilenameUtils.getFullPath(inputString);
        File path = new File(fullPath);
        File baseDirFile = new File(this.basedir);
        if (!baseDirFile.exists()) {
            throw new ExitVmException("Input base directory '" + baseDirFile + "' does not exist!");
        }
        if (!baseDirFile.isDirectory()) {
            throw new ExitVmException("Input base directory '" + baseDirFile + "' is not a directory!");
        }
        log.debug("Path is absolute: {}", path.isAbsolute());
        //identify absolute and relative files
        if (!path.isAbsolute()) {
            log.info("Resolving relative file against basedir: {}", this.basedir);
            path = new File(this.basedir, fullPath);
        }
        //normalize filenames
        fullPath = FilenameUtils.normalize(path.getAbsolutePath());
        log.debug("After normalization: {}", fullPath);
        IOFileFilter dirFilter = this.recurse ? TrueFileFilter.INSTANCE : null;
        if (isWildcard) {
            log.debug("Using wildcard matcher for {}", name);
            files.addAll(FileUtils.listFiles(new File(fullPath),
                    new WildcardFileFilter(name, IOCase.INSENSITIVE), dirFilter));
        } else {
            log.debug("Using name for {}", name);
            File f = new File(fullPath, name);
            if (!f.exists()) {
                throw new ExitVmException("Input file '" + f + "' does not exist!");
            }
            files.add(f);
        }
    }
    return files;
}

From source file:de.uzk.hki.da.grid.IrodsGridFacadeBase.java

/**
 * Prepare replication.//  w w  w  . jav  a2 s.  c o  m
 *
 * @param file the file
 * @param relative_address_dest the relative_address_dest
 * @return true, if successful
 * @throws IOException Signals that an I/O exception has occurred.
 */
protected boolean PrepareReplication(File file, String relative_address_dest, StoragePolicy sp)
        throws IOException {

    if (sp.getGridCacheAreaRootPath() == null)
        throw new IOException("gridCacheAreaRootPath is not set");

    if (irodsSystemConnector.getDefaultStorage() == null)
        logger.error("Default Storage for node named " + sp.getNodeName() + " must be set!");
    if (irodsSystemConnector.getZone() == null)
        throw new IOException("MyZone is not set");
    if (!file.exists())
        throw new IOException("Not an existing File to put: " + file);

    String address_dest = relative_address_dest;
    if (!relative_address_dest.startsWith("/"))
        address_dest = "/" + relative_address_dest;
    String targetPhysically = sp.getGridCacheAreaRootPath() + "/" + WorkArea.AIP + address_dest;
    String targetAbsoluteLogicalPath = "/" + irodsSystemConnector.getZone() + "/" + WorkArea.AIP + address_dest;

    File gridfile = new File(targetPhysically);

    if (gridfile.exists()) {

        if (!replicatedOnlyToCache(targetAbsoluteLogicalPath))
            throw new java.io.IOException("Grid File " + gridfile + " " + targetAbsoluteLogicalPath
                    + " not exclusively or not only available on cache group devices!");

        if (MD5Checksum.getMD5checksumForLocalFile(file)
                .equals(MD5Checksum.getMD5checksumForLocalFile(gridfile))) {
            logger.info("GridFile is valid and only available on cache devices");
            return true;
        } else {
            logger.error("Leftovers or invalid file on the grid!");
            irodsSystemConnector.removeFile(targetAbsoluteLogicalPath);
            if (gridfile.exists())
                gridfile.delete();
        }
    }

    try {
        new File(FilenameUtils.getFullPath(targetPhysically)).mkdir();
        FileUtils.copyFile(file, gridfile);
    } catch (IOException e) {
        logger.error(
                "Error while creating File or directory physically on the GridCachePath, target file may already exist "
                        + e.getMessage());
        return false;
    }

    if (!MD5Checksum.getMD5checksumForLocalFile(file)
            .equals(MD5Checksum.getMD5checksumForLocalFile(gridfile))) {
        logger.error(" put of " + file + " failed");
        return false;
    }
    return true;
}

From source file:MSUmpire.LCMSPeakStructure.LCMSPeakDIAMS2.java

public LCMSPeakDIAMS2(String Filename, DIAPack parentDIA, InstrumentParameter parameter, XYData WindowMZ,
        XYData LastWindowMZ, SpectrumParserBase spectrumparser, int NoCPUs) {
    this.DIA_MZ_Range = WindowMZ;
    this.Last_MZ_Range = LastWindowMZ;
    this.WindowID = (int) Math.floor(WindowMZ.getX()) + "_" + (int) Math.floor(WindowMZ.getY());
    this.SpectrumParser = spectrumparser;
    this.ScanCollectionName = FilenameUtils.getFullPath(Filename) + "/" + FilenameUtils.getBaseName(Filename)
            + "_" + (int) Math.floor(WindowMZ.getX()) + "_" + (int) Math.floor(WindowMZ.getY());
    this.ParentmzXMLName = FilenameUtils.getFullPath(Filename) + "/" + FilenameUtils.getBaseName(Filename);
    this.parentDIA = parentDIA;
    this.parameter = parameter;
    this.MaxNoPeakCluster = parameter.MaxMS2NoPeakCluster;
    this.MinNoPeakCluster = parameter.MinMS2NoPeakCluster;
    this.StartCharge = parameter.MS2StartCharge;
    this.EndCharge = parameter.MS2EndCharge;
    this.MiniIntensity = parameter.MinMSMSIntensity;
    this.SNR = parameter.MS2SNThreshold;
    this.NoCPUs = NoCPUs;
}

From source file:com.nuvolect.securesuite.util.OmniUtil.java

/**
 * Return a unique file given the current file as a model.
 * Example if file exists: /Picture/mypic.jpg > /Picture/mypic~.jpg
 * @return//from  w  ww . j a va  2 s . c  o  m
 */
public static OmniFile makeUniqueName(OmniFile initialFile) {

    String path = initialFile.getPath();
    String basePath = FilenameUtils.getFullPath(path); // path without name
    String baseName = FilenameUtils.getBaseName(path); // name without extension
    String extension = FilenameUtils.getExtension(path); // extension
    String volumeId = initialFile.getVolumeId();
    String dot = ".";
    if (extension.isEmpty())
        dot = "";
    OmniFile file = initialFile;

    while (file.exists()) {

        //            LogUtil.log("File exists: "+file.getPath());
        baseName += "~";
        String fullPath = basePath + baseName + dot + extension;
        file = new OmniFile(volumeId, fullPath);
    }
    //        LogUtil.log("File unique: "+file.getPath());
    return file;
}

From source file:MSUmpire.DIA.RTMappingExtLib.java

private void GenerateRTMapPNG(XYSeriesCollection xySeriesCollection, XYSeries series, float R2)
        throws IOException {
    String pngfile = FilenameUtils.getFullPath(TargetLCMS.mzXMLFileName) + "/"
            + FilenameUtils.getBaseName(TargetLCMS.mzXMLFileName) + "_" + libManager.LibID + "_RTMap.png";
    FileWriter writer = new FileWriter(FilenameUtils.getFullPath(TargetLCMS.mzXMLFileName) + "/"
            + FilenameUtils.getBaseName(TargetLCMS.mzXMLFileName) + "_" + libManager.LibID + "_RTMap.txt");

    XYSeries smoothline = new XYSeries("RT fitting curve");
    for (XYZData data : regression.PredictYList) {
        smoothline.add(data.getX(), data.getY());
        writer.write(data.getX() + "\t" + data.getY() + "\n");
    }//from   ww  w.  j  a v  a 2 s .c o  m
    writer.close();
    xySeriesCollection.addSeries(smoothline);
    xySeriesCollection.addSeries(series);
    JFreeChart chart = ChartFactory.createScatterPlot("Retention time mapping: R2=" + R2,
            "Normalized RT (" + libManager.LibID + ")",
            "RT:" + FilenameUtils.getBaseName(TargetLCMS.mzXMLFileName), xySeriesCollection,
            PlotOrientation.VERTICAL, true, true, false);
    XYPlot xyPlot = (XYPlot) chart.getPlot();
    xyPlot.setDomainCrosshairVisible(true);
    xyPlot.setRangeCrosshairVisible(true);

    XYItemRenderer renderer = xyPlot.getRenderer();
    renderer.setSeriesPaint(1, Color.blue);
    renderer.setSeriesPaint(0, Color.BLACK);
    renderer.setSeriesShape(1, new Ellipse2D.Double(0, 0, 3, 3));
    renderer.setSeriesStroke(1, new BasicStroke(3.0f));
    renderer.setSeriesStroke(0, new BasicStroke(3.0f));
    xyPlot.setBackgroundPaint(Color.white);
    ChartUtilities.saveChartAsPNG(new File(pngfile), chart, 1000, 600);
}