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:de.uzk.hki.da.convert.CLIConversionStrategy.java

/**
 * Tokenizes commandLine and replaces certain strings.
 * "input" and "output" get replaced by paths of source and destination file.
 * strings beginning with "{" and ending with "}" get replaced by the contents of additionalParams of the ConversionInstruction.
 * Each of the {}-surrounded string gets replaced by exactly one token of additional params.
 *
 * @param ci the ci/*from ww  w .  j av  a  2s. co  m*/
 * @param repName the rep name
 * @return The processed command as list of tokens. The tokenized string has the right format
 * for a call in Runtime.getRuntime().exec(commandToExecute). This holds especially true
 * for filenames (which replace the input/output parameters) that are separated by
 * whitespaces. "file 2.jpg" is represented as one token only.
 */
protected String[] assemble(WorkArea wa, ConversionInstruction ci, String repName) {

    String commandLine_ = commandLine;

    // replace additional params
    List<String> ap = tokenize(ci.getAdditional_params(), ",");
    for (String s : ap) {

        Pattern pattern = Pattern.compile("\\{.*?\\}");
        Matcher matcher = pattern.matcher(commandLine_);
        commandLine_ = matcher.replaceFirst(s);
    }

    // tokenize before replacement to group original tokens together
    // (to prevent wrong tokenization like two tokens for "file" "2.jpg"
    //  which can result from replacement)
    String[] tokenizedCmd = tokenize(commandLine_);

    String targetSuffix = ci.getConversion_routine().getTarget_suffix();
    if (targetSuffix.equals("*"))
        targetSuffix = FilenameUtils.getExtension(wa.toFile(ci.getSource_file()).getAbsolutePath());
    StringUtilities.replace(tokenizedCmd, "input", wa.toFile(ci.getSource_file()).getAbsolutePath());
    StringUtilities.replace(tokenizedCmd, "output",
            wa.dataPath() + "/" + repName + "/" + StringUtilities.slashize(ci.getTarget_folder())
                    + FilenameUtils.removeExtension(Matcher.quoteReplacement(
                            FilenameUtils.getName(wa.toFile(ci.getSource_file()).getAbsolutePath())))
                    + "." + targetSuffix);

    return tokenizedCmd;
}

From source file:com.highcharts.export.controller.ExportController.java

