use of org.apache.commons.fileupload.FileUploadException in project pratilipi by Pratilipi.
the class GenericApi method executeApi.
final Object executeApi(GenericApi api, Method apiMethod, JsonObject requestPayloadJson, Class<? extends GenericRequest> apiMethodParameterType, HttpServletRequest request) {
try {
GenericRequest apiRequest = new Gson().fromJson(requestPayloadJson, apiMethodParameterType);
if (apiRequest instanceof GenericFileUploadRequest) {
GenericFileUploadRequest gfuRequest = (GenericFileUploadRequest) apiRequest;
try {
ServletFileUpload upload = new ServletFileUpload();
FileItemIterator iterator = upload.getItemIterator(request);
while (iterator.hasNext()) {
FileItemStream fileItemStream = iterator.next();
if (!fileItemStream.isFormField()) {
gfuRequest.setName(fileItemStream.getName());
gfuRequest.setData(IOUtils.toByteArray(fileItemStream.openStream()));
gfuRequest.setMimeType(fileItemStream.getContentType());
break;
}
}
} catch (IOException | FileUploadException e) {
throw new UnexpectedServerException();
}
}
JsonObject errorMessages = apiRequest.validate();
if (errorMessages.entrySet().size() > 0)
return new InvalidArgumentException(errorMessages);
else
return apiMethod.invoke(api, apiRequest);
} catch (JsonSyntaxException e) {
logger.log(Level.SEVERE, "Invalid JSON in request body.", e);
return new InvalidArgumentException("Invalid JSON in request body.");
} catch (UnexpectedServerException e) {
return e;
} catch (InvocationTargetException e) {
Throwable te = e.getTargetException();
if (te instanceof InvalidArgumentException || te instanceof InsufficientAccessException || te instanceof UnexpectedServerException) {
return te;
} else {
logger.log(Level.SEVERE, "Failed to execute API.", te);
return new UnexpectedServerException();
}
} catch (IllegalAccessException | IllegalArgumentException e) {
logger.log(Level.SEVERE, "Failed to execute API.", e);
return new UnexpectedServerException();
}
}
use of org.apache.commons.fileupload.FileUploadException in project nhin-d by DirectProject.
the class PoliciesController method checkLexiconFile.
/*********************************
*
* Check Lexicon File Method
*
*********************************/
@PreAuthorize("hasRole('ROLE_ADMIN')")
@RequestMapping(value = "/checkLexiconFile", method = { RequestMethod.GET, RequestMethod.POST })
@ResponseBody
public String checkLexiconFile(@RequestHeader(value = "X-Requested-With", required = false) String requestedWith, HttpServletResponse response, Object command, @RequestHeader(value = "lexicon", required = false) String lexicon, MultipartHttpServletRequest request) throws FileUploadException, IOException, Exception {
final org.nhindirect.policy.PolicyLexicon parseLexicon;
String jsonResponse = "";
String uploadToString = "";
if (log.isDebugEnabled()) {
log.debug("Checking uploaded lexicon file for format and validation");
}
// Grab uploaded file from the post submission
UploadedFile ufile = new UploadedFile();
Iterator<String> itr = request.getFileNames();
MultipartFile mpf = request.getFile(itr.next());
try {
ufile.length = mpf.getBytes().length;
ufile.bytes = mpf.getBytes();
ufile.type = mpf.getContentType();
ufile.name = mpf.getOriginalFilename();
} catch (IOException e) {
}
// Convert upload content to string
uploadToString = new String(ufile.bytes);
uploadToString = JSONObject.escape(uploadToString);
lexicon = request.getParameter("lexicon");
org.nhind.config.PolicyLexicon lex = null;
// Check the file for three types of policies
if (lexicon.isEmpty()) {
lex = org.nhind.config.PolicyLexicon.SIMPLE_TEXT_V1;
} else {
try {
// Convert string of file contents to lexicon object
lex = org.nhind.config.PolicyLexicon.fromString(lexicon);
} catch (Exception e) {
log.error("Invalid lexicon name.");
}
}
// Determine lexicon type
if (lex.equals(org.nhind.config.PolicyLexicon.JAVA_SER)) {
parseLexicon = org.nhindirect.policy.PolicyLexicon.JAVA_SER;
} else if (lex.equals(org.nhind.config.PolicyLexicon.SIMPLE_TEXT_V1)) {
parseLexicon = org.nhindirect.policy.PolicyLexicon.SIMPLE_TEXT_V1;
} else {
parseLexicon = org.nhindirect.policy.PolicyLexicon.XML;
}
InputStream inStr = null;
try {
// Convert policy file upload to byte stream
inStr = new ByteArrayInputStream(ufile.bytes);
// Initialize parser engine
final PolicyLexiconParser parser = PolicyLexiconParserFactory.getInstance(parseLexicon);
// Attempt to parse the lexicon file for validity
parser.parse(inStr);
} catch (PolicyParseException e) {
log.error("Syntax error in policy file " + " : " + e.getMessage());
jsonResponse = "{\"Status\":\"File was not a valid file.\",\"Content\":\"" + uploadToString + "\"}";
} finally {
IOUtils.closeQuietly(inStr);
}
if (jsonResponse.isEmpty()) {
jsonResponse = "{\"Status\":\"Success\",\"Content\":\"" + uploadToString + "\"}";
}
return jsonResponse;
}
use of org.apache.commons.fileupload.FileUploadException in project spring-framework by spring-projects.
the class CommonsMultipartFile method transferTo.
@Override
public void transferTo(File dest) throws IOException, IllegalStateException {
if (!isAvailable()) {
throw new IllegalStateException("File has already been moved - cannot be transferred again");
}
if (dest.exists() && !dest.delete()) {
throw new IOException("Destination file [" + dest.getAbsolutePath() + "] already exists and could not be deleted");
}
try {
this.fileItem.write(dest);
if (logger.isDebugEnabled()) {
String action = "transferred";
if (!this.fileItem.isInMemory()) {
action = isAvailable() ? "copied" : "moved";
}
logger.debug("Multipart file '" + getName() + "' with original filename [" + getOriginalFilename() + "], stored " + getStorageDescription() + ": " + action + " to [" + dest.getAbsolutePath() + "]");
}
} catch (FileUploadException ex) {
throw new IllegalStateException(ex.getMessage());
} catch (IOException ex) {
throw ex;
} catch (Exception ex) {
logger.error("Could not transfer to file", ex);
throw new IOException("Could not transfer to file: " + ex.getMessage());
}
}
use of org.apache.commons.fileupload.FileUploadException in project spring-framework by spring-projects.
the class CommonsMultipartResolver method parseRequest.
/**
* Parse the given servlet request, resolving its multipart elements.
* @param request the request to parse
* @return the parsing result
* @throws MultipartException if multipart resolution failed.
*/
protected MultipartParsingResult parseRequest(HttpServletRequest request) throws MultipartException {
String encoding = determineEncoding(request);
FileUpload fileUpload = prepareFileUpload(encoding);
try {
List<FileItem> fileItems = ((ServletFileUpload) fileUpload).parseRequest(request);
return parseFileItems(fileItems, encoding);
} catch (FileUploadBase.SizeLimitExceededException ex) {
throw new MaxUploadSizeExceededException(fileUpload.getSizeMax(), ex);
} catch (FileUploadBase.FileSizeLimitExceededException ex) {
throw new MaxUploadSizeExceededException(fileUpload.getFileSizeMax(), ex);
} catch (FileUploadException ex) {
throw new MultipartException("Failed to parse multipart servlet request", ex);
}
}
use of org.apache.commons.fileupload.FileUploadException in project felix by apache.
the class ServletRequestWrapper method handleMultipart.
private void handleMultipart() throws IOException {
// Create a new file upload handler
final ServletFileUpload upload = new ServletFileUpload();
upload.setSizeMax(this.multipartConfig.multipartMaxRequestSize);
upload.setFileSizeMax(this.multipartConfig.multipartMaxFileSize);
upload.setFileItemFactory(new DiskFileItemFactory(this.multipartConfig.multipartThreshold, new File(this.multipartConfig.multipartLocation)));
// Parse the request
List<FileItem> items = null;
try {
items = upload.parseRequest(new ServletRequestContext(this));
} catch (final FileUploadException fue) {
throw new IOException("Error parsing multipart request", fue);
}
parts = new ArrayList<>();
for (final FileItem item : items) {
parts.add(new Part() {
@Override
public InputStream getInputStream() throws IOException {
return item.getInputStream();
}
@Override
public String getContentType() {
return item.getContentType();
}
@Override
public String getName() {
return item.getFieldName();
}
@Override
public String getSubmittedFileName() {
return item.getName();
}
@Override
public long getSize() {
return item.getSize();
}
@Override
public void write(String fileName) throws IOException {
try {
item.write(new File(fileName));
} catch (IOException e) {
throw e;
} catch (Exception e) {
throw new IOException(e);
}
}
@Override
public void delete() throws IOException {
item.delete();
}
@Override
public String getHeader(String name) {
return item.getHeaders().getHeader(name);
}
@Override
public Collection<String> getHeaders(String name) {
final List<String> values = new ArrayList<>();
final Iterator<String> iter = item.getHeaders().getHeaders(name);
while (iter.hasNext()) {
values.add(iter.next());
}
return values;
}
@Override
public Collection<String> getHeaderNames() {
final List<String> names = new ArrayList<>();
final Iterator<String> iter = item.getHeaders().getHeaderNames();
while (iter.hasNext()) {
names.add(iter.next());
}
return names;
}
});
}
}
Aggregations