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:com.openkm.servlet.admin.CheckTextExtractionServlet.java

@SuppressWarnings("unchecked")
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    log.debug("doPost({}, {})", request, response);
    request.setCharacterEncoding("UTF-8");
    updateSessionManager(request);//  w  w w. j  a  va2s .co m
    InputStream is = null;

    try {
        if (ServletFileUpload.isMultipartContent(request)) {
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            List<FileItem> items = upload.parseRequest(request);
            String docUuid = null;
            String repoPath = null;
            String text = null;
            String error = null;
            String mimeType = null;
            String extractor = null;

            for (Iterator<FileItem> it = items.iterator(); it.hasNext();) {
                FileItem item = it.next();

                if (item.isFormField()) {
                    if (item.getFieldName().equals("docUuid")) {
                        docUuid = item.getString("UTF-8");
                    } else if (item.getFieldName().equals("repoPath")) {
                        repoPath = item.getString("UTF-8");
                    }
                } else {
                    is = item.getInputStream();
                    String name = FilenameUtils.getName(item.getName());
                    mimeType = MimeTypeConfig.mimeTypes.getContentType(name.toLowerCase());

                    if (!name.isEmpty() && item.getSize() > 0) {
                        docUuid = null;
                        repoPath = null;
                    } else if (docUuid.isEmpty() && repoPath.isEmpty()) {
                        mimeType = null;
                    }
                }
            }

            if (docUuid != null && !docUuid.isEmpty()) {
                repoPath = OKMRepository.getInstance().getNodePath(null, docUuid);
            }

            if (repoPath != null && !repoPath.isEmpty()) {
                String name = PathUtils.getName(repoPath);
                mimeType = MimeTypeConfig.mimeTypes.getContentType(name.toLowerCase());
                is = OKMDocument.getInstance().getContent(null, repoPath, false);
            }

            long begin = System.currentTimeMillis();

            if (is != null) {
                if (!MimeTypeConfig.MIME_UNDEFINED.equals(mimeType)) {
                    TextExtractor extClass = RegisteredExtractors.getTextExtractor(mimeType);

                    if (extClass != null) {
                        try {
                            extractor = extClass.getClass().getCanonicalName();
                            text = RegisteredExtractors.getText(mimeType, null, is);
                        } catch (Exception e) {
                            error = e.getMessage();
                        }
                    } else {
                        extractor = "Undefined text extractor";
                    }
                }
            }

            ServletContext sc = getServletContext();
            sc.setAttribute("docUuid", docUuid);
            sc.setAttribute("repoPath", repoPath);
            sc.setAttribute("text", text);
            sc.setAttribute("time", System.currentTimeMillis() - begin);
            sc.setAttribute("mimeType", mimeType);
            sc.setAttribute("error", error);
            sc.setAttribute("extractor", extractor);
            sc.getRequestDispatcher("/admin/check_text_extraction.jsp").forward(request, response);
        }
    } catch (DatabaseException e) {
        sendErrorRedirect(request, response, e);
    } catch (FileUploadException e) {
        sendErrorRedirect(request, response, e);
    } catch (PathNotFoundException e) {
        sendErrorRedirect(request, response, e);
    } catch (AccessDeniedException e) {
        sendErrorRedirect(request, response, e);
    } catch (RepositoryException e) {
        sendErrorRedirect(request, response, e);
    } finally {
        IOUtils.closeQuietly(is);
    }
}

From source file:com.textocat.textokit.commons.util.DocumentUtils.java

public static String getFilename(String uriStr) throws URISyntaxException {
    URI uri = new URI(uriStr);
    String path;/*w ww . jav a2 s .  co m*/
    if (uri.isOpaque()) {
        // TODO this is a hotfix. In future we should avoid setting opaque source URIs in DocumentMetadata
        path = uri.getSchemeSpecificPart();
    } else {
        path = uri.getPath();
    }
    return FilenameUtils.getName(path);
}

From source file:com.frostwire.android.gui.httpserver.DesktopUploadHandler.java