@RequestMapping(method = { RequestMethod.POST, RequestMethod.GET })
public HttpEntity<byte[]> exporter(@RequestParam(value = "svg", required = false) String svg,
        @RequestParam(value = "type", required = false) String type,
        @RequestParam(value = "filename", required = false) String filename,
        @RequestParam(value = "width", required = false) String width,
        @RequestParam(value = "scale", required = false) String scale,
        @RequestParam(value = "options", required = false) String options,
        @RequestParam(value = "globaloptions", required = false) String globalOptions,
        @RequestParam(value = "constr", required = false) String constructor,
        @RequestParam(value = "callback", required = false) String callback,
        @RequestParam(value = "callbackHC", required = false) String callbackHC,
        @RequestParam(value = "async", required = false, defaultValue = "false") Boolean async,
        @RequestParam(value = "jsonp", required = false, defaultValue = "false") Boolean jsonp,
        HttpServletRequest request, HttpSession session)
        throws ServletException, InterruptedException, SVGConverterException, NoSuchElementException,
        PoolException, TimeoutException, IOException, ZeroRequestParameterException {

    MimeType mime = getMime(type);
    String randomFilename = null;
    String jsonpCallback = "";
    boolean isAndroid = request.getHeader("user-agent") != null
            && request.getHeader("user-agent").contains("Android");

    if ("GET".equalsIgnoreCase(request.getMethod())) {

        // Handle redirect downloads for Android devices, these come in without request parameters
        String tempFile = (String) session.getAttribute("tempFile");
        session.removeAttribute("tempFile");

        if (tempFile != null && !tempFile.isEmpty()) {
            logger.debug("filename stored in session, read and stream from filesystem");
            String basename = FilenameUtils.getBaseName(tempFile);
            String extension = FilenameUtils.getExtension(tempFile);

            return getFile(basename, extension);

        }/*from   ww  w.  ja v a 2  s  .c o  m*/
    }

    // check for visitors who don't know this domain is really only for the exporting service ;)
    if (request.getParameterMap().isEmpty()) {
        throw new ZeroRequestParameterException();
    }

    /* Most JSONP implementations use the 'callback' request parameter and this overwrites
     * the original callback parameter for chart creation with Highcharts. If JSONP is
     * used we recommend using the requestparameter callbackHC as the callback for Highcharts.
     * store the callback method name and reset the callback parameter,
     * otherwise it will be used when creation charts
     */
    if (jsonp) {
        async = true;
        jsonpCallback = callback;
        callback = null;

        if (callbackHC != null) {
            callback = callbackHC;
        }
    }

    if (isAndroid || MimeType.PDF.equals(mime) || async) {
        randomFilename = createRandomFileName(mime.name().toLowerCase());
    }

    /* If randomFilename is not null, then we want to save the filename in session, in case of GET is used later on*/
    if (isAndroid) {
        logger.debug("storing randomfile in session: " + FilenameUtils.getName(randomFilename));
        session.setAttribute("tempFile", FilenameUtils.getName(randomFilename));
    }

    String output = convert(svg, mime, width, scale, options, constructor, callback, globalOptions,
            randomFilename);
    ByteArrayOutputStream stream;

    HttpHeaders headers = new HttpHeaders();

    if (async) {
        String link = TempDir.getDownloadLink(randomFilename);
        stream = new ByteArrayOutputStream();
        if (jsonp) {
            StringBuilder sb = new StringBuilder(jsonpCallback);
            sb.append("('");
            sb.append(link);
            sb.append("')");
            stream.write(sb.toString().getBytes("utf-8"));
            headers.add("Content-Type", "text/javascript; charset=utf-8");
        } else {
            stream.write(link.getBytes("utf-8"));
            headers.add("Content-Type", "text/html; charset=UTF-8");
        }
    } else {
        headers.add("Content-Type", mime.getType() + "; charset=utf-8");
        if (randomFilename != null && randomFilename.equals(output)) {
            stream = writeFileToStream(randomFilename);
        } else {
            boolean base64 = !mime.getExtension().equals("svg");
            stream = outputToStream(output, base64);
        }
        filename = getFilename(filename);
        headers.add("Content-Disposition",
                "attachment; filename=" + filename.replace(" ", "_") + "." + mime.name().toLowerCase());
    }

    headers.setContentLength(stream.size());

    return new HttpEntity<byte[]>(stream.toByteArray(), headers);
}

From source file:com.look.UploadPostServlet.java

