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:io.github.retz.web.ClientHelper.java

public static void getWholeBinaryFile(Client c, int id, String path, String output) throws IOException {
    String fullpath = FilenameUtils.concat(output, FilenameUtils.getName(path));
    LOG.info("Saving {} as {}", path, fullpath);
    try (FileOutputStream out = new FileOutputStream(fullpath)) {
        c.getBinaryFile(id, path, out);/*from w  w  w.ja va  2 s  .c o  m*/
    }
}

From source file:com.joyent.manta.client.multipart.ServerSideMultipartManager.java

@Override
public Stream<MantaMultipartUpload> listInProgress() throws IOException {
    final String uploadsPath = uploadsPath();

    Stream<MantaMultipartUpload> stream = mantaClient.listObjects(uploadsPath).map(mantaObject -> {
        try {/*www .j  a va  2 s.c om*/
            return mantaClient.listObjects(mantaObject.getPath()).map(item -> {
                final String objectName = FilenameUtils.getName(item.getPath());
                final UUID id = UUID.fromString(objectName);

                // We don't know the final object name. The server will implement
                // this as a feature in the future.

                return new ServerSideMultipartUpload(id, null, uuidPrefixedPath(id));
            }).collect(Collectors.toSet());
        } catch (IOException e) {
            throw new UncheckedIOException(e);
        }
    }).flatMap(Collection::stream);

    danglingStreams.add(stream);

    return stream;
}

From source file:edu.ku.brc.specify.tasks.subpane.wb.GridTableModel.java

public Object getValueAt(int row, int column) {
    if (row < 0 || row >= getRowCount() || column < 0 || column >= getColumnCount()) {
        return null;
    }/*from  w ww .ja va2 s. com*/

    // if this is the image column...
    if (headers.get(column) == imageMappingItem) {
        WorkbenchRow rowObj = getWorkbench().getRow(row);
        Set<WorkbenchRowImage> images = rowObj.getWorkbenchRowImages();
        if (images != null && images.size() > 0) {
            StringBuilder sb = new StringBuilder();
            for (WorkbenchRowImage rowImg : images) {
                String fullPath = rowImg.getCardImageFullPath();
                String filename = FilenameUtils.getName(fullPath);
                sb.append(filename + "; ");
            }
            sb.delete(sb.length() - 2, sb.length());
            return sb.toString();
        }
        // else
        return "";
    }

    if (headers.get(column) == sgrHeading) {
        SGRPluginImpl sgr = (SGRPluginImpl) workbenchPaneSS.getPlugin(SGRPluginImpl.class);
        if (sgr != null) {
            WorkbenchColorizer colorizer = sgr.getColorizer();
            Float score = colorizer.getScoreForRow(workbenchPaneSS.getWorkbench().getRow(row));
            return score != null ? String.format("%1$.2f", score) : "";
        }
        return 0;
    }

    // otherwise...
    if (getRowCount() > row) {
        return getWorkbench().getWorkbenchRowsAsList().get(row).getData(column);
    }

    return null;
}

From source file:fr.inrialpes.exmo.align.service.HTTPTransport.java

/**
 * Starts a HTTP server to given port./*from ww w  .  j a v a  2  s. c o m*/
 *
 * @param params: the parameters of the connection, including HTTP port and host
 * @param manager: the manager which will deal with connections
 * @param serv: the set of services to be listening on this connection
 * @throws AServException when something goes wrong (e.g., socket already in use)
 */
