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

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

Introduction

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

Prototype

public static String getBaseName(String filename) 

Source Link

Document

Gets the base name, minus the full path and extension, from a full filename.

Usage

From source file:fr.inria.soctrace.tools.importer.paraver.ParaverImporter.java

private String getNewTraceDBName(String traceFile) {
    String basename = FilenameUtils.getBaseName(traceFile);
    String extension = FilenameUtils.getExtension(traceFile);
    if (extension.equals(ParaverConstants.TRACE_EXT)) {
        basename = basename.replace(ParaverConstants.TRACE_EXT, "");
    }//from  w w  w  . j  av a  2  s.  c om
    return FramesocManager.getInstance().getTraceDBName(basename);
}

From source file:com.alibaba.otter.node.etl.common.pipe.impl.http.archive.ArchiveBean.java

/**
 * /*from  w  w w.j  a  v a 2s  .c o  m*/
 */
@SuppressWarnings("resource")
private boolean doPack(final File targetArchiveFile, List<FileData> fileDatas,
        final ArchiveRetriverCallback<FileData> callback) {
    // ?
    if (true == targetArchiveFile.exists() && false == NioUtils.delete(targetArchiveFile, 3)) {
        throw new ArchiveException(
                String.format("[%s] exist and delete failed", targetArchiveFile.getAbsolutePath()));
    }

    boolean exist = false;
    ZipOutputStream zipOut = null;
    Set<String> entryNames = new HashSet<String>();
    BlockingQueue<Future<ArchiveEntry>> queue = new LinkedBlockingQueue<Future<ArchiveEntry>>(); // ?
    ExecutorCompletionService completionService = new ExecutorCompletionService(executor, queue);

    final File targetDir = new File(targetArchiveFile.getParentFile(),
            FilenameUtils.getBaseName(targetArchiveFile.getPath()));
    try {
        // 
        FileUtils.forceMkdir(targetDir);

        zipOut = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(targetArchiveFile)));
        zipOut.setLevel(Deflater.BEST_SPEED);
        // ??
        for (final FileData fileData : fileDatas) {
            if (fileData.getEventType().isDelete()) {
                continue; // delete??
            }

            String namespace = fileData.getNameSpace();
            String path = fileData.getPath();
            boolean isLocal = StringUtils.isBlank(namespace);
            String entryName = null;
            if (true == isLocal) {
                entryName = FilenameUtils.getPath(path) + FilenameUtils.getName(path);
            } else {
                entryName = namespace + File.separator + path;
            }

            // ????
            if (entryNames.contains(entryName) == false) {
                entryNames.add(entryName);
            } else {
                continue;
            }

            final String name = entryName;
            if (true == isLocal && !useLocalFileMutliThread) {
                // ??
                queue.add(new DummyFuture(new ArchiveEntry(name, callback.retrive(fileData))));
            } else {
                completionService.submit(new Callable<ArchiveEntry>() {

                    public ArchiveEntry call() throws Exception {
                        // ??
                        InputStream input = null;
                        OutputStream output = null;
                        try {
                            input = callback.retrive(fileData);

                            if (input instanceof LazyFileInputStream) {
                                input = ((LazyFileInputStream) input).getInputSteam();// ?stream
                            }

                            if (input != null) {
                                File tmp = new File(targetDir, name);
                                NioUtils.create(tmp.getParentFile(), false, 3);// ?
                                output = new FileOutputStream(tmp);
                                NioUtils.copy(input, output);// ?
                                return new ArchiveEntry(name, new File(targetDir, name));
                            } else {
                                return new ArchiveEntry(name);
                            }
                        } finally {
                            IOUtils.closeQuietly(input);
                            IOUtils.closeQuietly(output);
                        }
                    }
                });
            }
        }

        for (int i = 0; i < entryNames.size(); i++) {
            // ?
            ArchiveEntry input = null;
            InputStream stream = null;
            try {
                input = queue.take().get();
                if (input == null) {
                    continue;
                }

                stream = input.getStream();
                if (stream == null) {
                    continue;
                }

                if (stream instanceof LazyFileInputStream) {
                    stream = ((LazyFileInputStream) stream).getInputSteam();// ?stream
                }

                exist = true;
                zipOut.putNextEntry(new ZipEntry(input.getName()));
                NioUtils.copy(stream, zipOut);// ?
                zipOut.closeEntry();
            } finally {
                IOUtils.closeQuietly(stream);
            }
        }

        if (exist) {
            zipOut.finish();
        }
    } catch (Exception e) {
        throw new ArchiveException(e);
    } finally {
        IOUtils.closeQuietly(zipOut);
        try {
            FileUtils.deleteDirectory(targetDir);// 
        } catch (IOException e) {
            // ignore
        }
    }

    return exist;
}

