use of org.apache.commons.fileupload.FileItem in project felix by apache.
the class WebConsoleUtil method getParameter.
/**
* An utility method, that is used to filter out simple parameter from file
* parameter when multipart transfer encoding is used.
*
* This method processes the request and sets a request attribute
* {@link AbstractWebConsolePlugin#ATTR_FILEUPLOAD}. The attribute value is a {@link Map}
* where the key is a String specifying the field name and the value
* is a {@link org.apache.commons.fileupload.FileItem}.
*
* @param request the HTTP request coming from the user
* @param name the name of the parameter
* @return if not multipart transfer encoding is used - the value is the
* parameter value or <code>null</code> if not set. If multipart is used,
* and the specified parameter is field - then the value of the parameter
* is returned.
*/
public static final String getParameter(HttpServletRequest request, String name) {
// just get the parameter if not a multipart/form-data POST
if (!FileUploadBase.isMultipartContent(new ServletRequestContext(request))) {
return request.getParameter(name);
}
// check, whether we already have the parameters
Map params = (Map) request.getAttribute(AbstractWebConsolePlugin.ATTR_FILEUPLOAD);
if (params == null) {
// parameters not read yet, read now
// Create a factory for disk-based file items
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(256000);
// See https://issues.apache.org/jira/browse/FELIX-4660
final Object repo = request.getAttribute(AbstractWebConsolePlugin.ATTR_FILEUPLOAD_REPO);
if (repo instanceof File) {
factory.setRepository((File) repo);
}
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setSizeMax(-1);
// Parse the request
params = new HashMap();
try {
List items = upload.parseRequest(request);
for (Iterator fiter = items.iterator(); fiter.hasNext(); ) {
FileItem fi = (FileItem) fiter.next();
FileItem[] current = (FileItem[]) params.get(fi.getFieldName());
if (current == null) {
current = new FileItem[] { fi };
} else {
FileItem[] newCurrent = new FileItem[current.length + 1];
System.arraycopy(current, 0, newCurrent, 0, current.length);
newCurrent[current.length] = fi;
current = newCurrent;
}
params.put(fi.getFieldName(), current);
}
} catch (FileUploadException fue) {
// TODO: log
}
request.setAttribute(AbstractWebConsolePlugin.ATTR_FILEUPLOAD, params);
}
FileItem[] param = (FileItem[]) params.get(name);
if (param != null) {
for (int i = 0; i < param.length; i++) {
if (param[i].isFormField()) {
return param[i].getString();
}
}
}
// no valid string parameter, fail
return null;
}
use of org.apache.commons.fileupload.FileItem in project felix by apache.
the class BundlesServlet method installBundles.
// ---------- Bundle Installation handler (former InstallAction)
private void installBundles(HttpServletRequest request) throws IOException {
// get the uploaded data
final Map params = (Map) request.getAttribute(AbstractWebConsolePlugin.ATTR_FILEUPLOAD);
if (params == null) {
return;
}
final FileItem startItem = getParameter(params, FIELD_START);
final FileItem startLevelItem = getParameter(params, FIELD_STARTLEVEL);
final FileItem[] bundleItems = getFileItems(params, FIELD_BUNDLEFILE);
final FileItem refreshPackagesItem = getParameter(params, FIELD_REFRESH_PACKAGES);
// don't care any more if no bundle item
if (bundleItems.length == 0) {
return;
}
// default values
// it exists
int startLevel = -1;
String bundleLocation = "inputstream:";
// convert the start level value
if (startLevelItem != null) {
try {
startLevel = Integer.parseInt(startLevelItem.getString());
} catch (NumberFormatException nfe) {
log(LogService.LOG_INFO, "Cannot parse start level parameter " + startLevelItem + " to a number, not setting start level");
}
}
for (int i = 0; i < bundleItems.length; i++) {
final FileItem bundleItem = bundleItems[i];
// write the bundle data to a temporary file to ease processing
File tmpFile = null;
try {
// copy the data to a file for better processing
tmpFile = File.createTempFile("install", ".tmp");
bundleItem.write(tmpFile);
} catch (Exception e) {
log(LogService.LOG_ERROR, "Problem accessing uploaded bundle file: " + bundleItem.getName(), e);
// remove the tmporary file
if (tmpFile != null) {
tmpFile.delete();
tmpFile = null;
}
}
// install or update the bundle now
if (tmpFile != null) {
// start, refreshPackages just needs to exist, don't care for value
final boolean start = startItem != null;
final boolean refreshPackages = refreshPackagesItem != null;
bundleLocation = "inputstream:" + bundleItem.getName();
installBundle(bundleLocation, tmpFile, startLevel, start, refreshPackages);
}
}
}
use of org.apache.commons.fileupload.FileItem in project summer-bean by cn-cerc.
the class ImportFile method init.
public int init() throws UnsupportedEncodingException {
dataSet = new DataSet();
// 处理文件上传
DiskFileItemFactory factory = new DiskFileItemFactory();
// 设置最大缓存
factory.setSizeThreshold(5 * 1024);
ServletFileUpload upload = new ServletFileUpload(factory);
try {
uploadFiles = upload.parseRequest(request);
} catch (FileUploadException e) {
// e.printStackTrace();
uploadFiles = null;
return 0;
}
if (uploadFiles != null) {
for (int i = 0; i < uploadFiles.size(); i++) {
FileItem fileItem = uploadFiles.get(i);
if (fileItem.isFormField()) {
// 普通数据
String val = new String(fileItem.getString().getBytes("ISO-8859-1"), "UTF-8");
dataSet.getHead().setField(fileItem.getFieldName(), val);
} else {
// 文件数据
if (fileItem.getSize() > 0) {
Record rs = dataSet.append().getCurrent();
rs.setField("_FieldNo", i);
rs.setField("_FieldName", fileItem.getFieldName());
rs.setField("_ContentType", fileItem.getContentType());
rs.setField("_FileName", fileItem.getName());
rs.setField("_FileSize", fileItem.getSize());
}
}
}
}
dataSet.first();
return dataSet.size();
}
use of org.apache.commons.fileupload.FileItem in project pentaho-platform by pentaho.
the class PluggableUploadFileServlet method doPost.
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
IUploadFileServletPlugin uploaderPlugin = getUploaderBean(getDispatchKey(request), response);
if (uploaderPlugin == null) {
return;
}
// $NON-NLS-1$
response.setContentType("text/plain");
FileItem uploadItem = getFileItem(request, uploaderPlugin.getMaxFileSize());
if (uploadItem == null) {
response.getWriter().write(// $NON-NLS-1$
Messages.getInstance().getErrorString("PluggableUploadFileServlet.ERROR_0001_NO_FILE_TO_UPLOAD"));
return;
}
String path = PentahoSystem.getApplicationContext().getSolutionPath(uploaderPlugin.getTargetFolder());
File pathDir = new File(path);
// create the path if it doesn't exist yet
if (!pathDir.exists()) {
pathDir.mkdirs();
}
if (uploadItem.getSize() + getFolderSize(pathDir) > uploaderPlugin.getMaxFolderSize()) {
response.getWriter().write(// $NON-NLS-1$
Messages.getInstance().getErrorString("PluggableUploadFileServlet.ERROR_0004_FOLDER_SIZE_LIMIT_REACHED"));
return;
}
UUID id = UUIDUtil.getUUID();
String filename = id.toString() + uploaderPlugin.getFileExtension();
File outFile = new File(path, filename);
if (doesFileExists(outFile)) {
response.getWriter().write(// $NON-NLS-1$
Messages.getInstance().getErrorString("PluggableUploadFileServlet.ERROR_0002_FILE_ALREADY_EXIST"));
return;
}
InputStream fileInputStream = uploadItem.getInputStream();
FileOutputStream outputStream = new FileOutputStream(outFile);
try {
IOUtils.copy(fileInputStream, outputStream);
} finally {
if (outputStream != null) {
outputStream.close();
}
if (fileInputStream != null) {
fileInputStream.close();
}
}
uploaderPlugin.onSuccess(outFile.getAbsolutePath(), response);
} catch (Exception e) {
response.getWriter().write(Messages.getInstance().getErrorString("PluggableUploadFileServlet.ERROR_0005_UNKNOWN_ERROR", // $NON-NLS-1$
e.getLocalizedMessage()));
}
}
use of org.apache.commons.fileupload.FileItem in project iaf by ibissource.
the class RestServiceDispatcher method dispatchRequest.
/**
* Dispatch a request.
* @param uri the name of the IReceiver object
* @param method the correlationId of this request;
* @param request the <code>String</code> with the request/input
* @return String with the result of processing the <code>request</code> through the <code>serviceName</code>
*/
public String dispatchRequest(String restPath, String uri, HttpServletRequest httpServletRequest, String contentType, String request, IPipeLineSession context, HttpServletResponse httpServletResponse, ServletContext servletContext) throws ListenerException {
String method = httpServletRequest.getMethod();
if (log.isTraceEnabled())
log.trace("searching listener for uri [" + uri + "] method [" + method + "]");
String matchingPattern = findMatchingPattern(uri);
if (matchingPattern == null) {
if (uri != null && (uri.equals("/showFlowDiagram") || uri.startsWith("/showFlowDiagram/"))) {
log.info("no REST listener configured for uri [" + uri + "], so using 'no image available'");
noImageAvailable(httpServletResponse);
return "";
}
if (uri != null && (uri.equals("/showConfigurationStatus") || uri.startsWith("/showConfigurationStatus/"))) {
log.info("no REST listener configured for uri [" + uri + "], if REST listener does exist then trying to restart");
if (RestListenerUtils.restartShowConfigurationStatus(servletContext)) {
httpServletResponse.setHeader("REFRESH", "0");
return "";
}
}
throw new ListenerException("no REST listener configured for uri [" + uri + "]");
}
Map methodConfig = getMethodConfig(matchingPattern, method);
if (methodConfig == null) {
throw new ListenerException("No REST listener specified for uri [" + uri + "] method [" + method + "]");
}
if (context == null) {
context = new PipeLineSessionBase();
}
context.put("restPath", restPath);
context.put("uri", uri);
context.put("method", method);
String etag = null;
String ifNoneMatch = httpServletRequest.getHeader("If-None-Match");
if (ifNoneMatch != null && !ifNoneMatch.isEmpty()) {
context.put("if-none-match", ifNoneMatch);
etag = ifNoneMatch;
}
String ifMatch = httpServletRequest.getHeader("If-Match");
if (ifMatch != null && !ifMatch.isEmpty()) {
context.put("if-match", ifMatch);
etag = ifMatch;
}
context.put("contentType", contentType);
context.put("userAgent", httpServletRequest.getHeader("User-Agent"));
ServiceClient listener = (ServiceClient) methodConfig.get(KEY_LISTENER);
String etagKey = (String) methodConfig.get(KEY_ETAG_KEY);
String contentTypeKey = (String) methodConfig.get(KEY_CONTENT_TYPE_KEY);
Principal principal = null;
if (httpServletRequest != null) {
principal = httpServletRequest.getUserPrincipal();
if (principal != null) {
context.put("principal", principal.getName());
}
}
String ctName = Thread.currentThread().getName();
try {
boolean writeToSecLog = false;
if (listener instanceof RestListener) {
RestListener restListener = (RestListener) listener;
if (restListener.isRetrieveMultipart()) {
if (ServletFileUpload.isMultipartContent(httpServletRequest)) {
try {
DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);
List<FileItem> items = servletFileUpload.parseRequest(httpServletRequest);
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();
log.trace("setting parameter [" + fieldName + "] to [" + fieldValue + "]");
context.put(fieldName, fieldValue);
} else {
// Process form file field (input type="file").
String fieldName = item.getFieldName();
String fieldNameName = fieldName + "Name";
String fileName = FilenameUtils.getName(item.getName());
if (log.isTraceEnabled())
log.trace("setting parameter [" + fieldNameName + "] to [" + fileName + "]");
context.put(fieldNameName, fileName);
InputStream inputStream = item.getInputStream();
if (inputStream.available() > 0) {
log.trace("setting parameter [" + fieldName + "] to input stream of file [" + fileName + "]");
context.put(fieldName, inputStream);
} else {
log.trace("setting parameter [" + fieldName + "] to [" + null + "]");
context.put(fieldName, null);
}
}
}
} catch (FileUploadException e) {
throw new ListenerException(e);
} catch (IOException e) {
throw new ListenerException(e);
}
}
}
writeToSecLog = restListener.isWriteToSecLog();
if (writeToSecLog) {
context.put("writeSecLogMessage", restListener.isWriteSecLogMessage());
}
boolean authorized = false;
if (principal == null) {
authorized = true;
} else {
String authRoles = restListener.getAuthRoles();
if (StringUtils.isNotEmpty(authRoles)) {
StringTokenizer st = new StringTokenizer(authRoles, ",;");
while (st.hasMoreTokens()) {
String authRole = st.nextToken();
if (httpServletRequest.isUserInRole(authRole)) {
authorized = true;
}
}
}
}
if (!authorized) {
throw new ListenerException("Not allowed for uri [" + uri + "]");
}
Thread.currentThread().setName(restListener.getName() + "[" + ctName + "]");
}
if (etagKey != null)
context.put(etagKey, etag);
if (contentTypeKey != null)
context.put(contentTypeKey, contentType);
if (log.isTraceEnabled())
log.trace("dispatching request, uri [" + uri + "] listener pattern [" + matchingPattern + "] method [" + method + "] etag [" + etag + "] contentType [" + contentType + "]");
if (httpServletRequest != null)
context.put(IPipeLineSession.HTTP_REQUEST_KEY, httpServletRequest);
if (httpServletResponse != null)
context.put(IPipeLineSession.HTTP_RESPONSE_KEY, httpServletResponse);
if (servletContext != null)
context.put(IPipeLineSession.SERVLET_CONTEXT_KEY, servletContext);
if (writeToSecLog) {
secLog.info(HttpUtils.getExtendedCommandIssuedBy(httpServletRequest));
}
// Caching: check for etags
if (uri.startsWith("/"))
uri = uri.substring(1);
if (uri.indexOf("?") > -1) {
uri = uri.split("?")[0];
}
String etagCacheKey = restPath + "_" + uri;
if (cache != null && cache.containsKey(etagCacheKey)) {
String cachedEtag = (String) cache.get(etagCacheKey);
if (ifNoneMatch != null && ifNoneMatch.equalsIgnoreCase(cachedEtag) && method.equalsIgnoreCase("GET")) {
// Exit with 304
context.put("exitcode", 304);
if (log.isDebugEnabled())
log.trace("aborting request with status 304, matched if-none-match [" + ifNoneMatch + "]");
return null;
}
if (ifMatch != null && !ifMatch.equalsIgnoreCase(cachedEtag) && !method.equalsIgnoreCase("GET")) {
// Exit with 412
context.put("exitcode", 412);
if (log.isDebugEnabled())
log.trace("aborting request with status 412, matched if-match [" + ifMatch + "] method [" + method + "]");
return null;
}
}
String result = listener.processRequest(null, request, context);
// Caching: pipeline has been processed, save etag
if (result != null && cache != null && context.containsKey("etag")) {
// In case the eTag has manually been set and the pipeline exited in error state...
cache.put(etagCacheKey, context.get("etag"));
}
if (result == null && !context.containsKey("exitcode")) {
log.warn("result is null!");
}
return result;
} finally {
if (listener instanceof RestListener) {
Thread.currentThread().setName(ctName);
}
}
}
Aggregations