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

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

Introduction

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

Prototype

public static String getName(String filename) 

Source Link

Document

Gets the name minus the path from a full filename.

Usage

From source file:net.grinder.util.AbstractGrinderClassPathProcessor.java

/**
 * Construct the classpath of ngrinder which is very important and located in the head of
 * classpath.// w w  w. j  a v a  2 s  .c  o  m
 *
 * @param classPath classpath string
 * @param logger    logger
 * @return classpath optimized for grinder.
 */
public String filterPatchClassPath(String classPath, Logger logger) {
    List<String> classPathList = new ArrayList<String>();
    for (String eachClassPath : checkNotNull(classPath).split(File.pathSeparator)) {
        String filename = FilenameUtils.getName(eachClassPath);
        if (isPatchJar(filename)) {
            logger.trace("classpath :" + eachClassPath);
            classPathList.add(eachClassPath);
        }
    }
    return StringUtils.join(classPathList, File.pathSeparator);
}

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

@Override
public void execute() throws IOException {
    final PrintWriter out = outputFilename == null ? new PrintWriter(System.out)
            : new PrintWriter(outputFilename);
    try {/*from w  w  w . j  av a 2 s  .  com*/
        int index = 0;
        out.print("trackName\t");
        for (String attributeName : attributeNames) {
            if (!"ignore".equals(attributeName)) {
                out.print(attributeName);

                if (index != attributeNames.length) {
                    out.print('\t');
                }
            }
            index++;
        }
        out.println();
        for (String file : filenames) {
            final String file1 = file;
            String name = FilenameUtils.getName(file1);
            String filename = FilenameUtils.getBaseName(name);
            String[] tokens = filename.split(delimiter);
            out.printf("%s\t", adjustSuffix(name));
            for (int i = 0; i < attributeNames.length; i++) {
                if (!"ignore".equals(attributeNames[i])) {
                    if (tokens.length <= i) {
                        continue;
                    }
                    out.print(tokens[i]);
                    if (i != attributeNames.length) {
                        out.print('\t');
                    }
                }

            }
            out.println();
        }
        out.flush();
    } finally {
        out.close();

    }
}

From source file:com.uber.jenkins.phabricator.coverage.CoberturaXMLParser.java

private Map<String, List<Integer>> parse(Map<NodeList, List<String>> coverageData) {
    Map<String, SortedMap<Integer, Integer>> internalCounts = new HashMap<String, SortedMap<Integer, Integer>>();

    // Each entry in the map is an XML list of classes (files) mapped to its possible source roots
    for (Map.Entry<NodeList, List<String>> entry : coverageData.entrySet()) {
        NodeList classes = entry.getKey();
        List<String> sourceDirs = entry.getValue();

        // Loop over all files in the coverage report
        for (int i = 0; i < classes.getLength(); i++) {
            Node classNode = classes.item(i);
            String fileName = classNode.getAttributes().getNamedItem(NODE_FILENAME).getTextContent();

            if (includeFileNames != null && !includeFileNames.contains(FilenameUtils.getName(fileName))) {
                continue;
            }/*from ww w  . j  a  v  a2  s . c  o  m*/

            // Make a guess on which of the `sourceDirs` contains the file in question
            String detectedSourceRoot = new PathResolver(workspace, sourceDirs).choose(fileName);
            fileName = join(detectedSourceRoot, fileName);

            SortedMap<Integer, Integer> hitCounts = internalCounts.get(fileName);
            if (hitCounts == null) {
                hitCounts = new TreeMap<Integer, Integer>();
            }

            NodeList children = classNode.getChildNodes();
            for (int j = 0; j < children.getLength(); j++) {
                Node child = children.item(j);

                if (NODE_NAME_LINES.equals(child.getNodeName())) {
                    NodeList lines = child.getChildNodes();
                    for (int k = 0; k < lines.getLength(); k++) {
                        Node line = lines.item(k);
                        if (!NODE_NAME_LINE.equals(line.getNodeName())) {
                            continue;
                        }

                        Integer lineNumber = getIntValue(line, NODE_NUMBER);
                        int existingHits = hitCounts.containsKey(lineNumber) ? hitCounts.get(lineNumber) : 0;
                        hitCounts.put(lineNumber, Math.max(existingHits, getIntValue(line, NODE_HITS)));
                    }
                    internalCounts.put(fileName, hitCounts);
                }
            }
        }

    }
    return computeLineCoverage(internalCounts);
}

