use of org.apache.commons.fileupload.FileUploadException in project endpoints-java by cloudendpoints.
the class RestServletRequestParamReader method read.
@Override
public Object[] read() throws ServiceException {
// TODO: Take charset from content-type as encoding
try {
EndpointMethod method = getMethod();
if (method.getParameterClasses().length == 0) {
return new Object[0];
}
HttpServletRequest servletRequest = endpointsContext.getRequest();
JsonNode node;
// this case, each part represents a named parameter instead.
if (ServletFileUpload.isMultipartContent(servletRequest)) {
try {
ServletFileUpload upload = new ServletFileUpload();
FileItemIterator iter = upload.getItemIterator(servletRequest);
ObjectNode obj = (ObjectNode) objectReader.createObjectNode();
while (iter.hasNext()) {
FileItemStream item = iter.next();
if (item.isFormField()) {
obj.put(item.getFieldName(), IoUtil.readStream(item.openStream()));
} else {
throw new BadRequestException("unable to parse multipart form field");
}
}
node = obj;
} catch (FileUploadException e) {
throw new BadRequestException("unable to parse multipart request", e);
}
} else {
String requestBody = IoUtil.readRequestBody(servletRequest);
logger.atFine().log("requestBody=%s", requestBody);
// Unlike the Lily protocol, which essentially always requires a JSON body to exist (due to
// path and query parameters being injected into the body), bodies are optional here, so we
// create an empty body and inject named parameters to make deserialize work.
node = Strings.isEmptyOrWhitespace(requestBody) ? objectReader.createObjectNode() : objectReader.readTree(requestBody);
}
if (!node.isObject()) {
throw new BadRequestException("expected a JSON object body");
}
ObjectNode body = (ObjectNode) node;
Map<String, Class<?>> parameterMap = getParameterMap(method);
// the order of precedence is resource field > query parameter > path parameter.
for (Enumeration<?> e = servletRequest.getParameterNames(); e.hasMoreElements(); ) {
String parameterName = (String) e.nextElement();
if (!body.has(parameterName)) {
Class<?> parameterClass = parameterMap.get(parameterName);
ApiParameterConfig parameterConfig = parameterConfigMap.get(parameterName);
if (parameterClass != null && parameterConfig.isRepeated()) {
ArrayNode values = body.putArray(parameterName);
for (String value : servletRequest.getParameterValues(parameterName)) {
values.add(value);
}
} else {
body.put(parameterName, servletRequest.getParameterValues(parameterName)[0]);
}
}
}
for (Entry<String, String> entry : rawPathParameters.entrySet()) {
String parameterName = entry.getKey();
Class<?> parameterClass = parameterMap.get(parameterName);
if (parameterClass != null && !body.has(parameterName)) {
if (parameterConfigMap.get(parameterName).isRepeated()) {
ArrayNode values = body.putArray(parameterName);
for (String value : COMPOSITE_PATH_SPLITTER.split(entry.getValue())) {
values.add(value);
}
} else {
body.put(parameterName, entry.getValue());
}
}
}
for (Entry<String, ApiParameterConfig> entry : parameterConfigMap.entrySet()) {
if (!body.has(entry.getKey()) && entry.getValue().getDefaultValue() != null) {
body.put(entry.getKey(), entry.getValue().getDefaultValue());
}
}
return deserializeParams(body);
} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException | IOException e) {
logger.atInfo().withCause(e).log("Unable to read request parameter(s)");
throw new BadRequestException(e);
}
}
use of org.apache.commons.fileupload.FileUploadException in project sonarqube by SonarSource.
the class CommonsMultipartRequestHandler method handleRequest.
/**
* <p> Parses the input stream and partitions the parsed items into a set
* of form fields and a set of file items. In the process, the parsed
* items are translated from Commons FileUpload <code>FileItem</code>
* instances to Struts <code>FormFile</code> instances. </p>
*
* @param request The multipart request to be processed.
* @throws ServletException if an unrecoverable error occurs.
*/
public void handleRequest(HttpServletRequest request) throws ServletException {
// Get the app config for the current request.
ModuleConfig ac = (ModuleConfig) request.getAttribute(Globals.MODULE_KEY);
// Create and configure a DIskFileUpload instance.
DiskFileUpload upload = new DiskFileUpload();
// The following line is to support an "EncodingFilter"
// see http://issues.apache.org/bugzilla/show_bug.cgi?id=23255
upload.setHeaderEncoding(request.getCharacterEncoding());
// Set the maximum size before a FileUploadException will be thrown.
upload.setSizeMax(getSizeMax(ac));
// Set the maximum size that will be stored in memory.
upload.setSizeThreshold((int) getSizeThreshold(ac));
// Set the the location for saving data on disk.
upload.setRepositoryPath(getRepositoryPath(ac));
// Create the hash tables to be populated.
elementsText = new Hashtable();
elementsFile = new Hashtable();
elementsAll = new Hashtable();
// Parse the request into file items.
List items = null;
try {
items = upload.parseRequest(request);
} catch (DiskFileUpload.SizeLimitExceededException e) {
// Special handling for uploads that are too big.
request.setAttribute(MultipartRequestHandler.ATTRIBUTE_MAX_LENGTH_EXCEEDED, Boolean.TRUE);
return;
} catch (FileUploadException e) {
log.error("Failed to parse multipart request", e);
throw new ServletException(e);
}
// Partition the items into form fields and files.
Iterator iter = items.iterator();
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
if (item.isFormField()) {
addTextParameter(request, item);
} else {
addFileParameter(item);
}
}
}
use of org.apache.commons.fileupload.FileUploadException in project zuul by Netflix.
the class FilterScriptManagerServlet method handlePostBody.
private String handlePostBody(HttpServletRequest request, HttpServletResponse response) throws IOException {
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
org.apache.commons.fileupload.FileItemIterator it = null;
try {
it = upload.getItemIterator(request);
while (it.hasNext()) {
FileItemStream stream = it.next();
InputStream input = stream.openStream();
// NOTE: we are going to pull the entire stream into memory
// this will NOT work if we have huge scripts, but we expect these to be measured in KBs, not MBs or larger
byte[] uploadedBytes = getBytesFromInputStream(input);
input.close();
if (uploadedBytes.length == 0) {
setUsageError(400, "ERROR: Body contained no data.", response);
return null;
}
return new String(uploadedBytes);
}
} catch (FileUploadException e) {
throw new IOException(e.getMessage());
}
return null;
}
use of org.apache.commons.fileupload.FileUploadException in project OpenAttestation by OpenAttestation.
the class WLMDataController method uploadManifest.
public ModelAndView uploadManifest(HttpServletRequest req, HttpServletResponse res) {
log.info("WLMDataController.uploadManifest >>");
req.getSession().removeAttribute("manifestValue");
ModelAndView responseView = new ModelAndView(new JSONView());
List<Map<String, String>> manifestValue = new ArrayList<Map<String, String>>();
// Check that we have a file upload request
boolean isMultipart = ServletFileUpload.isMultipartContent(req);
System.out.println(isMultipart);
if (!isMultipart) {
responseView.addObject("result", false);
return responseView;
}
// Create a factory for disk-based file items
FileItemFactory factory = new DiskFileItemFactory();
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
// Parse the request
try {
@SuppressWarnings("unchecked") List<FileItem> items = upload.parseRequest(req);
// Process the uploaded items
Iterator<FileItem> iter = items.iterator();
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
if (!item.isFormField()) {
String[] lines = item.getString().split("\\r?\\n");
for (String values : lines) {
if (values.length() > 2) {
String[] val = values.split(":");
if (val.length == 2) {
Map<String, String> manifest = new HashMap<String, String>();
manifest.put(val[0], val[1]);
manifestValue.add(manifest);
} else {
responseView.addObject("result", false);
return responseView;
}
}
}
}
}
log.info("Uploaded Content :: " + manifestValue.toString());
req.getSession().setAttribute("manifestValue", manifestValue);
/*responseView.addObject("manifestValue",manifestValue);*/
responseView.addObject("result", manifestValue.size() > 0 ? true : false);
} catch (FileUploadException e) {
e.printStackTrace();
responseView.addObject("result", false);
} catch (Exception e) {
e.printStackTrace();
responseView.addObject("result", false);
}
log.info("WLMDataController.uploadManifest <<<");
return responseView;
}
use of org.apache.commons.fileupload.FileUploadException in project sling by apache.
the class ParameterSupport method getRequestParameterMapInternal.
private ParameterMap getRequestParameterMapInternal() {
if (this.postParameterMap == null) {
// SLING-508 Try to force servlet container to decode parameters
// as ISO-8859-1 such that we can recode later
String encoding = getServletRequest().getCharacterEncoding();
if (encoding == null) {
encoding = Util.ENCODING_DIRECT;
try {
getServletRequest().setCharacterEncoding(encoding);
} catch (UnsupportedEncodingException uee) {
throw new SlingUnsupportedEncodingException(uee);
}
}
// SLING-152 Get parameters from the servlet Container
ParameterMap parameters = new ParameterMap();
// fallback is only used if this request has been started by a service call
boolean useFallback = getServletRequest().getAttribute(MARKER_IS_SERVICE_PROCESSING) != null;
boolean addContainerParameters = false;
// Query String
final String query = getServletRequest().getQueryString();
if (query != null) {
try {
InputStream input = Util.toInputStream(query);
Util.parseQueryString(input, encoding, parameters, false);
addContainerParameters = checkForAdditionalParameters;
} catch (IllegalArgumentException e) {
this.log.error("getRequestParameterMapInternal: Error parsing request", e);
} catch (UnsupportedEncodingException e) {
throw new SlingUnsupportedEncodingException(e);
} catch (IOException e) {
this.log.error("getRequestParameterMapInternal: Error parsing request", e);
}
useFallback = false;
} else {
addContainerParameters = checkForAdditionalParameters;
useFallback = true;
}
// POST requests
final boolean isPost = "POST".equals(this.getServletRequest().getMethod());
if (isPost) {
// WWW URL Form Encoded POST
if (isWWWFormEncodedContent(this.getServletRequest())) {
try {
InputStream input = this.getServletRequest().getInputStream();
Util.parseQueryString(input, encoding, parameters, false);
addContainerParameters = checkForAdditionalParameters;
} catch (IllegalArgumentException e) {
this.log.error("getRequestParameterMapInternal: Error parsing request", e);
} catch (UnsupportedEncodingException e) {
throw new SlingUnsupportedEncodingException(e);
} catch (IOException e) {
this.log.error("getRequestParameterMapInternal: Error parsing request", e);
}
this.requestDataUsed = true;
useFallback = false;
}
// Multipart POST
if (ServletFileUpload.isMultipartContent(new ServletRequestContext(this.getServletRequest()))) {
if (isStreamed(parameters, this.getServletRequest())) {
// special case, the request is Multipart and streamed processing has been requested
try {
this.getServletRequest().setAttribute(REQUEST_PARTS_ITERATOR_ATTRIBUTE, new RequestPartsIterator(this.getServletRequest()));
this.log.debug("getRequestParameterMapInternal: Iterator<javax.servlet.http.Part> available as request attribute named request-parts-iterator");
} catch (IOException e) {
this.log.error("getRequestParameterMapInternal: Error parsing multipart streamed request", e);
} catch (FileUploadException e) {
this.log.error("getRequestParameterMapInternal: Error parsing multipart streamed request", e);
}
// The request data has been passed to the RequestPartsIterator, hence from a RequestParameter pov its been used, and must not be used again.
this.requestDataUsed = true;
// must not try and get anything from the request at this point so avoid jumping through the stream.
addContainerParameters = false;
useFallback = false;
} else {
this.parseMultiPartPost(parameters);
this.requestDataUsed = true;
addContainerParameters = checkForAdditionalParameters;
useFallback = false;
}
}
}
if (useFallback) {
getContainerParameters(parameters, encoding, true);
} else if (addContainerParameters) {
getContainerParameters(parameters, encoding, false);
}
// apply any form encoding (from '_charset_') in the parameter map
Util.fixEncoding(parameters);
this.postParameterMap = parameters;
}
return this.postParameterMap;
}
Aggregations