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.apt.ajax.controller.AjaxUpload.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from   www.  j a  va  2 s .co  m
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("application/json");

    String uploadDir = request.getServletContext().getRealPath(File.separator) + "upload";
    Gson gson = new Gson();
    MessageBean messageBean = new MessageBean();
    try (PrintWriter out = response.getWriter()) {
        /* TODO output your page here. You may use following sample code. */
        File x = new File(uploadDir);
        if (!x.exists()) {
            x.mkdir();
        }
        boolean isMultiplePart = ServletFileUpload.isMultipartContent(request);

        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        if (!isMultiplePart) {

        } else {
            List items = null;

            try {
                items = upload.parseRequest(request);
                if (items != null) {
                    Iterator iterator = items.iterator();
                    String assignmentId = "";
                    String stuid = "";
                    while (iterator.hasNext()) {
                        FileItem item = (FileItem) iterator.next();
                        if (item.isFormField()) {
                            String fieldName = item.getFieldName();
                            if (fieldName.equals("assignmentid")) {
                                assignmentId = item.getString();
                                File c = new File(uploadDir + File.separator + assignmentId);
                                if (!c.exists()) {
                                    c.mkdir();
                                }
                                uploadDir = c.getPath();
                                if (request.getSession().getAttribute("studentId") != null) {
                                    stuid = request.getSession().getAttribute("studentId").toString();
                                    File stuDir = new File(uploadDir + File.separator + stuid);
                                    if (!stuDir.exists()) {
                                        stuDir.mkdir();
                                    }
                                    uploadDir = stuDir.getPath();
                                }
                            }
                        } else {
                            String itemname = item.getName();
                            if (itemname == null || itemname.equals("")) {
                            } else {
                                String filename = FilenameUtils.getName(itemname);
                                File f = new File(uploadDir + File.separator + filename);
                                String[] split = f.getPath().split(Pattern.quote(File.separator) + "upload"
                                        + Pattern.quote(File.separator));
                                String save = split[split.length - 1];
                                if (assignmentId != null && !assignmentId.equals("")) {
                                    if (stuid != null && !stuid.equals("")) {

                                    } else {
                                        Assignment assignment = new AssignmentFacade()
                                                .findAssignment(Integer.parseInt(assignmentId));
                                        assignment.setUrl(save);
                                        new AssignmentFacade().updateAssignment(assignment);
                                    }
                                }
                                item.write(f);
                                messageBean.setStatus(0);
                                messageBean.setMessage("File " + f.getName() + " sucessfuly uploaded");

                            }
                        }
                    }
                }

                gson.toJson(messageBean, out);
            } catch (Exception ex) {
                messageBean.setStatus(1);
                messageBean.setMessage(ex.getMessage());
                gson.toJson(messageBean, out);
            }

        }
    } catch (Exception ex) {
        Logger.getLogger(AjaxUpload.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:de.thischwa.pmcms.gui.listener.ListenerImageBulkImport.java

@Override
public void widgetSelected(SelectionEvent e) {
    final Shell shell = e.display.getActiveShell();
    File galleryDirectory = PoPathInfo.getSiteGalleryDirectory(this.gallery);
    FileDialog fileDialog = new FileDialog(shell, SWT.MULTI);
    fileDialog.setText("Select one or more images ...");
    List<String> exts = new ArrayList<String>();
    for (String extension : InitializationManager.getAllowedImageExtensions()) {
        exts.add("*." + extension);
    }//from ww w.jav a 2 s.  com
    exts.add(0, StringUtils.join(exts.iterator(), ';'));
    fileDialog.setFilterExtensions(exts.toArray(new String[exts.size()]));
    if (galleryDirectory.exists())
        fileDialog.setFilterPath(galleryDirectory.getAbsolutePath());
    if (fileDialog.open() != null) {
        // collecting files
        List<File> filesToCopy = new ArrayList<File>(fileDialog.getFileNames().length);
        for (String fileName : fileDialog.getFileNames())
            filesToCopy.add(new File(fileDialog.getFilterPath(), fileName));
        List<File> copiedFiles = null;
        if (!(new File(fileDialog.getFilterPath()).getAbsolutePath()
                .startsWith(galleryDirectory.getAbsolutePath()))) {
            try {
                copiedFiles = FileTool.copyToDirectoryUnique(filesToCopy, galleryDirectory);
            } catch (IOException e1) {
                MessageBox mb = new MessageBox(shell, SWT.ICON_ERROR | SWT.OK);
                mb.setText(LabelHolder.get("popup.error")); //$NON-NLS-1$
                mb.setMessage("Error while copying files:\n" + e1.getStackTrace().toString());
                mb.open();
                return;
            }
        } else {
            logger.debug("Image files are not copied, because they are in the right directory!");
            copiedFiles = filesToCopy;
        }

        SiteHolder siteHolder = InitializationManager.getBean(SiteHolder.class);
        for (File file : copiedFiles) {
            Image image = new Image();
            image.setParent(this.gallery);
            image.setFileName(FilenameUtils.getName(file.getAbsolutePath()));
            siteHolder.mark(image);
            this.gallery.add(image);
            logger.debug("Image added: ".concat(image.getDecorationString()));
        }

        TreeViewManager treeViewManager = InitializationManager.getBean(TreeViewManager.class);
        treeViewManager.fillAndExpands(this.gallery);
        BrowserManager browserManager = InitializationManager.getBean(BrowserManager.class);
        browserManager.view(this.gallery, ViewMode.PREVIEW);
        try {
            SitePersister.write(siteHolder.getSite());
        } catch (IOException e2) {
            throw new RuntimeException(e2);
        }
    }
}

From source file:com.amalto.core.servlet.LogViewerServlet.java

private void downloadLogFile(HttpServletResponse response) throws IOException {
    String filename = file.getAbsolutePath();
    filename = FilenameUtils.getName(filename);
    response.setContentType("text/x-log; name=\"" + filename + '"'); //$NON-NLS-1$
    response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + '"'); //$NON-NLS-1$ //$NON-NLS-2$
    FileInputStream fis = new FileInputStream(file);
    try {/*from   w  w  w. j  av  a  2  s. co  m*/
        OutputStream responseOutputStream = response.getOutputStream();
        IOUtils.copyLarge(fis, responseOutputStream);
        responseOutputStream.close();
    } finally {
        try {
            fis.close();
        } catch (Exception e) {
            // ignore it
        }
    }
}

From source file:com.jaeksoft.searchlib.web.PushServlet.java

@Override
protected void doRequest(ServletTransaction transaction) throws ServletException {
    try {/* www . j av a2  s  .  c o  m*/

        User user = transaction.getLoggedUser();
        if (user != null && !user.isAdmin())
            throw new SearchLibException("Not permitted");

        Client client = transaction.getClient();

        String cmd = transaction.getParameterString("cmd");
        if (CALL_XML_CMD_INIT.equals(cmd)) {
            transaction.addXmlResponse(CALL_XML_KEY_CMD, CALL_XML_CMD_INIT);
            ClientCatalog.receive_init(client);
            transaction.addXmlResponse(XML_CALL_KEY_STATUS, XML_CALL_KEY_STATUS_OK);
            return;
        }
        if (CALL_XML_CMD_SWITCH.equals(cmd)) {
            transaction.addXmlResponse(CALL_XML_KEY_CMD, CALL_XML_CMD_SWITCH);
            ClientCatalog.receive_switch(transaction.getWebApp(), client);
            transaction.addXmlResponse(XML_CALL_KEY_STATUS, XML_CALL_KEY_STATUS_OK);
            return;
        }
        if (CALL_XML_CMD_MERGE.equals(cmd)) {
            transaction.addXmlResponse(CALL_XML_KEY_CMD, CALL_XML_CMD_MERGE);
            ClientCatalog.receive_merge(transaction.getWebApp(), client);
            transaction.addXmlResponse(XML_CALL_KEY_STATUS, XML_CALL_KEY_STATUS_OK);
            return;
        }
        if (CALL_XML_CMD_ABORT.equals(cmd)) {
            transaction.addXmlResponse(CALL_XML_KEY_CMD, CALL_XML_CMD_ABORT);
            ClientCatalog.receive_abort(client);
            transaction.addXmlResponse(XML_CALL_KEY_STATUS, XML_CALL_KEY_STATUS_OK);
            return;
        }
        String filePath = transaction.getParameterString(CALL_XML_CMD_FILEPATH);
        Long lastModified = transaction.getParameterLong("lastModified", 0L);
        Long length = transaction.getParameterLong("length", 0L);
        if (CALL_XML_CMD_EXISTS.equals(cmd)) {
            transaction.addXmlResponse(CALL_XML_KEY_CMD, CALL_XML_CMD_EXISTS);
            boolean exist = ClientCatalog.receive_file_exists(client, filePath, lastModified, length);
            transaction.addXmlResponse(CALL_XML_KEY_EXISTS, Boolean.toString(exist));
            transaction.addXmlResponse(XML_CALL_KEY_STATUS, XML_CALL_KEY_STATUS_OK);
            return;
        }
        transaction.addXmlResponse(CALL_XML_KEY_CMD, CALL_XML_CMD_FILEPATH);
        if (FilenameUtils.getName(filePath).startsWith(".")) {
            transaction.addXmlResponse(XML_CALL_KEY_STATUS, XML_CALL_KEY_STATUS_OK);
            return;
        }
        filePath = FileUtils.unixToSystemPath(filePath);
        if (transaction.getParameterBoolean("type", "dir", false))
            ClientCatalog.receive_dir(client, filePath);
        else
            ClientCatalog.receive_file(client, filePath, lastModified, transaction.getInputStream());
        transaction.addXmlResponse(XML_CALL_KEY_STATUS, XML_CALL_KEY_STATUS_OK);
    } catch (SearchLibException e) {
        throw new ServletException(e);
    } catch (NamingException e) {
        throw new ServletException(e);
    } catch (InterruptedException e) {
        throw new ServletException(e);
    } catch (IOException e) {
        throw new ServletException(e);
    }

}

From source file:edu.ku.brc.specify.conversion.ConversionLogger.java

/**
 * @param indexWriter/*from   w  w w.java2s.  c  o m*/
 * @param orderList
 */
protected void writeIndex(final TableWriter indexWriter, final Vector<TableWriter> orderList) {
    indexWriter.startTable();

    for (TableWriter tblWriter : orderList) {
        System.out.println(tblWriter.getTitle());

        try {
            if (tblWriter.hasLines()) {
                indexWriter.log("<A href=\"" + FilenameUtils.getName(tblWriter.getFileName()) + "\">"
                        + tblWriter.getTitle() + "</A>");
                tblWriter.close();

            } else {
                tblWriter.flush();
                tblWriter.close();

                File f = new File(tblWriter.getFileName());
                if (f.exists()) {
                    f.delete();
                }
            }

        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    indexWriter.endTable();
}

From source file:com.epam.ngb.cli.TestHttpServer.java

public void addFileRegistration(Long refId, String path, String name, Long fileId, Long fileBioId,
        BiologicalDataItemFormat format) {
    onRequest().havingMethodEqualTo(HTTP_POST)
            .havingPathEqualTo(String.format(REGISTRATION_URL, format.name().toLowerCase()))
            .havingBodyEqualTo(TestDataProvider.getRegistrationJson(refId, path, name, null)).respond()
            .withBody(TestDataProvider.getFilePayloadJson(fileId, fileBioId, format, path,
                    name == null ? FilenameUtils.getName(path) : name))
            .withStatus(HTTP_STATUS_OK);
}

From source file:de.uzk.hki.da.at.ATMetadataUpdatesMetsMods.java

@Test
public void testPres() throws JDOMException, FileNotFoundException, IOException {

    assertEquals(C.CB_PACKAGETYPE_METS, object.getPackage_type());

    SAXBuilder builder = XMLUtils.createNonvalidatingSaxBuilder();
    metsDoc = builder.build(new FileReader(ath.loadDefaultMetsFileFromPip(object.getIdentifier())));
    List<Element> elements = mh.getMetsFileElements(metsDoc);
    for (Element e : elements) {
        assertTrue(mh.getMetsHref(e).contains(preservationSystem.getUrisFile()));
        assertTrue(mh.getMimetypeInMets(e).equals(C.MIMETYPE_IMAGE_JPEG));
        assertTrue(mh.getMetsLoctype(e).equals("URL"));

        assertTrue(//from w w  w  . j a  v a2s. c o m
                ath.loadFileFromPip(object.getIdentifier(), FilenameUtils.getName(mh.getMetsHref(e))).exists());

    }
}

From source file:com.ikon.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);/*from   ww  w  .j  av  a  2 s .c  o 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 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) {
                        extractor = extClass.getClass().getCanonicalName();
                        text = RegisteredExtractors.getText(mimeType, null, is);
                    } 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("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:ca.on.oicr.pde.workflows.GATK3Workflow.java

@Override
public Map<String, SqwFile> setupFiles() {

    List<String> inputFilesList = Arrays.asList(StringUtils.split(getProperty("input_files"), ","));
    Set<String> inputFilesSet = new HashSet<>(inputFilesList);

    if (inputFilesList.size() != inputFilesSet.size()) {
        throw new RuntimeException("Duplicate files detected in input_files");
    }/*from   w w  w.j a v  a2 s  .c o  m*/

    if ((inputFilesSet.size() % 2) != 0) {
        throw new RuntimeException("Each bam should have a corresponding index");
    }

    Map<String, String> bams = new HashMap<>();
    Map<String, String> bais = new HashMap<>();
    for (String f : inputFilesSet) {
        String fileExtension = FilenameUtils.getExtension(f);
        String fileKey = FilenameUtils.removeExtension(f);
        if (null != fileExtension) {
            switch (fileExtension) {
            case "bam":
                bams.put(fileKey, f);
                break;
            case "bai":
                bais.put(fileKey, f);
                break;
            default:
                throw new RuntimeException("Unsupported input file type");
            }
        }
    }

    int id = 0;
    for (Entry<String, String> e : bams.entrySet()) {
        String key = e.getKey();
        String bamFilePath = e.getValue();

        String baiFilePath = bais.get(key);
        if (baiFilePath == null) {
            throw new RuntimeException("Missing index for " + FilenameUtils.getName(bamFilePath));
        }

        SqwFile bam = this.createFile("file_in_" + id++);
        bam.setSourcePath(bamFilePath);
        bam.setType("application/bam");
        bam.setIsInput(true);

        SqwFile bai = this.createFile("file_in_" + id++);
        bai.setSourcePath(baiFilePath);
        bai.setType("application/bam-index");
        bai.setIsInput(true);

        //FIXME: this seems to work for now, it would be better to be able to set the provisionedPath as
        //bai.getProvisionedPath != bai.getOutputPath ...
        //at least with seqware 1.1.0, setting output path changes where the output file will be stored,
        //but the commonly used get provisioned path will return the incorrect path to the file
        bai.setOutputPath(FilenameUtils.getPath(bam.getProvisionedPath()));

        inputBamFiles.add(bam.getProvisionedPath());
    }

    return this.getFiles();
}

From source file:com.GTDF.server.FileUploadServlet.java

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String rootDirectory = getServletConfig().getInitParameter("TRANSFORM_HOME");
    String workDirectory = getServletConfig().getInitParameter("TRANSFORM_DIR");
    String prefixDirectory = "";
    boolean writeToFile = true;
    String returnOKMessage = "OK";
    String username = "";
    String authResult = "";

    boolean isMultipart = ServletFileUpload.isMultipartContent(request);

    PrintWriter out = response.getWriter();

    // Create a factory for disk-based file items 
    if (isMultipart) {

        // We are uploading a file (deletes are performed by non multipart requests) 
        FileItemFactory factory = new DiskFileItemFactory();

        // Create a new file upload handler 
        ServletFileUpload upload = new ServletFileUpload(factory);
        // Parse the request 
        try {/*w ww.j a  v a 2  s .co  m*/

            List items = upload.parseRequest(request);

            // Process the uploaded items 
            Iterator iter = items.iterator();
            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();
                if (item.isFormField()) {

                    // Hidden field containing username - check authorization
                    if (item.getFieldName().equals("username")) {
                        username = item.getString();
                        String wikiDb = getServletConfig().getInitParameter("WIKIDB");
                        String wikiDbUser = getServletConfig().getInitParameter("WIKIDB_USER");
                        String wikiDbPassword = getServletConfig().getInitParameter("WIKIDB_PASSWORD");
                        String wikiNoAuth = getServletConfig().getInitParameter("NOAUTH"); // v1.5 Check parameter NOAUTH
                        WikiUserImpl wikiUser = new WikiUserImpl();
                        authResult = wikiUser.wikiUserVerifyDb(username, wikiDb, wikiDbUser, wikiDbPassword,
                                wikiNoAuth);
                        if (authResult != "LOGGED") {
                            out.print(authResult);
                            return;
                        } else
                            new File(rootDirectory + workDirectory + '/' + username).mkdirs();
                    }

                    // Hidden field containing file prefix to create subdirectory
                    if (item.getFieldName().equals("prefix")) {
                        prefixDirectory = item.getString();
                        new File(rootDirectory + workDirectory + '/' + username + '/' + prefixDirectory)
                                .mkdirs();
                        prefixDirectory += '/';
                    }
                } else {
                    if (writeToFile) {
                        String fileName = item.getName();
                        if (fileName != null && !fileName.equals("")) {
                            fileName = FilenameUtils.getName(fileName);
                            File uploadedFile = new File(rootDirectory + workDirectory + '/' + username + '/'
                                    + prefixDirectory + fileName);
                            try {
                                item.write(uploadedFile);
                                String hostedOn = getServletConfig().getInitParameter("HOSTED_ON");
                                out.print("Infile at: " + hostedOn + workDirectory + '/' + username + '/'
                                        + prefixDirectory + fileName);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    } else {
                    }
                }
            }
        } catch (FileUploadException e) {
            e.printStackTrace();
        }
    } else {

        //Process a request to delete a file 
        String[] paramValues = request.getParameterValues("uploadFormElement");
        for (int i = 0; i < paramValues.length; i++) {
            String fileName = FilenameUtils.getName(paramValues[i]);
            File deleteFile = new File(rootDirectory + workDirectory + fileName);
            if (deleteFile.delete()) {
                out.print(returnOKMessage);
            }
        }
    }

}