public void init(Properties params, AServProtocolManager manager, Vector<AlignmentServiceProfile> serv)
        throws AServException {
    this.manager = manager;
    services = serv;
    tcpPort = Integer.parseInt(params.getProperty("http"));
    tcpHost = params.getProperty("host");

    // ********************************************************************
    // JE: Jetty implementation
    server = new Server(tcpPort);

    // The handler deals with the request
    // most of its work is to deal with large content sent in specific ways 
    Handler handler = new AbstractHandler() {
        public void handle(String String, Request baseRequest, HttpServletRequest request,
                HttpServletResponse response) throws IOException, ServletException {
            String method = request.getMethod();
            String uri = request.getPathInfo();
            Properties params = new Properties();
            try {
                decodeParams(request.getQueryString(), params);
            } catch (Exception ex) {
                logger.debug("IGNORED EXCEPTION: {}", ex);
            }
            ;
            // I do not decode them here because it is useless
            // See below how it is done.
            Properties header = new Properties();
            Enumeration<String> headerNames = request.getHeaderNames();
            while (headerNames.hasMoreElements()) {
                String headerName = headerNames.nextElement();
                header.setProperty(headerName, request.getHeader(headerName));
            }

            // Get the content if any
            // This is supposed to be only an uploaded file
            // Note that this could be made more uniform 
            // with the text/xml part stored in a file as well.
            String mimetype = request.getContentType();
            // Multi part: the content provided by an upload HTML form
            if (mimetype != null && mimetype.startsWith("multipart/form-data")) {
                try {
                    //if ( !ServletFileUpload.isMultipartContent( request ) ) {
                    //   logger.debug( "Does not detect multipart" );
                    //}
                    DiskFileItemFactory factory = new DiskFileItemFactory();
                    File tempDir = new File(System.getProperty("java.io.tmpdir"));
                    factory.setRepository(tempDir);
                    ServletFileUpload upload = new ServletFileUpload(factory);
                    List<FileItem> items = upload.parseRequest(request);
                    for (FileItem fi : items) {
                        if (fi.isFormField()) {
                            logger.trace("  >> {} = {}", fi.getFieldName(), fi.getString());
                            params.setProperty(fi.getFieldName(), fi.getString());
                        } else {
                            logger.trace("  >> {} : {}", fi.getName(), fi.getSize());
                            logger.trace("  Stored at {}", fi.getName(), fi.getSize());
                            try {
                                // FilenameUtils.getName() needed for Internet Explorer problem
                                File uploadedFile = new File(tempDir, FilenameUtils.getName(fi.getName()));
                                fi.write(uploadedFile);
                                params.setProperty("filename", uploadedFile.toString());
                                params.setProperty("todiscard", "true");
                            } catch (Exception ex) {
                                logger.warn("Cannot load file", ex);
                            }
                            // Another solution is to run this in 
                            /*
                              InputStream uploadedStream = item.getInputStream();
                              ...
                              uploadedStream.close();
                            */
                        }
                    }
                    ;
                } catch (FileUploadException fuex) {
                    logger.trace("Upload Error", fuex);
                }
            } else if (mimetype != null && mimetype.startsWith("text/xml")) {
                // Most likely Web service request (REST through POST)
                int length = request.getContentLength();
                if (length > 0) {
                    char[] mess = new char[length + 1];
                    try {
                        new BufferedReader(new InputStreamReader(request.getInputStream())).read(mess, 0,
                                length);
                    } catch (Exception e) {
                        logger.debug("IGNORED Exception", e);
                    }
                    params.setProperty("content", new String(mess));
                }
                // File attached to SOAP messages
            } else if (mimetype != null && mimetype.startsWith("application/octet-stream")) {
                File alignFile = new File(File.separator + "tmp" + File.separator + newId() + "XXX.rdf");
                // check if file already exists - and overwrite if necessary.
                if (alignFile.exists())
                    alignFile.delete();
                FileOutputStream fos = new FileOutputStream(alignFile);
                InputStream is = request.getInputStream();

                try {
                    byte[] buffer = new byte[4096];
                    int bytes = 0;
                    while (true) {
                        bytes = is.read(buffer);
                        if (bytes < 0)
                            break;
                        fos.write(buffer, 0, bytes);
                    }
                } catch (Exception e) {
                } finally {
                    fos.flush();
                    fos.close();
                }
                is.close();
                params.setProperty("content", "");
                params.setProperty("filename", alignFile.getAbsolutePath());
            }

            // Get the answer (HTTP)
            HTTPResponse r = serve(uri, method, header, params);

            // Return it
            response.setContentType(r.getContentType());
            response.setStatus(HttpServletResponse.SC_OK);
            response.getWriter().println(r.getData());
            ((Request) request).setHandled(true);
        }
    };
    server.setHandler(handler);

    // Common part
    try {
        server.start();
    } catch (Exception e) {
        throw new AServException("Cannot launch HTTP Server", e);
    }
    //server.join();

    // ********************************************************************
    //if ( params.getProperty( "wsdl" ) != null ){
    //    wsmanager = new WSAServProfile();
    //    if ( wsmanager != null ) wsmanager.init( params, manager );
    //}
    //if ( params.getProperty( "http" ) != null ){
    //    htmanager = new HTMLAServProfile();
    //    if ( htmanager != null ) htmanager.init( params, manager );
    //}
    myId = "LocalHTMLInterface";
    serverId = manager.serverURL();
    logger.info("Launched on {}/html/", serverId);
    localId = 0;
}

From source file:com.alibaba.otter.node.etl.common.pipe.impl.http.archive.ArchiveBean.java