From source file:de.teamgrit.grit.checking.testing.JavaProjectTester.java

/**
 * Creates the qualified name form a source file.
 *
 * @param path//from w ww . java  2 s  .  co  m
 *            the path to the sourcefile
 * @return the qualified name
 * @throws IOException
 *             in case of io errors
 */
private String getQuallifiedNameFromSource(Path path) throws IOException {

    final String packageRegex = "package\\s[^,;]+;";
    LineIterator it;
    String result = "";
    it = FileUtils.lineIterator(path.toFile(), "UTF-8");

    while (it.hasNext()) {
        String line = it.nextLine();
        if (line.matches(packageRegex)) {
            result = line;
            // strip not needed elements
            result = result.substring(8, result.length() - 1);
            // append classname
            return result + "." + FilenameUtils.getBaseName(path.toString());
        }
    }
    return FilenameUtils.getBaseName(path.toString());
}

From source file:de.thischwa.pmcms.tool.file.FileTool.java

/**
 * Copies 'srcFile' to 'destDir'. If there is a file with the same name, 'srcFile' will be renamed. E.g.:<br>
 * <code><pre>//w  w w.  j  a  v  a 2 s  .c o  m
 * filename.ext -&gt; filename_1.ext
 * </pre></code>
 * The extension will be converted to lower case.
 * 
 * @param srcFile
 * @param destDir
 * @return the dest file.
 * @throws IOException
 */
public static File copyToDirectoryUnique(final File srcFile, final File destDir) throws IOException {
    String basename = FilenameUtils.getBaseName(srcFile.getAbsolutePath());
    String extension = StringUtils.lowerCase(FilenameUtils.getExtension(srcFile.getAbsolutePath()));
    File destFile = getUniqueFile(destDir, normalizeFileName(basename) + '.' + extension);
    FileUtils.copyFile(srcFile, destFile);
    return destFile;
}

From source file:com.cognifide.cq.cqsm.core.scripts.ScriptStorageImpl.java

private String generateFileName(String fileName, Node saveNode) throws RepositoryException {
    String baseName = FilenameUtils.getBaseName(fileName);
    int num = 1;/*w w w.  java 2  s.  c om*/
    do {
        fileName = baseName + ((num > 1) ? ("-" + num) : "") + Cqsm.FILE_EXT;
        num++;
    } while (saveNode.hasNode(fileName));

    return fileName;
}

From source file:ijfx.core.segmentation.MeasurementSegmentationTask.java

