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:edu.umn.msi.tropix.proteomics.scaffold.impl.ScaffoldJobProcessorImpl.java

private void addFullPathToScaffoldInputFiles(final String inputDirectory, final String databaseDirectory,
        final Scaffold scaffold) {
    final Experiment experiment = scaffoldInput.getExperiment();
    final List<FastaDatabase> databases = experiment.getFastaDatabase();
    for (final FastaDatabase database : databases) {
        final String path = database.getPath();
        final String sanitizedPath = FilenameUtils.getName(path);
        database.setPath(databaseDirectory + getStagingDirectory().getSep() + sanitizedPath);
    }/*from w  w w.  j  av a 2s.com*/

    final List<BiologicalSample> samples = scaffold.getExperiment().getBiologicalSample();
    for (final BiologicalSample sample : samples) {
        for (int i = 0; i < sample.getInputFile().size(); i++) {
            final String relativePath = sample.getInputFile().get(i);
            final String sanitizedPath = FilenameUtils.getName(relativePath);
            sample.getInputFile().set(i, inputDirectory + getStagingDirectory().getSep() + sanitizedPath);
        }
    }
}

From source file:com.nuvolect.securesuite.webserver.connector.CmdZipdl.java

private InputStream archiveFiles(@NonNull Map<String, String> params) {
    /**//from   www  .  j a  v a2 s. c  o m
     * Params only has the first element of the targets[] array.
     * This is fine if there is only one target but an issue for multiple file operations.
     * Manually parse the query parameter strings to get all targets.
     */
    String[] qps = params.get("queryParameterStrings").split("&");

    ArrayList<OmniFile> files = new ArrayList<>();
    for (String candidate : qps) {
        if (candidate.contains("targets")) {
            String[] parts = candidate.split("=");

            String target = parts[1];
            files.add(new OmniFile(target));

            if (LogUtil.DEBUG) {
                LogUtil.log(LogUtil.LogType.CMD_ZIPDL, target);
            }
        }
    }

    /**
     * Create a file for the target archive in the directory of the first target file.
     */
    String volumeId = files.get(0).getVolumeId();
    String zipFileName = "Archive.zip";
    String zipPath = files.get(0).getParentFile().getPath() + File.separator + zipFileName;
    OmniFile zipFile = OmniUtil.makeUniqueName(new OmniFile(volumeId, zipPath));

    // Filename may have changed
    zipFileName = FilenameUtils.getName(zipFile.getPath());

    JsonObject zipdl = new JsonObject();
    JsonObject wrapper = new JsonObject();

    zipdl.addProperty("file", zipFile.getHash());
    zipdl.addProperty("name", zipFileName);
    zipdl.addProperty("mime", MimeUtil.MIME_ZIP);
    wrapper.add("zipdl", zipdl);

    if (!OmniZip.zipFiles(context, files, zipFile, 0)) {
        return null;
    }

    LogUtil.log(LogUtil.LogType.CMD_ZIPDL, "first request");
    LogUtil.log(LogUtil.LogType.CMD_ZIPDL, wrapper.toString());

    return getInputStream(wrapper);
}

From source file:au.org.ala.delta.editor.slotfile.model.DirectiveFile.java

public String getShortFileName() {
    String fileName = getFileName();
    return FilenameUtils.getName(fileName);
}

From source file:com.aquest.emailmarketing.web.controllers.ImportController.java

/**
 * Import list./* w  ww  .jav a2 s. c  o m*/
 *
 * @param model the model
 * @param request the request
 * @return the string
 * @throws IOException Signals that an I/O exception has occurred.
 * @throws FileNotFoundException the file not found exception
 * @throws ParserConfigurationException the parser configuration exception
 * @throws TransformerException the transformer exception
 * @throws ServletException the servlet exception
 * @throws FileUploadException the file upload exception
 */