/**
 * /*from   w  w w.ja  v  a 2  s. c  om*/
 */
@SuppressWarnings("resource")
private boolean doPack(final File targetArchiveFile, List<FileData> fileDatas,
        final ArchiveRetriverCallback<FileData> callback) {
    // ?
    if (true == targetArchiveFile.exists() && false == NioUtils.delete(targetArchiveFile, 3)) {
        throw new ArchiveException(
                String.format("[%s] exist and delete failed", targetArchiveFile.getAbsolutePath()));
    }

    boolean exist = false;
    ZipOutputStream zipOut = null;
    Set<String> entryNames = new HashSet<String>();
    BlockingQueue<Future<ArchiveEntry>> queue = new LinkedBlockingQueue<Future<ArchiveEntry>>(); // ?
    ExecutorCompletionService completionService = new ExecutorCompletionService(executor, queue);

    final File targetDir = new File(targetArchiveFile.getParentFile(),
            FilenameUtils.getBaseName(targetArchiveFile.getPath()));
    try {
        // 
        FileUtils.forceMkdir(targetDir);

        zipOut = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(targetArchiveFile)));
        zipOut.setLevel(Deflater.BEST_SPEED);
        // ??
        for (final FileData fileData : fileDatas) {
            if (fileData.getEventType().isDelete()) {
                continue; // delete??
            }

            String namespace = fileData.getNameSpace();
            String path = fileData.getPath();
            boolean isLocal = StringUtils.isBlank(namespace);
            String entryName = null;
            if (true == isLocal) {
                entryName = FilenameUtils.getPath(path) + FilenameUtils.getName(path);
            } else {
                entryName = namespace + File.separator + path;
            }

            // ????
            if (entryNames.contains(entryName) == false) {
                entryNames.add(entryName);
            } else {
                continue;
            }

            final String name = entryName;
            if (true == isLocal && !useLocalFileMutliThread) {
                // ??
                queue.add(new DummyFuture(new ArchiveEntry(name, callback.retrive(fileData))));
            } else {
                completionService.submit(new Callable<ArchiveEntry>() {

                    public ArchiveEntry call() throws Exception {
                        // ??
                        InputStream input = null;
                        OutputStream output = null;
                        try {
                            input = callback.retrive(fileData);

                            if (input instanceof LazyFileInputStream) {
                                input = ((LazyFileInputStream) input).getInputSteam();// ?stream
                            }

                            if (input != null) {
                                File tmp = new File(targetDir, name);
                                NioUtils.create(tmp.getParentFile(), false, 3);// ?
                                output = new FileOutputStream(tmp);
                                NioUtils.copy(input, output);// ?
                                return new ArchiveEntry(name, new File(targetDir, name));
                            } else {
                                return new ArchiveEntry(name);
                            }
                        } finally {
                            IOUtils.closeQuietly(input);
                            IOUtils.closeQuietly(output);
                        }
                    }
                });
            }
        }

        for (int i = 0; i < entryNames.size(); i++) {
            // ?
            ArchiveEntry input = null;
            InputStream stream = null;
            try {
                input = queue.take().get();
                if (input == null) {
                    continue;
                }

                stream = input.getStream();
                if (stream == null) {
                    continue;
                }

                if (stream instanceof LazyFileInputStream) {
                    stream = ((LazyFileInputStream) stream).getInputSteam();// ?stream
                }

                exist = true;
                zipOut.putNextEntry(new ZipEntry(input.getName()));
                NioUtils.copy(stream, zipOut);// ?
                zipOut.closeEntry();
            } finally {
                IOUtils.closeQuietly(stream);
            }
        }

        if (exist) {
            zipOut.finish();
        }
    } catch (Exception e) {
        throw new ArchiveException(e);
    } finally {
        IOUtils.closeQuietly(zipOut);
        try {
            FileUtils.deleteDirectory(targetDir);// 
        } catch (IOException e) {
            // ignore
        }
    }

    return exist;
}

From source file:com.compomics.colims.distributed.playground.AnnotatedSpectraParser.java

/**
 * Parse APL File Paths. Put all the apl files to be used in aplFilePaths list.
 *
 * @param andromedaDirectory//ww  w .  ja  va2s . c  om
 * @throws FileNotFoundException
 * @throws IOException
 */