/**
 * Handles post request for uploading images and creating a post (image post)
 * @param request HttpRequest from client
 * @param response HttpResponse to be sent to client
 * @throws ServletException//w w w . j av a2  s  .  c o m
 * @throws IOException
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    //must reset responseMessage on next post. Fixes unwanted error message bug
    responseMessage = "";

    //get real image directory path
    IMAGE_DIRECTORY = getServletContext().getRealPath("/images/");

    //get user attribute from session
    user = request.getSession().getAttribute("user").toString();

    //try to handle request
    boolean success = handleRequest(request);
    //if handling was not successful (bad input) forward to upload.jsp with message
    if (success == false) {
        request.setAttribute("title", title);
        request.setAttribute("description", description);
        request.setAttribute("tags", tags);
        request.setAttribute("message", responseMessage);
        getServletContext().getRequestDispatcher("/upload.jsp").forward(request, response);
        return;
    }

    Connection conn = null; // connection to the database

    int post_id = -1;

    try {
        // connects to the database
        conn = LookDatabaseUtils.getNewConnection();

        // constructs SQL statement
        String postSQL = "INSERT INTO posts (title, description, users_user_ID, image_url, time_posted)"
                + " values (?, ?, ?, ?, CURRENT_TIMESTAMP)";
        PreparedStatement post_statement = conn.prepareStatement(postSQL);
        post_statement.setString(1, title);
        post_statement.setString(2, description);

        String userQuery = "SELECT user_id FROM users WHERE username=\"" + user + "\"";
        Statement userStatement = conn.createStatement();
        ResultSet userIDRS = userStatement.executeQuery(userQuery);
        userIDRS.next();
        int userID = userIDRS.getInt(1);
        post_statement.setInt(3, userID);

        post_statement.setString(4, imageURL);
        post_statement.executeUpdate();

        Statement postIDStatement = conn.createStatement();
        ResultSet postIDRS = postIDStatement
                .executeQuery("SELECT post_id FROM posts WHERE image_url=\"" + imageURL + "\";");
        postIDRS.next();
        post_id = postIDRS.getInt(1);
        imageURL = FilenameUtils.getName(post_id + "." + imageExtension);
        String imagePermaSQL = "UPDATE posts " + "SET image_url= ? " + "WHERE post_id=" + post_id + ";";
        PreparedStatement imagePermaURL = conn.prepareStatement(imagePermaSQL);
        imagePermaURL.setString(1, imageURL);
        imagePermaURL.executeUpdate();

        if (!uploadFile()) {
            request.setAttribute("message", "Failed to upload");
            Statement removeStatement = conn.createStatement();
            removeStatement.executeUpdate("DELETE FROM posts WHERE post_id=" + post_id + ";");
            getServletContext().getRequestDispatcher("/upload.jsp").forward(request, response);
            return;
        }

        //if there are tags
        if (tagList != null && tagList.size() > 0) {
            //add tags to database
            String addTagSQL = "INSERT IGNORE INTO tags (tag) " + "VALUES (?); ";
            String addRelationshipSQL = "INSERT INTO tags_has_posts(tags_tag_id, posts_post_id) "
                    + "VALUES (?, ?);";
            for (String tag : tagList) {
                PreparedStatement s = conn.prepareStatement(addTagSQL);
                s.setString(1, tag);
                s.executeUpdate();
                ResultSet r = conn.createStatement()
                        .executeQuery("SELECT tag_id FROM tags WHERE tag='" + tag + "';");
                r.next();
                int tag_id = r.getInt(1);
                PreparedStatement rS = conn.prepareStatement(addRelationshipSQL);
                rS.setInt(1, tag_id);
                rS.setInt(2, post_id);
                rS.executeUpdate();
            }
        }

    } catch (SQLException ex) {
        responseMessage = "ERROR: " + ex.getMessage();
        log.warning(ex.getMessage());
    } catch (ClassNotFoundException ex) {
        Logger.getLogger(UploadPostServlet.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        if (conn != null) {
            // closes the database connection
            try {
                conn.close();
            } catch (SQLException ex) {
                log.warning(ex.getMessage());
            }
        }

        response.sendRedirect("post?id=" + post_id);
        //getServletContext().getRequestDispatcher("/index.jsp").forward(request, response);
    }
}

From source file:ch.entwine.weblounge.dispatcher.impl.handler.ImageRequestHandlerImpl.java

/**
 * Handles the request for an image resource that is believed to be in the
 * content repository. The handler scales the image as requested, sets the
 * response headers and the writes the image contents to the response.
 * <p>//www .  ja  v a 2s.  co m
 * This method returns <code>true</code> if the handler is decided to handle
 * the request, <code>false</code> otherwise.
 * 
 * @param request
 *          the weblounge request
 * @param response
 *          the weblounge response
 */
