2 * Copyright (C) 2007-2012 Argeo GmbH
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
16 package org
.argeo
.eclipse
.ui
.specific
;
19 import java
.io
.IOException
;
21 import javax
.servlet
.ServletException
;
22 import javax
.servlet
.http
.HttpServletRequest
;
23 import javax
.servlet
.http
.HttpServletResponse
;
25 import org
.apache
.commons
.io
.FileUtils
;
26 import org
.argeo
.ArgeoException
;
27 import org
.eclipse
.rap
.rwt
.service
.ServiceHandler
;
30 * Basic Default service handler that retrieves a file on the server file system
31 * using its absolute path and forwards it to the end user browser. Rap
34 * Clients might extend to provide context specific services (to open files from
35 * a JCR repository for instance)
37 public class OpenFileService
implements ServiceHandler
{
38 public final static String PARAM_FILE_NAME
= "param.fileName";
39 public final static String PARAM_FILE_URI
= "param.fileURI";
41 public final static String SCHEME_HOST_SEPARATOR
= "://";
42 public final static String FILE_SCHEME
= "file";
44 public OpenFileService() {
47 public void service(HttpServletRequest request
, HttpServletResponse response
)
48 throws IOException
, ServletException
{
49 String fileName
= request
.getParameter(PARAM_FILE_NAME
);
50 String uri
= request
.getParameter(PARAM_FILE_URI
);
53 response
.setContentType("application/octet-stream");
54 response
.setContentLength((int) getFileLength(uri
));
55 if (fileName
== null || "".equals(fileName
.trim()))
56 fileName
= getFileName(uri
);
57 String contentDisposition
= "attachment; filename=\"" + fileName
+ "\"";
58 response
.setHeader("Content-Disposition", contentDisposition
);
60 response
.getOutputStream().write(getFileAsByteArray(uri
));
61 // FileUtils.readFileToByteArray(new File(path))
64 protected byte[] getFileAsByteArray(String uri
) {
65 if (uri
.startsWith(FILE_SCHEME
)) {
67 return FileUtils
.readFileToByteArray(new File(
68 getFilePathFromUri(uri
)));
69 } catch (IOException ioe
) {
70 throw new ArgeoException("Error while getting the file at "
77 protected long getFileLength(String uri
) {
78 if (uri
.startsWith(FILE_SCHEME
)) {
79 return new File(getFilePathFromUri(uri
)).length();
84 protected String
getFileName(String uri
) {
85 if (uri
.startsWith(FILE_SCHEME
)) {
86 return new File(getFilePathFromUri(uri
)).getName();
91 private String
getFilePathFromUri(String uri
) {
92 return uri
.substring((FILE_SCHEME
+ SCHEME_HOST_SEPARATOR
).length());