From source file:egovframework.com.utl.wed.filter.CkImageSaver.java

public void saveAndReturnUrlToClient(HttpServletRequest request, HttpServletResponse response)
        throws IOException {
    // Parse the request
    try {/*from w  ww.  ja v  a 2s .  c  om*/
        FileItemFactory factory = new DiskFileItemFactory();

        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);

        List<FileItem> /* FileItem */ items = upload.parseRequest(request);
        // We upload just one file at the same time
        FileItem uplFile = items.get(0);

        String errorMessage = null;
        String relUrl = null;

        if (isAllowFileType(FilenameUtils.getName(uplFile.getName()))) {
            relUrl = fileSaveManager.saveFile(uplFile, imageBaseDir, imageDomain);

        } else {
            errorMessage = "Restricted Image Format";
        }

        StringBuffer sb = new StringBuffer();
        sb.append("<script type=\"text/javascript\">\n");
        // Compressed version of the document.domain automatic fix script.
        // The original script can be found at [fckeditor_dir]/_dev/domain_fix_template.js
        // sb.append("(function(){var d=document.domain;while (true){try{var A=window.parent.document.domain;break;}catch(e) {};d=d.replace(/.*?(?:\\.|$)/,'');if (d.length==0) break;try{document.domain=d;}catch (e){break;}}})();\n");
        sb.append("window.parent.CKEDITOR.tools.callFunction(").append(request.getParameter(FUNC_NO))
                .append(", '");
        sb.append(relUrl);
        if (errorMessage != null) {
            sb.append("', '").append(errorMessage);
        }
        sb.append("');\n </script>");

        response.setContentType("text/html");
        response.setHeader("Cache-Control", "no-cache");
        PrintWriter out = response.getWriter();

        out.print(sb.toString());
        out.flush();
        out.close();

    } catch (FileUploadException e) {
        log.error(e);
    }
}

From source file:edu.usc.pgroup.floe.client.FloeClient.java

/**
 * Uploads the file to the coordinator./*from w  w w .  j  a  va  2 s .c  o  m*/
 * The file is uploaded relative to the coordinator's scratch folder.
 *
 * @param fileName name of the file to be stored on the coordinator.
 * @return the base fileName which may be used for downloading the file
 * later.
 */
public final String uploadFileSync(final String fileName) {
    String baseFile = FilenameUtils.getName(fileName);
    try {
        int fid = getClient().beginFileUpload(baseFile);
        ReadableByteChannel inChannel = Channels.newChannel(new FileInputStream(fileName));
        ByteBuffer buffer = ByteBuffer.allocate(Utils.Constants.BUFFER_SIZE);
        while (inChannel.read(buffer) > 0) {
            buffer.flip();
            getClient().uploadChunk(fid, buffer);
            buffer.clear();
        }
        inChannel.close();
        getClient().finishUpload(fid);
    } catch (TException e) {
        LOGGER.error(e.getMessage());
        throw new RuntimeException(e);
    } catch (FileNotFoundException e) {
        LOGGER.error(e.getMessage());
        throw new RuntimeException(e);
    } catch (IOException e) {
        LOGGER.error(e.getMessage());
        throw new RuntimeException(e);
    }
    return baseFile;
}

From source file:it.geosolutions.geofence.gui.server.UploadServlet.java

@SuppressWarnings("unchecked")
@Override/* ww  w. j  ava2 s. c o m*/
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    // process only multipart requests
    if (ServletFileUpload.isMultipartContent(req)) {

        // Create a factory for disk-based file items
        FileItemFactory factory = new DiskFileItemFactory();

        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);

        File uploadedFile = null;
        // Parse the request
        try {
            List<FileItem> items = upload.parseRequest(req);

            for (FileItem item : items) {
                // process only file upload - discard other form item types
                if (item.isFormField()) {
                    continue;
                }

                String fileName = item.getName();
                // get only the file name not whole path
                if (fileName != null) {
                    fileName = FilenameUtils.getName(fileName);
                }

                uploadedFile = File.createTempFile(fileName, "");
                // if (uploadedFile.createNewFile()) {
                item.write(uploadedFile);
                resp.setStatus(HttpServletResponse.SC_CREATED);
                resp.flushBuffer();

                // uploadedFile.delete();
                // } else
                // throw new IOException(
                // "The file already exists in repository.");
            }
        } catch (Exception e) {
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    "An error occurred while creating the file : " + e.getMessage());
        }

        try {
            String wkt = calculateWKT(uploadedFile);
            resp.getWriter().print(wkt);
        } catch (Exception exc) {
            resp.getWriter().print("Error : " + exc.getMessage());
            logger.error("ERROR ********** " + exc);
        }

        uploadedFile.delete();

    } else {
        resp.sendError(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE,
                "Request contents type is not supported by the servlet.");
    }
}