public boolean service(WebloungeRequest request, WebloungeResponse response) {

    WebUrl url = request.getUrl();
    Site site = request.getSite();
    String path = url.getPath();
    String fileName = null;

    // Get hold of the content repository
    ContentRepository contentRepository = site.getContentRepository();
    if (contentRepository == null) {
        logger.warn("No content repository found for site '{}'", site);
        return false;
    } else if (contentRepository.isIndexing()) {
        logger.debug("Content repository of site '{}' is currently being indexed", site);
        DispatchUtils.sendServiceUnavailable(request, response);
        return true;
    }

    // Check if the request uri matches the special uri for images. If so, try
    // to extract the id from the last part of the path. If not, check if there
    // is an image with the current path.
    ResourceURI imageURI = null;
    ImageResource imageResource = null;
    try {
        String id = null;
        String imagePath = null;

        if (path.startsWith(URI_PREFIX)) {
            String uriSuffix = StringUtils.chomp(path.substring(URI_PREFIX.length()), "/");
            uriSuffix = URLDecoder.decode(uriSuffix, "utf-8");

            // Check whether we are looking at a uuid or a url path
            if (uriSuffix.length() == UUID_LENGTH) {
                id = uriSuffix;
            } else if (uriSuffix.length() >= UUID_LENGTH) {
                int lastSeparator = uriSuffix.indexOf('/');
                if (lastSeparator == UUID_LENGTH && uriSuffix.indexOf('/', lastSeparator + 1) < 0) {
                    id = uriSuffix.substring(0, lastSeparator);
                    fileName = uriSuffix.substring(lastSeparator + 1);
                } else {
                    imagePath = uriSuffix;
                    fileName = FilenameUtils.getName(imagePath);
                }
            } else {
                imagePath = "/" + uriSuffix;
                fileName = FilenameUtils.getName(imagePath);
            }
        } else {
            imagePath = path;
            fileName = FilenameUtils.getName(imagePath);
        }

        // Try to load the resource
        imageURI = new ImageResourceURIImpl(site, imagePath, id);
        imageResource = contentRepository.get(imageURI);
        if (imageResource == null) {
            logger.debug("No image found at {}", imageURI);
            return false;
        }
    } catch (ContentRepositoryException e) {
        logger.error("Error loading image from {}: {}", contentRepository, e.getMessage());
        DispatchUtils.sendInternalError(request, response);
        return true;
    } catch (UnsupportedEncodingException e) {
        logger.error("Error decoding image url {} using utf-8: {}", path, e.getMessage());
        DispatchUtils.sendInternalError(request, response);
        return true;
    }

    // Agree to serve the image
    logger.debug("Image handler agrees to handle {}", path);

    // Check the request method. Only GET is supported right now.
    String requestMethod = request.getMethod().toUpperCase();
    if ("OPTIONS".equals(requestMethod)) {
        String verbs = "OPTIONS,GET";
        logger.trace("Answering options request to {} with {}", url, verbs);
        response.setHeader("Allow", verbs);
        response.setContentLength(0);
        return true;
    } else if (!"GET".equals(requestMethod)) {
        logger.debug("Image request handler does not support {} requests", requestMethod);
        DispatchUtils.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, request, response);
        return true;
    }

    // Is it published?
    // TODO: Fix this. imageResource.isPublished() currently returns false,
    // as both from and to dates are null (see PublishingCtx)
    // if (!imageResource.isPublished()) {
    // logger.debug("Access to unpublished image {}", imageURI);
    // DispatchUtils.sendNotFound(request, response);
    // return true;
    // }

    // Can the image be accessed by the current user?
    User user = request.getUser();
    try {
        // TODO: Check permission
        // PagePermission p = new PagePermission(page, user);
        // AccessController.checkPermission(p);
    } catch (SecurityException e) {
        logger.warn("Access to image {} denied for user {}", imageURI, user);
        DispatchUtils.sendAccessDenied(request, response);
        return true;
    }

    // Determine the response language by filename
    Language language = null;
    if (StringUtils.isNotBlank(fileName)) {
        for (ImageContent c : imageResource.contents()) {
            if (c.getFilename().equalsIgnoreCase(fileName)) {
                if (language != null) {
                    logger.debug("Unable to determine language from ambiguous filename");
                    language = LanguageUtils.getPreferredContentLanguage(imageResource, request, site);
                    break;
                }
                language = c.getLanguage();
            }
        }
        if (language == null)
            language = LanguageUtils.getPreferredContentLanguage(imageResource, request, site);
    } else {
        language = LanguageUtils.getPreferredContentLanguage(imageResource, request, site);
    }

    // If the filename did not lead to a language, apply language resolution
    if (language == null) {
        logger.warn("Image {} does not exist in any supported language", imageURI);
        DispatchUtils.sendNotFound(request, response);
        return true;
    }

    // Extract the image style and scale the image
    String styleId = StringUtils.trimToNull(request.getParameter(OPT_IMAGE_STYLE));
    if (styleId != null) {
        try {
            StringBuffer redirect = new StringBuffer(PathUtils.concat(PreviewRequestHandlerImpl.URI_PREFIX,
                    imageResource.getURI().getIdentifier()));
            redirect.append("?style=").append(styleId);
            response.sendRedirect(redirect.toString());
        } catch (Throwable t) {
            logger.debug("Error sending redirect to the client: {}", t.getMessage());
        }
        return true;
    }

    // Check the modified headers
    long revalidationTime = MS_PER_DAY;
    long expirationDate = System.currentTimeMillis() + revalidationTime;
    if (!ResourceUtils.hasChanged(request, imageResource, language)) {
        logger.debug("Image {} was not modified", imageURI);
        response.setDateHeader("Expires", expirationDate);
        DispatchUtils.sendNotModified(request, response);
        return true;
    }

    // Load the image contents from the repository
    ImageContent imageContents = imageResource.getContent(language);

    // Add mime type header
    String contentType = imageContents.getMimetype();
    if (contentType == null)
        contentType = MediaType.APPLICATION_OCTET_STREAM;

    // Set the content type
    String characterEncoding = response.getCharacterEncoding();
    if (StringUtils.isNotBlank(characterEncoding))
        response.setContentType(contentType + "; charset=" + characterEncoding.toLowerCase());
    else
        response.setContentType(contentType);

    // Browser caches and proxies are allowed to keep a copy
    response.setHeader("Cache-Control", "public, max-age=" + revalidationTime);

    // Set Expires header
    response.setDateHeader("Expires", expirationDate);

    // Determine the resource's modification date
    long resourceLastModified = ResourceUtils.getModificationDate(imageResource, language).getTime();

    // Add last modified header
    response.setDateHeader("Last-Modified", resourceLastModified);

    // Add ETag header
    response.setHeader("ETag", ResourceUtils.getETagValue(imageResource));

    // Load the input stream from the repository
    InputStream imageInputStream = null;
    try {
        imageInputStream = contentRepository.getContent(imageURI, language);
    } catch (Throwable t) {
        logger.error("Error loading {} image '{}' from {}: {}",
                new Object[] { language, imageResource, contentRepository, t.getMessage() });
        logger.error(t.getMessage(), t);
        IOUtils.closeQuietly(imageInputStream);
        return false;
    }

    // Write the image back to the client
    try {
        response.setHeader("Content-Length", Long.toString(imageContents.getSize()));
        response.setHeader("Content-Disposition", "inline; filename=" + imageContents.getFilename());
        IOUtils.copy(imageInputStream, response.getOutputStream());
        response.getOutputStream().flush();
    } catch (EOFException e) {
        logger.debug("Error writing image '{}' back to client: connection closed by client", imageResource);
        return true;
    } catch (IOException e) {
        if (RequestUtils.isCausedByClient(e))
            return true;
        logger.error("Error writing {} image '{}' back to client: {}",
                new Object[] { language, imageResource, e.getMessage() });
    } finally {
        IOUtils.closeQuietly(imageInputStream);
    }
    return true;

}