private void parseAplFilePaths(Path andromedaDirectory) throws FileNotFoundException, IOException {
    /**
     * Parse the apl summary file 'aplfiles.txt' to extract the apl spectrum file paths, the spectrum parameter file paths
     * and the mass analyzer and fragmentation type.
     */
    if (!Files.exists(andromedaDirectory)) {
        throw new FileNotFoundException(
                "The andromeda directory " + andromedaDirectory.toString() + " could not be found.");
    }

    Path aplSummaryPath = Paths.get(andromedaDirectory.toString(), MaxQuantConstants.APL_SUMMARY_FILE.value());
    if (!Files.exists(aplSummaryPath)) {
        throw new FileNotFoundException(
                "The apl summary file " + MaxQuantConstants.APL_SUMMARY_FILE + " could not be found.");
    }
    Map<String, String> allAplFilePaths = ParseUtils.parseParameters(aplSummaryPath,
            MaxQuantConstants.PARAM_TAB_DELIMITER.value());
    allAplFilePaths.entrySet().stream().forEach(entry -> {
        //use paths relative to the andromeda directory
        Path relativeAplfilePath = Paths.get(andromedaDirectory.toString(),
                FilenameUtils.getName(entry.getKey()));
        Path relativeSpectrumParametersfilePath = Paths.get(andromedaDirectory.toString(),
                FilenameUtils.getName(entry.getValue()));
        this.aplFilePaths.put(relativeAplfilePath, relativeSpectrumParametersfilePath);
    });

}

From source file:com.ikon.servlet.admin.CronTabServlet.java

@Override
@SuppressWarnings("unchecked")
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    log.debug("doPost({}, {})", request, response);
    request.setCharacterEncoding("UTF-8");
    String action = "";
    String userId = request.getRemoteUser();
    updateSessionManager(request);//w  w  w  .  ja v a 2  s. co  m

    try {
        if (ServletFileUpload.isMultipartContent(request)) {
            InputStream is = null;
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            List<FileItem> items = upload.parseRequest(request);
            CronTab ct = new CronTab();

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

                if (item.isFormField()) {
                    if (item.getFieldName().equals("action")) {
                        action = item.getString("UTF-8");
                    } else if (item.getFieldName().equals("ct_id")) {
                        ct.setId(Integer.parseInt(item.getString("UTF-8")));
                    } else if (item.getFieldName().equals("ct_name")) {
                        ct.setName(item.getString("UTF-8"));
                    } else if (item.getFieldName().equals("ct_mail")) {
                        ct.setMail(item.getString("UTF-8"));
                    } else if (item.getFieldName().equals("ct_expression")) {
                        ct.setExpression(item.getString("UTF-8"));
                    } else if (item.getFieldName().equals("ct_active")) {
                        ct.setActive(true);
                    }
                } else {
                    is = item.getInputStream();
                    ct.setFileName(FilenameUtils.getName(item.getName()));
                    ct.setFileContent(SecureStore.b64Encode(IOUtils.toByteArray(is)));
                    ct.setFileMime(MimeTypeConfig.mimeTypes.getContentType(item.getName()));
                    is.close();
                }
            }

            if (action.equals("create")) {
                CronTabDAO.create(ct);

                // Activity log
                UserActivity.log(userId, "ADMIN_CRONTAB_CREATE", null, null, ct.toString());
                list(request, response);
            } else if (action.equals("edit")) {
                CronTabDAO.update(ct);

                // Activity log
                UserActivity.log(userId, "ADMIN_CRONTAB_EDIT", Long.toString(ct.getId()), null, ct.toString());
                list(request, response);
            } else if (action.equals("delete")) {
                CronTabDAO.delete(ct.getId());

                // Activity log
                UserActivity.log(userId, "ADMIN_CRONTAB_DELETE", Long.toString(ct.getId()), null, null);
                list(request, response);
            }
        }
    } catch (DatabaseException e) {
        log.error(e.getMessage(), e);
        sendErrorRedirect(request, response, e);
    } catch (FileUploadException e) {
        log.error(e.getMessage(), e);
        sendErrorRedirect(request, response, e);
    }
}