From source file:com.haulmont.cuba.core.sys.LogControlImpl.java

@Override
public File getLogFile(String fileName) throws LogFileNotFoundException {
    File logFile = new File(logDir, FilenameUtils.getName(fileName));
    if (!logFile.exists())
        throw new LogFileNotFoundException(fileName);

    return logFile;
}

From source file:edu.umn.msi.tropix.genomics.bowtie.impl.BowtieJobProcessorImpl.java

private String writeIndex() {
    final File tempIndexZipFile = FILE_UTILS.createTempFile("tpxtmp", ".zip");
    final List<String> names = Lists.newArrayListWithCapacity(6);
    try {//from w  w w.j a  va  2  s  . co  m
        indexInputContext.get(tempIndexZipFile);
        ZIP_UTILS.unzipToContexts(tempIndexZipFile, new Function<String, OutputContext>() {
            public OutputContext apply(final String entryName) {
                // Flatten the name so the final resides in the base directory
                final String filename = FilenameUtils.getName(entryName);

                Preconditions.checkState(EBWT_NAME_PATTERN.matcher(filename).matches());
                // Record this filename
                names.add(filename);

                // Get and return outputcontext for that name
                final OutputContext outputContext = getStagingDirectory().getOutputContext(filename);
                return outputContext;
            }
        });
        Preconditions.checkState(names.size() == 6);
        final Matcher nameMatcher = EBWT_NAME_PATTERN.matcher(names.get(0));
        nameMatcher.matches();
        return nameMatcher.group(1);
    } finally {
        FILE_UTILS.deleteQuietly(tempIndexZipFile);
    }
}

From source file:com.cubusmail.gwtui.server.services.AttachmentUploadServlet.java

/**
 * Create a MimeBodyPart./*from   ww  w . j av  a  2 s  . co m*/
 * 
 * @param item
 * @return
 * @throws MessagingException
 * @throws IOException
 */
private DataSource createDataSource(FileItemStream item) throws MessagingException, IOException {

    final String fileName = FilenameUtils.getName(item.getName());
    final String contentType = item.getContentType();
    final InputStream stream = item.openStream();

    ByteArrayDataSource source = new ByteArrayDataSource(stream, contentType);
    source.setName(fileName);

    return source;
}

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

/**
 * using ImageMosaic reader extract needed data from the mosaic
 *//*from  w w  w. j a va 2  s .co m*/