From source file:edu.umn.msi.tropix.proteomics.scaffold.impl.ScaffoldJobProcessorImpl.java

private void addFullPathToScaffoldOutputFiles(final String outputDirectory, final Scaffold scaffold) {
    final List<Export> exports = scaffold.getExperiment().getExport();
    for (final Export export : exports) {
        final String relativePath = export.getPath();
        final String sanitizedPath = FilenameUtils.getName(relativePath);
        final String fullPath = outputDirectory + getStagingDirectory().getSep() + sanitizedPath;
        export.setPath(fullPath);// w w  w.  ja v a2 s.c  om
    }
}

From source file:com.gitpitch.models.SlideshowModel.java

public String fetchLogoName() {
    return (_yOpts != null) ? FilenameUtils.getName(_yOpts.fetchLogo(params())) : "#";
}

From source file:de.pixida.logtest.designer.Editor.java

private void updateDocumentName() {
    final String nameForUnassingedDocument = String.format("New %s [%d]", this.type.getName(),
            newDocumentRunningIndex++);//from w ww.j  a v  a 2  s .c om
    this.setDocumentName(this.file != null ? this.file.getPath() : nameForUnassingedDocument,
            this.file != null ? FilenameUtils.removeExtension(FilenameUtils.getName(this.file.getName()))
                    : nameForUnassingedDocument);
}

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