@RequestMapping(value = "/importList", method = RequestMethod.POST)
public String ImportList(Model model, HttpServletRequest request) throws IOException, FileNotFoundException,
        ParserConfigurationException, TransformerException, ServletException, FileUploadException {
    List<String> copypaste = new ArrayList<String>();
    String listfilename = "";
    String separator = "";
    String broadcast_id = "";
    String old_broadcast_id = "";
    String listType = "";
    EmailListForm emailListForm = new EmailListForm();

    InputStream fileContent = null;

    List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
    for (FileItem item : items) {
        if (item.isFormField()) {
            // Process regular form field (input type="text|radio|checkbox|etc", select, etc).
            String fieldName = item.getFieldName();
            String fieldValue = item.getString();
            if (fieldName.equals("listType")) {
                listType = fieldValue;
                System.out.println(listType);
            } else if (fieldName.equals("copypaste")) {
                for (String line : fieldValue.split("\\n")) {
                    copypaste.add(line);
                    System.out.println(line);
                }
            } else if (fieldName.equals("listfilename")) {
                listfilename = fieldValue;
            } else if (fieldName.equals("separator")) {
                separator = fieldValue;
            } else if (fieldName.equals("broadcast_id")) {
                broadcast_id = fieldValue;
            } else if (fieldName.equals("old_broadcast_id")) {
                old_broadcast_id = fieldValue;
            }
        } else {
            // Process form file field (input type="file").
            String fieldName = item.getFieldName();
            String fileName = FilenameUtils.getName(item.getName());
            fileContent = item.getInputStream();
        }
        System.out.println(listfilename);
        System.out.println(separator);
    }
    int importCount = 0;
    if (listType.equals("copy")) {
        if (!copypaste.isEmpty()) {
            List<EmailList> eList = emailListService.importEmailfromCopy(copypaste, broadcast_id);
            emailListForm.setEmailList(eList);
            importCount = eList.size();
        } else {
            // sta ako je prazno
        }
    }
    if (listType.equals("fromfile")) {
        List<EmailList> eList = emailListService.importEmailfromFile(fileContent, separator, broadcast_id);
        emailListForm.setEmailList(eList);
        importCount = eList.size();
    }

    System.out.println(broadcast_id);
    model.addAttribute("importCount", importCount);
    model.addAttribute("emailListForm", emailListForm);
    Broadcast broadcast = broadcastService.getBroadcast(broadcast_id);
    System.out.println("Old broadcast: " + old_broadcast_id);
    if (!old_broadcast_id.isEmpty()) {
        model.addAttribute("old_broadcast_id", old_broadcast_id);
    }
    String message = null;
    if (broadcast.getBcast_template_id() != null) {
        message = "template";
    }
    model.addAttribute("message", message);
    model.addAttribute("broadcast_id", broadcast_id);
    return "importlistreport";
}

From source file:com.frostwire.bittorrent.BTDownload.java

@Override
public String getDisplayName() {
    Priority[] priorities = th.filePriorities();

    int count = 0;
    int index = 0;
    for (int i = 0; i < priorities.length; i++) {
        if (!Priority.IGNORE.equals(priorities[i])) {
            count++;//from w  ww.ja  v a 2 s. c  o m
            index = i;
        }
    }

    return count != 1 ? th.name() : FilenameUtils.getName(th.torrentFile().files().filePath(index));
}

From source file:it.geosolutions.geobatch.geotiff.retile.GeotiffRetilerAction.java