private boolean readFile(InputStream is, String filePath, String token) {
    String fileName = FilenameUtils.getName(filePath);
    FileOutputStream fos = null;/*from   w  w  w  .ja v  a 2  s.  c o  m*/

    File file = null;
    DesktopTransfer transfer = null;
    DesktopTransferItem transferItem = null;

    try {

        file = new File(SystemUtils.getTempDirectory(), fileName);

        fos = new FileOutputStream(file);

        DesktopUploadRequest dur = sessionManager.getDUR(token);
        FileDescriptor fd = findFD(dur, filePath);

        transfer = TransferManager.instance().desktopTransfer(dur, fd);
        transferItem = transfer.getItem(fd);

        byte[] buffer = new byte[4 * 1024];
        int n;

        while ((n = is.read(buffer, 0, buffer.length)) != -1) {
            fos.write(buffer, 0, n);
            if (transfer.isCanceled()) {
                sessionManager.updateDURStatus(token, DesktopUploadRequestStatus.REJECTED);
                file.delete();
                fos.close();
                return false;
            } else {
                transferItem.addBytesTransferred(n);
                sessionManager.updateDURStatus(token, DesktopUploadRequestStatus.UPLOADING);
            }
        }

        sessionManager.updateDURStatus(token, DesktopUploadRequestStatus.ACCEPTED);

        File finalFile = new File(SystemUtils.getDesktopFilesirectory(), file.getName());

        if (file.renameTo(finalFile)) {
            Librarian.instance().scan(finalFile.getAbsoluteFile());
            return true;
        } else {
            file.delete();
        }

    } catch (Throwable e) {
        Log.e(TAG, String.format("Error saving file: fileName=%s, token=%s", fileName, token), e);

        if (file != null) {
            file.delete();
        }

        if (transferItem != null) {
            transferItem.setFailed();
        }
    } finally {
        if (fos != null) {
            try {
                fos.close();
            } catch (Throwable e) {
                // ignore
            }
        }
        try {
            is.close();
        } catch (Throwable e) {
            // ignore
        }
    }

    return false;
}

From source file:com.iyonger.apm.web.service.ScriptValidationService.java

@Override
public String validate(User user, IFileEntry scriptIEntry, boolean useScriptInSVN, String hostString) {
    FileEntry scriptEntry = TypeConvertUtils.cast(scriptIEntry);
    try {/*  w  w w. ja  v a2 s  .co  m*/
        checkNotNull(scriptEntry, "scriptEntity should be not null");
        checkNotEmpty(scriptEntry.getPath(), "scriptEntity path should be provided");
        if (!useScriptInSVN) {
            checkNotEmpty(scriptEntry.getContent(), "scriptEntity content should be provided");
        }
        checkNotNull(user, "user should be provided");
        // String result = checkSyntaxErrors(scriptEntry.getContent());

        ScriptHandler handler = scriptHandlerFactory.getHandler(scriptEntry);
        if (config.getControllerProperties().getPropertyBoolean(PROP_CONTROLLER_VALIDATION_SYNTAX_CHECK)) {
            String result = handler.checkSyntaxErrors(scriptEntry.getPath(), scriptEntry.getContent());
            LOGGER.info("Perform Syntax Check by {} for {}", user.getUserId(), scriptEntry.getPath());
            if (result != null) {
                return result;
            }
        }
        File scriptDirectory = config.getHome().getScriptDirectory(user);
        FileUtils.deleteDirectory(scriptDirectory);
        Preconditions.checkTrue(scriptDirectory.mkdirs(), "Script directory {} creation is failed.");

        ProcessingResultPrintStream processingResult = new ProcessingResultPrintStream(
                new ByteArrayOutputStream());
        handler.prepareDist(0L, user, scriptEntry, scriptDirectory, config.getControllerProperties(),
                processingResult);
        if (!processingResult.isSuccess()) {
            return new String(processingResult.getLogByteArray());
        }
        File scriptFile = new File(scriptDirectory, FilenameUtils.getName(scriptEntry.getPath()));

        if (useScriptInSVN) {
            fileEntryService.writeContentTo(user, scriptEntry.getPath(), scriptDirectory);
        } else {
            FileUtils.writeStringToFile(scriptFile, scriptEntry.getContent(),
                    StringUtils.defaultIfBlank(scriptEntry.getEncoding(), "UTF-8"));
        }
        File doValidate = localScriptTestDriveService.doValidate(scriptDirectory, scriptFile, new Condition(),
                config.isSecurityEnabled(), hostString, getTimeout());
        List<String> readLines = FileUtils.readLines(doValidate);
        StringBuilder output = new StringBuilder();
        String path = config.getHome().getDirectory().getAbsolutePath();
        for (String each : readLines) {
            if (!each.startsWith("*sys-package-mgr")) {
                each = each.replace(path, "${NGRINDER_HOME}");
                output.append(each).append("\n");
            }
        }
        return output.toString();
    } catch (Exception e) {
        throw processException(e);
    }
}

From source file:eu.esdihumboldt.hale.io.html.HtmlMappingExporter.java