From source file:ch.entwine.weblounge.dispatcher.impl.handler.PreviewRequestHandlerImpl.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>/*from www  .j a v  a2 s  . c  o 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;

    // This request handler can only be used with the prefix
    if (!path.startsWith(URI_PREFIX))
        return false;

    // 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 previews. 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 resourceURI = null;
    Resource<?> resource = null;
    try {
        String id = null;
        String imagePath = null;

        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);
        }

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

    // Agree to serve the preview
    logger.debug("Preview 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 resource 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 resource {} denied for user {}", resourceURI, user);
        DispatchUtils.sendAccessDenied(request, response);
        return true;
    }

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

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

    // Find a resource preview generator
    PreviewGenerator previewGenerator = null;
    synchronized (previewGenerators) {
        for (PreviewGenerator generator : previewGenerators) {
            if (generator.supports(resource)) {
                previewGenerator = generator;
                break;
            }
        }
    }

    // If we did not find a preview generator, we need to let go
    if (previewGenerator == null) {
        logger.debug("Unable to generate preview for {} since no suitable preview generator is available",
                resource);
        DispatchUtils.sendServiceUnavailable(request, response);
        return true;
    }

    // Extract the image style
    ImageStyle style = null;
    String styleId = StringUtils.trimToNull(request.getParameter(OPT_IMAGE_STYLE));
    if (styleId != null) {
        style = ImageStyleUtils.findStyle(styleId, site);
        if (style == null) {
            DispatchUtils.sendBadRequest("Image style '" + styleId + "' not found", request, response);
            return true;
        }
    }

    // Get the path to the preview image
    File previewFile = ImageStyleUtils.getScaledFile(resource, language, style);

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

    // Load the image contents from the repository
    ResourceContent resourceContents = resource.getContent(language);

    // Add mime type header
    String contentType = resourceContents.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);

    // Write the image back to the client
    InputStream previewInputStream = null;
    try {
        if (previewFile.isFile()
                && previewFile.lastModified() >= resourceContents.getCreationDate().getTime()) {
            previewInputStream = new FileInputStream(previewFile);
        } else {
            previewInputStream = createPreview(request, response, resource, language, style, previewGenerator,
                    previewFile, contentRepository);
        }

        if (previewInputStream == null) {
            // Assuming that createPreview() is setting the response header in the
            // case of failure
            return true;
        }

        // Add last modified header
        response.setDateHeader("Last-Modified", previewFile.lastModified());
        response.setHeader("ETag", ResourceUtils.getETagValue(previewFile.lastModified()));
        response.setHeader("Content-Disposition", "inline; filename=" + previewFile.getName());
        response.setHeader("Content-Length", Long.toString(previewFile.length()));
        previewInputStream = new FileInputStream(previewFile);
        IOUtils.copy(previewInputStream, response.getOutputStream());
        response.getOutputStream().flush();
        return true;
    } catch (EOFException e) {
        logger.debug("Error writing image '{}' back to client: connection closed by client", resource);
        return true;
    } catch (IOException e) {
        DispatchUtils.sendInternalError(request, response);
        if (RequestUtils.isCausedByClient(e))
            return true;
        logger.error("Error sending image '{}' to the client: {}", resourceURI, e.getMessage());
        return true;
    } catch (Throwable t) {
        logger.error("Error creating scaled image '{}': {}", resourceURI, t.getMessage());
        DispatchUtils.sendInternalError(request, response);
        return true;
    } finally {
        IOUtils.closeQuietly(previewInputStream);
    }
}

From source file:jp.co.opentone.bsol.linkbinder.view.correspon.attachment.AttachmentUploadActionTest.java

private String getExpectedFileName(UploadedFile file) {
    String result;//from  www. j  a va 2  s .  c o m
    // TODO ?
    //        if (file.getName().indexOf('/') != -1) {
    //            result = FilenameUtils.getName(file.getName());
    //        } else if (file.getName().indexOf('\\') != -1) {
    //            result = FilenameUtils.getName(file.getName());
    //        } else {
    //            result = file.getName();
    //        }
    if (file.getFilename().indexOf('/') != -1) {
        result = FilenameUtils.getName(file.getFilename());
    } else if (file.getFilename().indexOf('\\') != -1) {
        result = FilenameUtils.getName(file.getFilename());
    } else {
        result = file.getFilename();
    }
    String regex = SystemConfig.getValue("server.file.name.regex");
    String replacement = SystemConfig.getValue("server.file.name.replacement");

    System.out.printf("regex=%s, rep=%s, result=%s%n", regex, replacement,
            result.replaceAll(regex, replacement));

    return result.replaceAll(regex, replacement);
}

From source file:controllers.CodeApp.java

@IsAllowed(Operation.READ)
public static Result openFile(String userName, String projectName, String revision, String path)
        throws Exception {
    byte[] raw = RepositoryService.getFileAsRaw(userName, projectName, revision, path);

    if (raw == null) {
        return notFound(ErrorViews.NotFound.render("error.notfound"));
    }/*  w w  w.j av a  2  s . co m*/

    return ok(raw).as(FileUtil.detectMediaType(raw, FilenameUtils.getName(path)).toString());
}