@Override
public Queue<FileSystemEvent> execute(Queue<FileSystemEvent> events) throws ActionException {
    try {/*from   w  w  w. j  a  v a2s.  c o  m*/

        if (configuration == null) {
            final String message = "GeotiffRetiler::execute(): flow configuration is null.";
            if (LOGGER.isErrorEnabled())
                LOGGER.error(message);
            throw new ActionException(this, message);
        }
        if (events.size() == 0) {
            throw new ActionException(this,
                    "GeotiffRetiler::execute(): Unable to process an empty events queue.");
        }

        if (LOGGER.isInfoEnabled())
            LOGGER.info("GeotiffRetiler::execute(): Starting with processing...");

        listenerForwarder.started();

        // The return
        final Queue<FileSystemEvent> ret = new LinkedList<FileSystemEvent>();

        while (events.size() > 0) {

            FileSystemEvent event = events.remove();

            File eventFile = event.getSource();
            FileSystemEventType eventType = event.getEventType();

            if (eventFile.exists() && eventFile.canRead() && eventFile.canWrite()) {
                /*
                 * If here: we can start retiler actions on the incoming file event
                 */

                if (eventFile.isDirectory()) {

                    File[] fileList = eventFile.listFiles();
                    int size = fileList.length;
                    for (int progress = 0; progress < size; progress++) {

                        File inFile = fileList[progress];

                        final String absolutePath = inFile.getAbsolutePath();
                        final String inputFileName = FilenameUtils.getName(absolutePath);

                        if (LOGGER.isInfoEnabled())
                            LOGGER.info("is going to retile: " + inputFileName);

                        try {

                            listenerForwarder.setTask("GeotiffRetiler");
                            GeoTiffRetilerUtils.reTile(inFile, configuration, getTempDir());

                            // set the output
                            /*
                             * COMMENTED OUT 21 Feb 2011: simone: If the event represents a Dir
                             * we have to return a Dir. Do not matter failing files.
                             * 
                             * carlo: we may also want to check if a file is already tiled!
                             * 
                             * File outputFile=reTile(inFile); if (outputFile!=null){ //TODO:
                             * here we use the same event for each file in the ret.add(new
                             * FileSystemEvent(outputFile, eventType)); }
                             */

                        } catch (UnsupportedOperationException uoe) {
                            listenerForwarder.failed(uoe);
                            if (LOGGER.isWarnEnabled())
                                LOGGER.warn(uoe.getLocalizedMessage(), uoe);
                            continue;
                        } catch (IOException ioe) {
                            listenerForwarder.failed(ioe);
                            if (LOGGER.isWarnEnabled())
                                LOGGER.warn(ioe.getLocalizedMessage(), ioe);
                            continue;
                        } catch (IllegalArgumentException iae) {
                            listenerForwarder.failed(iae);
                            if (LOGGER.isWarnEnabled())
                                LOGGER.warn(iae.getLocalizedMessage(), iae);
                            continue;
                        } finally {
                            listenerForwarder.setProgress((progress * 100) / ((size != 0) ? size : 1));
                            listenerForwarder.progressing();
                        }
                    }

                    if (LOGGER.isInfoEnabled())
                        LOGGER.info("SUCCESSFULLY completed work on: " + event.getSource());

                    // add the directory to the return
                    ret.add(event);
                } else {
                    // file is not a directory
                    try {
                        listenerForwarder.setTask("GeotiffRetiler");
                        final File outputFile = GeoTiffRetilerUtils.reTile(eventFile, configuration,
                                getTempDir());

                        if (LOGGER.isInfoEnabled())
                            LOGGER.info("SUCCESSFULLY completed work on: " + event.getSource());
                        listenerForwarder.setProgress(100);
                        ret.add(new FileSystemEvent(outputFile, eventType));

                    } catch (UnsupportedOperationException uoe) {
                        listenerForwarder.failed(uoe);
                        if (LOGGER.isWarnEnabled())
                            LOGGER.warn(uoe.getLocalizedMessage(), uoe);
                        continue;
                    } catch (IOException ioe) {
                        listenerForwarder.failed(ioe);
                        if (LOGGER.isWarnEnabled())
                            LOGGER.warn(ioe.getLocalizedMessage(), ioe);
                        continue;
                    } catch (IllegalArgumentException iae) {
                        listenerForwarder.failed(iae);
                        if (LOGGER.isWarnEnabled())
                            LOGGER.warn(iae.getLocalizedMessage(), iae);
                        continue;
                    } finally {

                        listenerForwarder.setProgress((100) / ((events.size() != 0) ? events.size() : 1));
                        listenerForwarder.progressing();
                    }
                }
            } else {
                final String message = "The passed file event refers to a not existent "
                        + "or not readable/writeable file! File: " + eventFile.getAbsolutePath();
                if (LOGGER.isWarnEnabled())
                    LOGGER.warn(message);
                final IllegalArgumentException iae = new IllegalArgumentException(message);
                listenerForwarder.failed(iae);
            }
        } // endwile
        listenerForwarder.completed();

        // return
        if (ret.size() > 0) {
            events.clear();
            return ret;
        } else {
            /*
             * If here: we got an error no file are set to be returned the input queue is
             * returned
             */
            return events;
        }
    } catch (Exception t) {
        if (LOGGER.isErrorEnabled())
            LOGGER.error(t.getLocalizedMessage(), t);
        final ActionException exc = new ActionException(this, t.getLocalizedMessage(), t);
        listenerForwarder.failed(exc);
        throw exc;
    }
}

From source file:com.thoughtworks.go.server.service.builders.FetchTaskBuilder.java