private static boolean setReaderData(final File directory, final Map<String, Object> map) throws IOException {
    AbstractGridCoverage2DReader reader = null;

    final String absolutePath = directory.getAbsolutePath();
    final String inputFileName = FilenameUtils.getName(absolutePath);
    try {

        // /////////////////////////////////////////////////////////////////////
        //
        // ACQUIRING A READER
        //
        // /////////////////////////////////////////////////////////////////////
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Acquiring a reader for the provided directory...");
        }

        // ETj 20120824: ImageMosaicFormat.accepts() returns false when passing a dir,
        // but the getReader will work anyway.
        // Commenting out this check will make the action work properly.
        // Pls recheck.

        //            if (!IMAGEMOSAIC_FORMAT.accepts(directory)) {
        //                final String message = "IMAGEMOSAIC_FORMAT do not accept the directory: "
        //                        + directory.getAbsolutePath();
        //                final IOException ioe = new IOException(message);
        //                if (LOGGER.isErrorEnabled())
        //                    LOGGER.error(message, ioe);
        //                throw ioe;
        //            }
        reader = (AbstractGridCoverage2DReader) IMAGEMOSAIC_FORMAT.getReader(directory,
                new Hints(Hints.FORCE_LONGITUDE_FIRST_AXIS_ORDER, Boolean.TRUE));
        if (reader == null) {
            final String message = "Unable to find a reader for the provided file: " + inputFileName;
            final IOException ioe = new IOException(message);
            if (LOGGER.isErrorEnabled())
                LOGGER.error(message, ioe);
            throw ioe;
        }

        // HAS_TIME_DOMAIN this is a boolean String with values true|false. Meaning is obvious.
        // TIME_DOMAIN this returns a String that is a comma separated list of time values in
        // ZULU time using the ISO 8601 format (yyyy-MM-dd'T'HH:mm:ss.SSS)
        if ("true".equals(reader.getMetadataValue(AbstractGridCoverage2DReader.HAS_TIME_DOMAIN))) {
            map.put(AbstractGridCoverage2DReader.HAS_TIME_DOMAIN, Boolean.TRUE);
            final String times = reader.getMetadataValue(AbstractGridCoverage2DReader.TIME_DOMAIN);
            final Set<String> timesList = new TreeSet<String>();
            for (String time : times.split(",")) {
                timesList.add(time);
            }
            //                Collections.sort(timesList);
            map.put(AbstractGridCoverage2DReader.TIME_DOMAIN, timesList);
        } else {
            map.put(AbstractGridCoverage2DReader.HAS_TIME_DOMAIN, Boolean.FALSE);
        }

        // ELEVATION
        if ("true".equals(reader.getMetadataValue(AbstractGridCoverage2DReader.HAS_ELEVATION_DOMAIN))) {
            map.put(AbstractGridCoverage2DReader.HAS_ELEVATION_DOMAIN, Boolean.TRUE);
            final String elevations = reader.getMetadataValue(AbstractGridCoverage2DReader.ELEVATION_DOMAIN);
            final Set<String> elevList = new TreeSet<String>();
            for (String time : elevations.split(",")) {
                elevList.add(time);
            }
            map.put(AbstractGridCoverage2DReader.ELEVATION_DOMAIN, elevList);
        } else {
            map.put(AbstractGridCoverage2DReader.HAS_ELEVATION_DOMAIN, Boolean.FALSE);
        }

        final GeneralEnvelope originalEnvelope = reader.getOriginalEnvelope();
        // Setting BoundingBox
        DirectPosition position = originalEnvelope.getLowerCorner();
        double[] lowerCorner = position.getCoordinate();
        map.put(NATIVE_LOWER_CORNER_FIRST_KEY, (Double) lowerCorner[0]);
        map.put(NATIVE_LOWER_CORNER_SECOND_KEY, (Double) lowerCorner[1]);
        position = originalEnvelope.getUpperCorner();
        double[] upperCorner = position.getCoordinate();
        map.put(NATIVE_UPPER_CORNER_FIRST_KEY, (Double) upperCorner[0]);
        map.put(NATIVE_UPPER_CORNER_SECOND_KEY, (Double) upperCorner[1]);

        // Setting crs
        map.put(CRS_KEY, reader.getCrs());

        // computing lon/lat bbox
        final CoordinateReferenceSystem wgs84;
        try {
            wgs84 = CRS.decode("EPSG:4326", true);
            final GeneralEnvelope lonLatBBOX = (GeneralEnvelope) CRS.transform(originalEnvelope, wgs84);
            // Setting BoundingBox
            position = lonLatBBOX.getLowerCorner();
            lowerCorner = position.getCoordinate();
            map.put(LONLAT_LOWER_CORNER_FIRST_KEY, (Double) lowerCorner[0]);
            map.put(LONLAT_LOWER_CORNER_SECOND_KEY, (Double) lowerCorner[1]);
            position = lonLatBBOX.getUpperCorner();
            upperCorner = position.getCoordinate();
            map.put(LONLAT_UPPER_CORNER_FIRST_KEY, (Double) upperCorner[0]);
            map.put(LONLAT_UPPER_CORNER_SECOND_KEY, (Double) upperCorner[1]);
        } catch (NoSuchAuthorityCodeException e) {
            if (LOGGER.isWarnEnabled())
                LOGGER.warn(e.getLocalizedMessage(), e);
        } catch (FactoryException e) {
            if (LOGGER.isErrorEnabled())
                LOGGER.error(e.getLocalizedMessage(), e);
        } catch (TransformException e) {
            if (LOGGER.isErrorEnabled())
                LOGGER.error(e.getLocalizedMessage(), e);
        }

    } finally {
        if (reader != null) {
            try {
                reader.dispose();
            } catch (Exception e) {
                if (LOGGER.isWarnEnabled())
                    LOGGER.warn(e.getLocalizedMessage(), e);
            }

        }
    }
    return true;
}