@Override
protected IOReport execute(ProgressIndicator progress, IOReporter reporter)
        throws IOProviderConfigurationException, IOException {
    this.reporter = reporter;

    context = new VelocityContext();
    cellIds = new Identifiers<Cell>(Cell.class, false);

    alignment = getAlignment();//from w ww.  j av a  2  s  .c o m

    URL headlinePath = this.getClass().getResource("bg-headline.png"); //$NON-NLS-1$
    URL cssPath = this.getClass().getResource("style.css"); //$NON-NLS-1$
    URL linkPath = this.getClass().getResource("int_link.png"); //$NON-NLS-1$
    URL tooltipIcon = this.getClass().getResource("tooltip.gif"); //$NON-NLS-1$
    final String filesSubDir = FilenameUtils
            .removeExtension(FilenameUtils.getName(getTarget().getLocation().getPath())) + "_files"; //$NON-NLS-1$
    final File filesDir = new File(FilenameUtils.getFullPath(getTarget().getLocation().getPath()), filesSubDir);

    filesDir.mkdirs();
    context.put(FILE_DIRECTORY, filesSubDir);

    try {
        init();
    } catch (Exception e) {
        return reportError(reporter, "Initializing error", e);
    }
    File cssOutputFile = new File(filesDir, "style.css");
    FileUtils.copyFile(getInputFile(cssPath), cssOutputFile);

    // create headline picture
    File headlineOutputFile = new File(filesDir, "bg-headline.png"); //$NON-NLS-1$
    FileUtils.copyFile(getInputFile(headlinePath), headlineOutputFile);

    File linkOutputFile = new File(filesDir, "int_link.png"); //$NON-NLS-1$
    FileUtils.copyFile(getInputFile(linkPath), linkOutputFile);

    File tooltipIconFile = new File(filesDir, "tooltip.png"); //$NON-NLS-1$
    FileUtils.copyFile(getInputFile(tooltipIcon), tooltipIconFile);

    File htmlExportFile = new File(getTarget().getLocation().getPath());
    if (projectInfo != null) {
        Date date = new Date();
        DateFormat dfm = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT);

        // associate variables with information data
        String exportDate = dfm.format(date);
        context.put(EXPORT_DATE, exportDate);

        if (projectInfo.getCreated() != null) {
            String created = dfm.format(projectInfo.getCreated());
            context.put(CREATED_DATE, created);
        }

        context.put(PROJECT_INFO, projectInfo);
    }

    if (alignment != null) {
        Collection<TypeCellInfo> typeCellInfos = new ArrayList<TypeCellInfo>();
        Collection<? extends Cell> cells = alignment.getTypeCells();
        Iterator<? extends Cell> it = cells.iterator();
        while (it.hasNext()) {
            final Cell cell = it.next();
            // this is the collection of type cell info
            TypeCellInfo typeCellInfo = new TypeCellInfo(cell, alignment, cellIds, filesSubDir);
            typeCellInfos.add(typeCellInfo);
        }
        // put the full collection of type cell info to the context (for the
        // template)
        context.put(TYPE_CELL_INFOS, typeCellInfos);
        createImages(filesDir);
    }

    context.put(TOOLTIP, getParameter(TOOLTIP).as(boolean.class));

    Template template;
    try {
        template = velocityEngine.getTemplate(templateFile.getName(), "UTF-8");
    } catch (Exception e) {
        return reportError(reporter, "Could not load template", e);
    }

    FileWriter fileWriter = new FileWriter(htmlExportFile);
    template.merge(context, fileWriter);
    fileWriter.close();

    reporter.setSuccess(true);
    return reporter;
}

From source file:io.stallion.contentPublishing.UploadRequestProcessor.java