public void saveObjects(ProgressHandler handler, MeasurementSegmentationTask task) {

    if (destinationFolder == null) {
        return;/*from   ww  w  .  ja v  a2s  . c o  m*/
    }

    for (Explorable exp : getAsExplorable()) {

        exp.load();

        String filename = new StringBuilder(200).append(destinationFolder).append("")
                .append(FilenameUtils
                        .getBaseName(exp.getMetaDataSet().getStringValue(MetaData.FILE_NAME, "None")))
                .append("_pl")
                .append(exp.getMetaDataSet().getStringValue(MetaData.PLANE_NON_PLANAR_POSITION, "")).append("_")
                .append(exp.getMetaDataSet().getStringValue(MetaData.NAME, "noname")).append(".tif").toString();

        try {
            if (new File(filename).getParentFile().exists() == false) {
                new File(filename).getParentFile().mkdirs();
            }
            datasetIOService.save(exp.getDataset(), filename);
        } catch (IOException ex) {
            Logger.getLogger(MeasurementSegmentationTask.class.getName()).log(Level.SEVERE, null, ex);
        }

        exp.dispose();

    }

}

From source file:ch.entwine.weblounge.kernel.fop.FopEndpoint.java

/**
 * Downloads both XML and XSL document and transforms them to PDF.
 * //from w  ww. j  a  v  a2  s .  co  m
 * @param xmlURL
 *          the URL to the XML document
 * @param xslURL
 *          the URL to the XSL document
 * @return the generated PDF
 * @throws WebApplicationException
 *           if the XML document cannot be downloaded
 * @throws WebApplicationException
 *           if the XSL document cannot be downloaded
 * @throws WebApplicationException
 *           if the PDF creation fails
 */
@POST
@Path("/pdf")
public Response transformToPdf(@FormParam("xml") String xmlURL, @FormParam("xsl") String xslURL,
        @FormParam("parameters") String params) {

    // Make sure we have a service
    if (fopService == null)
        throw new WebApplicationException(Status.SERVICE_UNAVAILABLE);

    final Document xml;
    final Document xsl;

    // Load the xml document
    InputStream xmlInputStream = null;
    try {
        DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        xmlInputStream = new URL(xmlURL).openStream();
        xml = documentBuilder.parse(xmlInputStream);
    } catch (MalformedURLException e) {
        logger.warn("Error creating xml url from '{}'", xmlURL);
        throw new WebApplicationException(Status.BAD_REQUEST);
    } catch (IOException e) {
        logger.warn("Error accessing xml document at '{}': {}", xmlURL, e.getMessage());
        throw new WebApplicationException(Status.NOT_FOUND);
    } catch (ParserConfigurationException e) {
        logger.warn("Error setting up xml parser: {}", e.getMessage());
        throw new WebApplicationException(Status.BAD_REQUEST);
    } catch (SAXException e) {
        logger.warn("Error parsing xml document from {}: {}", xmlURL, e.getMessage());
        throw new WebApplicationException(Status.BAD_REQUEST);
    } finally {
        IOUtils.closeQuietly(xmlInputStream);
    }

    // Load the XLST stylesheet
    InputStream xslInputStream = null;
    try {
        DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        xslInputStream = new URL(xslURL).openStream();
        xsl = documentBuilder.parse(xslInputStream);
    } catch (MalformedURLException e) {
        logger.warn("Error creating xsl url from '{}'", xslURL);
        throw new WebApplicationException(Status.BAD_REQUEST);
    } catch (IOException e) {
        logger.warn("Error accessing xsl stylesheet at '{}': {}", xslURL, e.getMessage());
        throw new WebApplicationException(Status.NOT_FOUND);
    } catch (ParserConfigurationException e) {
        logger.warn("Error setting up xml parser: {}", e.getMessage());
        throw new WebApplicationException(Status.BAD_REQUEST);
    } catch (SAXException e) {
        logger.warn("Error parsing xml document from {}: {}", xslURL, e.getMessage());
        throw new WebApplicationException(Status.BAD_REQUEST);
    } finally {
        IOUtils.closeQuietly(xslInputStream);
    }

    // Create the filename
    String name = FilenameUtils.getBaseName(xmlURL) + ".pdf";

    // Process the parameters
    final List<String[]> parameters = new ArrayList<String[]>();
    if (StringUtils.isNotBlank(params)) {
        for (String param : StringUtils.split(params, ";")) {
            String[] parameterValue = StringUtils.split(param, "=");
            if (parameterValue.length != 2) {
                logger.warn("Parameter for PDF generation is malformed: {}", param);
                throw new WebApplicationException(Status.BAD_REQUEST);
            }
            parameters.add(
                    new String[] { StringUtils.trim(parameterValue[0]), StringUtils.trim(parameterValue[1]) });
        }
    }

    // Write the file contents back
    ResponseBuilder response = Response.ok(new StreamingOutput() {
        public void write(OutputStream os) throws IOException, WebApplicationException {
            try {
                fopService.xml2pdf(xml, xsl, parameters.toArray(new String[parameters.size()][2]), os);
            } catch (IOException e) {
                Throwable cause = e.getCause();
                if (cause == null || !"Broken pipe".equals(cause.getMessage()))
                    logger.warn("Error writing file contents to response", e);
            } catch (TransformerConfigurationException e) {
                logger.error("Error setting up the XSL transfomer: {}", e.getMessage());
                throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR);
            } catch (FOPException e) {
                logger.error("Error creating PDF document: {}", e.getMessage());
                throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR);
            } catch (TransformerException e) {
                logger.error("Error transforming to PDF: {}", e.getMessage());
                throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR);
            } finally {
                IOUtils.closeQuietly(os);
            }
        }
    });

    // Set response information
    response.type("application/pdf");
    response.header("Content-Disposition", "inline; filename=" + name);
    response.lastModified(new Date());

    return response.build();
}

