use of org.apache.commons.fileupload.FileUploadException in project MassBank-web by MassBank.
the class FileUpload method getRequestParam.
/**
* リクエストパラメータ解析
* multipart/form-dataに含まれている通常リクエスト情報を取得する
* 失敗した場合はnullを返却する
* @return 通常リクエスト情報MAP<キー, 値>
*/
@SuppressWarnings("unchecked")
public HashMap<String, String[]> getRequestParam() {
if (fileItemList == null) {
try {
fileItemList = (List<FileItem>) parseRequest(req);
} catch (FileUploadException e) {
e.printStackTrace();
return null;
}
}
HashMap<String, String[]> reqParamMap = new HashMap<String, String[]>();
for (FileItem fItem : fileItemList) {
// 通常フィールドの場合(リクエストパラメータの値が配列でない場合)
if (fItem.isFormField()) {
String key = fItem.getFieldName();
String val = fItem.getString();
if (key != null && !key.equals("")) {
reqParamMap.put(key, new String[] { val });
}
}
}
return reqParamMap;
}
use of org.apache.commons.fileupload.FileUploadException in project wcomponents by BorderTech.
the class ServletUtil method extractParameterMap.
/**
* Extract the parameters and file items allowing for multi part form fields.
*
* @param request the request being processed
* @param parameters the map to store non-file request parameters in.
* @param files the map to store the uploaded file parameters in.
*/
public static void extractParameterMap(final HttpServletRequest request, final Map<String, String[]> parameters, final Map<String, FileItem[]> files) {
if (isMultipart(request)) {
ServletFileUpload upload = new ServletFileUpload();
upload.setFileItemFactory(new DiskFileItemFactory());
try {
List fileItems = upload.parseRequest(request);
uploadFileItems(fileItems, parameters, files);
} catch (FileUploadException ex) {
throw new SystemException(ex);
}
// Include Query String Parameters (only if parameters were not included in the form fields)
for (Object entry : request.getParameterMap().entrySet()) {
Map.Entry<String, String[]> param = (Map.Entry<String, String[]>) entry;
if (!parameters.containsKey(param.getKey())) {
parameters.put(param.getKey(), param.getValue());
}
}
} else {
parameters.putAll(request.getParameterMap());
}
}
use of org.apache.commons.fileupload.FileUploadException in project getting-started-java by GoogleCloudPlatform.
the class CreateBookServlet method doPost.
@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
assert ServletFileUpload.isMultipartContent(req);
CloudStorageHelper storageHelper = (CloudStorageHelper) getServletContext().getAttribute("storageHelper");
String newImageUrl = null;
Map<String, String> params = new HashMap<String, String>();
try {
FileItemIterator iter = new ServletFileUpload().getItemIterator(req);
while (iter.hasNext()) {
FileItemStream item = iter.next();
if (item.isFormField()) {
params.put(item.getFieldName(), Streams.asString(item.openStream()));
} else if (!Strings.isNullOrEmpty(item.getName())) {
newImageUrl = storageHelper.uploadFile(item, System.getenv("BOOKSHELF_BUCKET"));
}
}
} catch (FileUploadException e) {
throw new IOException(e);
}
String createdByString = "";
String createdByIdString = "";
HttpSession session = req.getSession();
if (session.getAttribute("userEmail") != null) {
// Does the user have a logged in session?
createdByString = (String) session.getAttribute("userEmail");
createdByIdString = (String) session.getAttribute("userId");
}
Book book = new Book.Builder().author(params.get("author")).description(params.get("description")).publishedDate(params.get("publishedDate")).title(params.get("title")).imageUrl(null == newImageUrl ? params.get("imageUrl") : newImageUrl).createdBy(createdByString).createdById(createdByIdString).build();
BookDao dao = (BookDao) this.getServletContext().getAttribute("dao");
String id = dao.createBook(book);
logger.log(Level.INFO, "Created book {0}", book);
resp.sendRedirect("/read?id=" + id);
}
use of org.apache.commons.fileupload.FileUploadException in project getting-started-java by GoogleCloudPlatform.
the class UpdateBookServlet method doPost.
@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
BookDao dao = (BookDao) this.getServletContext().getAttribute("dao");
assert ServletFileUpload.isMultipartContent(req);
CloudStorageHelper storageHelper = (CloudStorageHelper) getServletContext().getAttribute("storageHelper");
String newImageUrl = null;
Map<String, String> params = new HashMap<String, String>();
try {
FileItemIterator iter = new ServletFileUpload().getItemIterator(req);
while (iter.hasNext()) {
FileItemStream item = iter.next();
if (item.isFormField()) {
params.put(item.getFieldName(), Streams.asString(item.openStream()));
} else if (!Strings.isNullOrEmpty(item.getName())) {
newImageUrl = storageHelper.uploadFile(item, getServletContext().getInitParameter("bookshelf.bucket"));
}
}
} catch (FileUploadException e) {
throw new IOException(e);
}
try {
Book oldBook = dao.readBook(Long.decode(params.get("id")));
Book book = new Book.Builder().author(params.get("author")).description(params.get("description")).publishedDate(params.get("publishedDate")).title(params.get("title")).imageUrl(null == newImageUrl ? params.get("imageUrl") : newImageUrl).id(Long.decode(params.get("id"))).createdBy(oldBook.getCreatedBy()).createdById(oldBook.getCreatedById()).build();
dao.updateBook(book);
resp.sendRedirect("/read?id=" + params.get("id"));
} catch (Exception e) {
throw new ServletException("Error updating book", e);
}
}
use of org.apache.commons.fileupload.FileUploadException in project iaf by ibissource.
the class RestServiceDispatcher method dispatchRequest.
/**
* Dispatch a request.
* @param uri the name of the IReceiver object
* @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, PipeLineSession 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) {
throw new ListenerException("no REST listener configured for uri [" + uri + "]");
}
Map<String, Object> methodConfig = getMethodConfig(matchingPattern, method);
if (methodConfig == null) {
throw new ListenerException("No REST listener specified for uri [" + uri + "] method [" + method + "]");
}
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(PipeLineSession.HTTP_REQUEST_KEY, httpServletRequest);
if (httpServletResponse != null)
context.put(PipeLineSession.HTTP_RESPONSE_KEY, httpServletResponse);
if (servletContext != null)
context.put(PipeLineSession.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;
try {
result = listener.processRequest(null, new Message(request), context).asString();
} catch (IOException e) {
throw new ListenerException(e);
}
// 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