protected File downloadExternalToLocalFile(U uploaded) {

    URI uri = URI.create(urlToFetch);

    String fullFileName = FilenameUtils.getName(uri.getPath());
    String extension = FilenameUtils.getExtension(fullFileName);
    String fileName = truncate(fullFileName, 85);
    String relativePath = GeneralUtils.slugify(truncate(FilenameUtils.getBaseName(fullFileName), 75)) + "-"
            + DateUtils.mils() + "." + extension;
    relativePath = "stallion-file-" + uploaded.getId() + "/" + GeneralUtils.secureRandomToken(8) + "/"
            + relativePath;/*from  ww  w.jav a 2s . co  m*/

    String destPath = uploadsFolder + relativePath;
    try {
        FileUtils.forceMkdir(new File(destPath).getParentFile());
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

    uploaded.setCloudKey(relativePath).setExtension(extension).setName(fileName)
            .setOwnerId(Context.getUser().getId()).setUploadedAt(DateUtils.utcNow())
            .setType(fileController.getTypeForExtension(extension));

    // Make raw URL
    String url = makeRawUrlForFile(uploaded, "org");
    uploaded.setRawUrl(url);

    fileController.save(uploaded);

    File outFile = new File(destPath);

    try {
        IOUtils.copy(Unirest.get(urlToFetch).asBinary().getRawBody(),
                org.apache.commons.io.FileUtils.openOutputStream(outFile));
    } catch (UnirestException e) {
        throw new ClientException("Error downloading file from " + url + ": " + e.getMessage(), 400, e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

    return outFile;

}

From source file:edu.cornell.med.icb.goby.stats.DifferentialExpressionAnalysis.java

/**
 * Return true if the basename is on the command line as an input basename.
 *
 * @param basename//from   w  w  w  . jav  a  2s  . c  o m
 * @param inputFilenames
 * @return
 */
private boolean isInputBasename(final String basename, final String[] inputFilenames) {
    for (final String inputFilename : inputFilenames) {
        if (FilenameUtils.getName(AlignmentReaderImpl.getBasename(inputFilename)).equals(basename)) {
            return true;
        }
    }
    return false;
}

From source file:com.nagarro.core.util.ws.impl.AddonAwareMessageSource.java

protected boolean validateFilename(final String path) {
    if (fileFilter == null) {
        return true;
    }/*from  ww  w  .  j ava  2s  .  c om*/
    final String filename = FilenameUtils.getName(path);
    return fileFilter.test(filename);
}

From source file:com.isomorphic.maven.util.ArchiveUtils.java

/**
 * Derives a new file path, in whole or in part, from an existing path.  The following use cases are supported explicitly:
 * <ul>   /*w  w w  . ja  v a2 s.c om*/
 *    <li>
 *       Rename a file (example: smartgwt-lgpl.jar)
 *       <p/>
 *       <code>
 *          ArchiveUtils.rewritePath("smartgwtee-4.1d/lib/smartgwt.jar", "smartgwt-lgpl.jar");   
 *       </code> 
 *    </li>
 *    <li>
 *       Move to another directory (example: target/smartgwt.jar)
 *      <p/>
 *       <code>
 *          ArchiveUtils.rewritePath("smartgwtee-4.1d/lib/smartgwt.jar", "target");
 *       </code>
 * </li>
 * <li>Move and rename (example: target/smartgwt-lgpl.jar)
 *       <p/>
 *       <code>
 *          ArchiveUtils.rewritePath("smartgwtee-4.1d/lib/smartgwt.jar", "target/smartgwt-lgpl.jar"); 
 *       </code> 
 * </li>
 *  <li>Move to new root directory, preserving some part of the existing path</li>
 *     <ul>
 *        <li>
 *           example: doc/api/com/isomorphic/servlet/IDACall.html
 *           <p/>
 *           <code>
 *              ArchiveUtils.rewritePath("smartgwtee-4.1d/doc/javadoc/com/isomorphic/servlet/IDACall.html","doc/api/#javadoc");
 *           </code>
 *          </li>
 *          <li>
 *           example: doc/api/com/isomorphic/servlet/network/FileAssembly.html
 *           <p/>
 *           <code>
 *                 ArchiveUtils.rewritePath("smartgwtee-4.1d/doc/javadoc/com/isomorphic/servlet/CompressionFilter.html", "doc/api/#javadoc/network");
 *           </code>
 *          </li>
 *     </ul>
        
 * </ul>
 * 
 * @param oldValue the existing path
 * @param newValue the value to use for the new path, including optional tokens
 * @return
 */
public static String rewritePath(String oldValue, String newValue) {

    String path = newValue;
    String filename;

    if ("".equals(FilenameUtils.getExtension(newValue))) {
        filename = FilenameUtils.getName(oldValue);
    } else {
        path = FilenameUtils.getPath(newValue);
        filename = FilenameUtils.getName(newValue);
    }

    Pattern p = Pattern.compile("(.*?)#(.*?)(?:$|(/.*))");
    Matcher m = p.matcher(path);

    if (m.find()) {

        String prefix = m.group(1);
        String dir = m.group(2);
        String suffix = m.group(3);

        int index = oldValue.indexOf(dir);
        int length = dir.length();

        String remainder = FilenameUtils.getPath(oldValue.substring(index + length));

        if (prefix != null && !prefix.equals("")) {
            path = prefix + remainder;
        } else {
            path = remainder;
        }

        if (suffix != null && !suffix.equals("")) {
            path += suffix;
        }
    }

    return FilenameUtils.normalize(path + "/" + filename);
}

From source file:controllers.CodeApp.java

@With(DefaultProjectCheckAction.class)
public static Result showRawFile(String userName, String projectName, String revision, String path)
        throws Exception {
    byte[] fileAsRaw = RepositoryService.getFileAsRaw(userName, projectName, revision, path);
    if (fileAsRaw == null) {
        return redirect(routes.CodeApp.codeBrowserWithBranch(userName, projectName, revision, path));
    }// ww w  .j a v  a 2  s  .  c o  m

    MediaType mediaType = FileUtil.detectMediaType(fileAsRaw, FilenameUtils.getName(path));

    String mediaTypeString = "text/plain";
    String charset = FileUtil.getCharset(mediaType);
    if (charset != null) {
        mediaTypeString += "; charset=" + charset;
    }

    return ok(fileAsRaw).as(mediaTypeString);
}