@Override
public boolean storagePolicyAchieved(String gridPath2, StoragePolicy sp, String checksum, Set<Node> cnodes) {
    irodsSystemConnector.establishConnect();

    String gridPath = "/" + irodsSystemConnector.getZone() + "/" + WorkArea.AIP + "/" + gridPath2;

    int minNodes = sp.getMinNodes();
    if (minNodes == 0) {
        logger.error("Given minnodes setting 0 violates long term preservation");
        return false;
    }//ww w  . j  a va  2s . c o  m
    try {
        logger.debug("checking StoragePolicy achieved for " + gridPath);
        List<String> targetResgroups = Arrays.asList(sp.getReplDestinations().split(","));
        int replicasTotal = 0;
        for (String targetResgroup : targetResgroups) {
            int replicas = 0;
            String res = targetResgroup;
            if (targetResgroup.startsWith("cp_"))
                res = targetResgroup.substring(3);
            replicas = irodsSystemConnector.getNumberOfReplsForDataObjectInResGroup(
                    FilenameUtils.getFullPath(gridPath), FilenameUtils.getName(gridPath), res);
            if (targetResgroup.startsWith("cp_") && replicas > 1)
                replicas--;
            replicasTotal = replicasTotal + replicas;
        }
        logger.debug("Number of Total Replications on LZA Nodes is now (" + replicasTotal
                + "). Total Checked Ressources " + targetResgroups.size() + " Has to exist on (" + minNodes
                + ")");

        if (replicasTotal >= minNodes) {
            irodsSystemConnector.saveOrUpdateAVUMetadataDataObject(gridPath, "replicated", "1");
            irodsSystemConnector.saveOrUpdateAVUMetadataDataObject(gridPath, "min_repls",
                    String.valueOf(minNodes));
            irodsSystemConnector.logoff();
            return true;
        } else {
            irodsSystemConnector.saveOrUpdateAVUMetadataDataObject(gridPath, "replicated", "0");
        }
        irodsSystemConnector.logoff();
        return false;

    } catch (IrodsRuntimeException e) {
        logger.error("Failure acquiring repl status of " + gridPath);
        irodsSystemConnector.logoff();
    }
    return false;
}

From source file:com.jaeksoft.searchlib.web.controller.ViewerController.java

@Command
public void onDownload() throws FileNotFoundException {
    Filedownload.save(new FileInputStream(tempFile), null, FilenameUtils.getName(uri.getPath()));
}

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

/**
 * Checks whether the dataobject exists at that given dest with the given 
 * md5sum. /*from   ww  w .  j a  va  2s . c o  m*/
 * @author Jens Peters
 * @param dest
 * @param md5sum
 * @return
 */
public boolean existsWithChecksum(String dest, String md5sum) {
    if (md5sum.equals(null))
        throw new RuntimeException("md5sum not given");
    if (md5sum.equals(""))
        throw new RuntimeException("md5sum not given");
    String data_name = FilenameUtils.getName(dest);
    String commandAsArray[] = new String[] { "ils", "-L", dest };
    String out = executeIcommand(commandAsArray);
    if (out.indexOf(data_name) >= 0 && out.indexOf(md5sum) > 0)
        return true;
    return false;
}