FetchHandler getHandler(FetchTask task, String pipelineName) {
    return isNotEmpty(task.getRawSrcdir()) ? new DirHandler(task.getRawSrcdir(), task.destOnAgent(pipelineName))
            : new FileHandler(task.artifactDest(pipelineName, FilenameUtils.getName(task.getRawSrcfile())),
                    task.getSrc());//from w  w w  . jav a 2s.  com
}

From source file:net.sf.zekr.engine.audio.AudioCacheManager.java

public PlayableObject getPlayableObject(AudioData audioData, String offlineUrl, String onlineUrl) {
    try {/*from   www  .  j  a v  a  2  s .co  m*/
        ApplicationConfig config = ApplicationConfig.getInstance();
        String filePath = AudioUtils.getAudioFileUrl(audioData, offlineUrl, onlineUrl);
        if (filePath == null) {
            return null;
        }
        if (PathUtils.isOnlineContent(filePath)) {
            String fileName = FilenameUtils.getName(new URI(filePath).getPath());
            String cacheItemName = getCacheItemName(audioData, fileName);
            File cached = getCacheItem(cacheItemName);
            if (cached == null || cached.length() == 0) {
                InputStream stream = config.getNetworkController().openSteam(filePath, 5000);
                return new PlayableObject(new NamedBufferedInputStream(filePath, stream, 4 * 1024));
            } else {
                return new PlayableObject(cached);
            }
        } else {
            File resolvedFile = PathUtils.resolve(filePath, audioData.file.getParent());
            if (resolvedFile != null && resolvedFile.exists()) {
                return new PlayableObject(resolvedFile);
            } else {
                logger.warn("File not found: " + resolvedFile);
                return null;
            }
        }
    } catch (Exception e) {
        logger.error("Error providing playable object.", e);
        return null;
    }
}

From source file:br.com.caelum.vraptor.observer.upload.CommonsUploadMultipartObserver.java

protected void processFile(FileItem item, String name, MutableRequest request) {
    try {/*  w w  w  .ja v a  2s.c  om*/
        String fileName = FilenameUtils.getName(item.getName());
        UploadedFile upload = new DefaultUploadedFile(item.getInputStream(), fileName, item.getContentType(),
                item.getSize());
        request.setParameter(name, name);
        request.setAttribute(name, upload);

        logger.debug("Uploaded file: {} with {}", name, upload);
    } catch (IOException e) {
        throw new InvalidParameterException("Cant parse uploaded file " + item.getName(), e);
    }
}

From source file:ching.icecreaming.actions.FileLink.java

@Action(value = "file-link", results = { @Result(name = "success", type = "stream", params = { "inputName",
        "imageStream", "contentType", "${contentType}", "contentDisposition", "attachment;filename=${fileName}",
        "allowCaching", "false", "bufferSize", "1024" }), @Result(name = "error", location = "errors.jsp") })
public String execute() throws Exception {
    Configuration propertiesConfiguration1 = new PropertiesConfiguration("mimeTypes.properties");
    File file1 = null, file2 = null;
    String string1 = null, fileExtension = null;
    fileExtension = FilenameUtils.getExtension(fileName);
    contentType = "application/octet-stream";
    if (!StringUtils.isBlank(fileExtension)) {
        if (propertiesConfiguration1.containsKey(fileExtension))
            contentType = propertiesConfiguration1.getString(fileExtension);
    } else {/*from ww  w  .j a  v a2s  .c om*/
        contentType = "image/png";
    }
    try {
        if (StringUtils.isBlank(sessionId)) {
            sessionId = httpServletRequest.getSession().getId();
        }
        string1 = System.getProperty("java.io.tmpdir") + File.separator + sessionId;
        if (StringUtils.isBlank(fileExtension))
            string1 += File.separator + FilenameUtils.getPath(fileName);
        fileName = FilenameUtils.getName(fileName);
        if (StringUtils.equalsIgnoreCase(fileExtension, "html")) {
            file2 = new File(string1, FilenameUtils.getBaseName(fileName) + ".zip");
            if (file2.exists()) {
                file1 = file2;
                contentType = "application/zip";
                fileName = file2.getName();
            } else {
                file1 = new File(string1, fileName);
            }
        } else {
            file1 = new File(string1, fileName);
        }
        if (file1.exists()) {
            imageStream = new BufferedInputStream(FileUtils.openInputStream(file1));
        }
    } catch (IOException exception1) {
        addActionError(exception1.getMessage());
        return ERROR;
    }
    return SUCCESS;
}