From source file:au.com.permeance.liferay.portlet.documentlibrary.action.DownloadFolderZipAction.java

protected void sendZipFile(ResourceRequest resourceRequest, ResourceResponse resourceResponse, File zipFile,
        String zipFileName) throws Exception {

    FileInputStream zipFileInputStream = null;

    try {//from w ww  .  j  av a2s.co  m

        if (StringUtils.isEmpty(zipFileName)) {
            zipFileName = FilenameUtils.getBaseName(zipFile.getName());
        }

        String zipFileMimeType = MimeTypesUtil.getContentType(zipFileName);
        resourceResponse.setContentType(zipFileMimeType);

        int folderDownloadCacheMaxAge = DownloadFolderZipPropsValues.DL_FOLDER_DOWNLOAD_CACHE_MAX_AGE;
        if (folderDownloadCacheMaxAge > 0) {
            String cacheControlValue = "max-age=" + folderDownloadCacheMaxAge + ", must-revalidate";
            resourceResponse.addProperty(HttpHeaders.CACHE_CONTROL, cacheControlValue);
        }

        String contentDispositionValue = "attachment; filename=\"" + zipFileName + "\"";
        resourceResponse.addProperty(HttpHeaders.CONTENT_DISPOSITION, contentDispositionValue);

        // NOTE: java.io.File may return a length of 0 (zero) for a valid file
        // @see java.io.File#length()
        long zipFileLength = zipFile.length();
        if ((zipFileLength > 0L) && (zipFileLength < (long) Integer.MAX_VALUE)) {
            resourceResponse.setContentLength((int) zipFileLength);
        }

        zipFileInputStream = new FileInputStream(zipFile);
        OutputStream responseOutputStream = resourceResponse.getPortletOutputStream();
        long responseByteCount = IOUtils.copy(zipFileInputStream, responseOutputStream);
        responseOutputStream.flush();
        responseOutputStream.close();
        zipFileInputStream.close();
        zipFileInputStream = null;

        if (s_log.isDebugEnabled()) {
            s_log.debug("sent " + responseByteCount + " byte(s) for ZIP file " + zipFileName);
        }

    } catch (Exception e) {

        String name = StringPool.BLANK;
        if (zipFile != null) {
            name = zipFile.getName();
        }

        String msg = "Error sending ZIP file " + name + " : " + e.getMessage();
        s_log.error(msg);
        throw new PortalException(msg, e);

    } finally {

        if (zipFileInputStream != null) {
            try {
                zipFileInputStream.close();
                zipFileInputStream = null;
            } catch (Exception e) {
                String msg = "Error closing ZIP input stream : " + e.getMessage();
                s_log.error(msg);
            }
        }

    }
}

From source file:net.mitnet.tools.pdf.book.openoffice.converter.OpenOfficeDocConverter.java

public void convertDocuments(File sourceDir, List<File> sourceFileList, File outputDir, String outputFormat)
        throws Exception {

    if (isVerboseEnabled()) {
        if (sourceFileList != null) {
            System.out//from  ww w.jav a2 s .c o m
                    .println("Converting " + sourceFileList.size() + " documents to " + outputFormat + " ...");
        }
    }

    if (isDebugEnabled()) {
        verbose("sourceDir: " + sourceDir);
        verbose("sourceFileList: " + sourceFileList);
        verbose("outputDir: " + outputDir);
        verbose("outputFormat: " + outputFormat);
        verbose("converting " + sourceFileList.size() + " document(s)");
        verbose("output dir is " + outputDir);
        verbose("output format is " + outputFormat);
        verbose("connecting to OpenOffice server " + this.serverContext);
    }

    OfficeManager officeManager = buildOfficeManager(serverContext);
    officeManager.start();

    try {
        OfficeDocumentConverter converter = new OfficeDocumentConverter(officeManager);
        if (isDebugEnabled()) {
            verbose("converter is " + converter);
        }

        int currentItemIndex = 0;
        int maxItemIndex = sourceFileList.size();
        for (File inputFile : sourceFileList) {
            currentItemIndex++;
            if (inputFile.isFile()) {
                String baseOutputFilePath = null;
                if (outputDir == null) {
                    baseOutputFilePath = inputFile.getParent();
                } else {
                    String pathToParent = FileHelper.getPathToParent(sourceDir, inputFile);
                    if (StringUtils.isEmpty(pathToParent)) {
                        baseOutputFilePath = outputDir.getAbsolutePath();
                    } else {
                        baseOutputFilePath = new File(outputDir, pathToParent).getPath();
                    }
                }
                String baseInputFileName = FilenameUtils.getBaseName(inputFile.getName());
                String outputFileName = baseInputFileName + "." + outputFormat;
                File outputFile = new File(baseOutputFilePath, outputFileName);
                convertDocument(converter, inputFile, outputFile);
                if (getProgressMonitor() != null) {
                    int progressPercentage = MathHelper.calculatePercentage(currentItemIndex, maxItemIndex);
                    getProgressMonitor().setProgressPercentage(progressPercentage);
                }
            }
        }

    } finally {
        if (isDebugEnabled()) {
            verbose("disconnecting");
        }
        officeManager.stop();
    }
}

From source file:it.geosolutions.geobatch.imagemosaic.ImageMosaicUpdater.java

private static boolean setFeature(File baseDir, File granule, SimpleFeature feature, String geometryName,
        String locationKey) {/*from   www. j a va 2  s .c o m*/

    String granuleBaseName = FilenameUtils.getBaseName(granule.getAbsolutePath());

    // get attributes and copy them over
    try {
        AbstractGridFormat format = (AbstractGridFormat) GridFormatFinder.findFormat(granule);
        if (format == null || (format instanceof UnknownFormat)) {
            throw new IllegalArgumentException(
                    "Unable to find a reader for the provided file: " + granule.getAbsolutePath());
        }
        // can throw UnsupportedOperationsException
        final AbstractGridCoverage2DReader reader = (AbstractGridCoverage2DReader) format.getReader(granule,
                new Hints(Hints.FORCE_LONGITUDE_FIRST_AXIS_ORDER, Boolean.TRUE));

        GeneralEnvelope originalEnvelope = reader.getOriginalEnvelope();

        ReferencedEnvelope bb = new ReferencedEnvelope(originalEnvelope);

        WKTReader wktReader = new WKTReader();
        Geometry the_geom = wktReader.read("POLYGON((" + bb.getMinX() + " " + bb.getMinY() + "," + bb.getMinX()
                + " " + bb.getMaxY() + "," + bb.getMaxX() + " " + bb.getMaxY() + "," + bb.getMaxX() + " "
                + bb.getMinY() + "," + bb.getMinX() + " " + bb.getMinY() + "))");

        Integer SRID = CRS.lookupEpsgCode(bb.getCoordinateReferenceSystem(), true);
        /*
         * TODO ETJ suggestion: String crsId =
         * CRS.lookupIdentifier(bb.getCoordinateReferenceSystem(), true);
         */
        if (SRID == null) {
            throw new IllegalArgumentException("Unable to get the EPSG code for the granule: " + granule);
        }
        the_geom.setSRID(SRID);

        feature.setAttribute(geometryName, the_geom);
        // TODO absolute
        feature.setAttribute(locationKey, granule.getName());
        // granule.getName().replaceAll("\\", "\\\\"));

        final File indexer = new File(baseDir, org.geotools.gce.imagemosaic.Utils.INDEXER_PROPERTIES);
        final Properties indexerProps = ImageMosaicProperties.getPropertyFile(indexer);

        /**
         * @see {@link #org.geotools.gce.imagemosaic.properties.RegExPropertiesCollector.collect(File)}
         */
        final String granuleName = FilenameUtils.getBaseName(granule.getName());

        if (indexerProps.getProperty("TimeAttribute") != null) {

            // Since timeattrib may be ranged, we may have 2 attribs to update
            String timePropNames[] = indexerProps.getProperty("TimeAttribute").split(";");

            for (String timePropName : timePropNames) {
                updateFeatureTimeAttrib(feature, baseDir, timePropName, indexerProps, granuleName);
            }
        }

        // TODO TODO TODO TODO TODO TODO TODO TODO TODO TODO TODO TODO TODO
        // TODO: the time attribute handling has been refact'ed in order to use proper regex files
        // and to support ranges.
        // Same should be done for Elevation, Runtime(?) and AdditionalDomain attributes.
        // Furthermore, proper SPI should be used for parsing.
        // All of this should be handled if possibile using GT libs, and not reimplementing
        // the parsing from scratch.
        // TODO TODO TODO TODO TODO TODO TODO TODO TODO TODO TODO TODO TODO

        if (indexerProps.getProperty("ElevationAttribute") != null) {
            // TODO move out of the cycle
            final File elevationRegex = new File(baseDir, "elevationregex.properties");
            final Properties elevProps = ImageMosaicProperties.getPropertyFile(elevationRegex);
            final Pattern elevPattern = Pattern.compile(elevProps.getProperty("regex"));
            // TODO move out of the cycle
            final Matcher matcher = elevPattern.matcher(granuleName);
            if (matcher.find()) {
                feature.setAttribute(indexerProps.getProperty("ElevationAttribute"),
                        Double.valueOf(matcher.group()));
            }
        }

        if (indexerProps.getProperty("RuntimeAttribute") != null) {
            // TODO move out of the cycle
            final File runtimeRegex = new File(baseDir, "runtimeregex.properties");
            final Properties runtimeProps = ImageMosaicProperties.getPropertyFile(runtimeRegex);
            final Pattern runtimePattern = Pattern.compile(runtimeProps.getProperty("regex"));
            // TODO move out of the cycle
            final Matcher matcher = runtimePattern.matcher(granuleName);
            if (matcher.find()) {
                feature.setAttribute(indexerProps.getProperty("RuntimeAttribute"),
                        Integer.valueOf(matcher.group()));
            }
        }

        return true;

    } catch (Throwable e) {
        if (LOGGER.isErrorEnabled())
            LOGGER.error(e.getLocalizedMessage(), e);
        return false;
    }

}