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 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 MSEC by Tencent.
the class FileUploadServlet method FileUpload.
//处理multi-part格式的http请求
//将key-value字段放到fields里返回
//将文件保存到tmp目录,并将文件名保存到filesOnServer列表里返回
protected static String FileUpload(Map<String, String> fields, List<String> filesOnServer, HttpServletRequest request, HttpServletResponse response) {
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
// Create a factory for disk-based file items
DiskFileItemFactory factory = new DiskFileItemFactory();
int MaxMemorySize = 10000000;
int MaxRequestSize = MaxMemorySize;
String tmpDir = System.getProperty("TMP", "/tmp");
//System.out.printf("temporary directory:%s", tmpDir);
// Set factory constraints
factory.setSizeThreshold(MaxMemorySize);
factory.setRepository(new File(tmpDir));
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setHeaderEncoding("utf8");
// Set overall request size constraint
upload.setSizeMax(MaxRequestSize);
// Parse the request
try {
@SuppressWarnings("unchecked") List<FileItem> items = upload.parseRequest(request);
// Process the uploaded items
Iterator<FileItem> iter = items.iterator();
while (iter.hasNext()) {
FileItem item = iter.next();
if (item.isFormField()) {
//普通的k -v字段
String name = item.getFieldName();
String value = item.getString("utf-8");
fields.put(name, value);
} else {
String fieldName = item.getFieldName();
String fileName = item.getName();
if (fileName == null || fileName.length() < 1) {
return "file name is empty.";
}
String localFileName = ServletConfig.fileServerRootDir + File.separator + "tmp" + File.separator + fileName;
//System.out.printf("upload file:%s", localFileName);
String contentType = item.getContentType();
boolean isInMemory = item.isInMemory();
long sizeInBytes = item.getSize();
File uploadedFile = new File(localFileName);
item.write(uploadedFile);
filesOnServer.add(localFileName);
}
}
return "success";
} catch (FileUploadException e) {
e.printStackTrace();
return e.toString();
} catch (Exception e) {
e.printStackTrace();
return e.toString();
}
}
use of org.apache.commons.fileupload.FileUploadException in project zm-mailbox by Zimbra.
the class FileUploadServlet method handleMultipartUpload.
@SuppressWarnings("unchecked")
List<Upload> handleMultipartUpload(HttpServletRequest req, HttpServletResponse resp, String fmt, Account acct, boolean limitByFileUploadMaxSize, AuthToken at, boolean csrfCheckComplete) throws IOException, ServiceException {
List<FileItem> items = null;
String reqId = null;
ServletFileUpload upload = getUploader2(limitByFileUploadMaxSize);
try {
items = upload.parseRequest(req);
if (!csrfCheckComplete && !CsrfUtil.checkCsrfInMultipartFileUpload(items, at)) {
drainRequestStream(req);
mLog.info("CSRF token validation failed for account: %s, Auth token is CSRF enabled", acct.getName());
sendResponse(resp, HttpServletResponse.SC_UNAUTHORIZED, fmt, null, null, items);
return Collections.emptyList();
}
} catch (FileUploadBase.SizeLimitExceededException e) {
// at least one file was over max allowed size
mLog.info("Exceeded maximum upload size of " + upload.getSizeMax() + " bytes: " + e);
drainRequestStream(req);
sendResponse(resp, HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE, fmt, reqId, null, items);
return Collections.emptyList();
} catch (FileUploadBase.InvalidContentTypeException e) {
// at least one file was of a type not allowed
mLog.info("File upload failed", e);
drainRequestStream(req);
sendResponse(resp, HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE, fmt, reqId, null, items);
return Collections.emptyList();
} catch (FileUploadException e) {
// parse of request failed for some other reason
mLog.info("File upload failed", e);
drainRequestStream(req);
sendResponse(resp, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, fmt, reqId, null, items);
return Collections.emptyList();
}
String charset = "utf-8";
LinkedList<String> names = new LinkedList<String>();
HashMap<FileItem, String> filenames = new HashMap<FileItem, String>();
if (items != null) {
for (Iterator<FileItem> it = items.iterator(); it.hasNext(); ) {
FileItem fi = it.next();
if (fi == null)
continue;
if (fi.isFormField()) {
if (fi.getFieldName().equals("requestId")) {
// correlate this file upload session's request and response
reqId = fi.getString();
} else if (fi.getFieldName().equals("_charset_") && !fi.getString().equals("")) {
// get the form value charset, if specified
charset = fi.getString();
} else if (fi.getFieldName().startsWith("filename")) {
// allow a client to explicitly provide filenames for the uploads
names.clear();
String value = fi.getString(charset);
if (!Strings.isNullOrEmpty(value)) {
for (String name : value.split("\n")) {
names.add(name.trim());
}
}
}
// strip form fields out of the list of uploads
it.remove();
} else {
if (fi.getName() == null || fi.getName().trim().equals("")) {
it.remove();
} else {
filenames.put(fi, names.isEmpty() ? null : names.remove());
}
}
}
}
// restrict requestId value for safety due to later use in javascript
if (reqId != null && reqId.length() != 0) {
if (!ALLOWED_REQUESTID_CHARS.matcher(reqId).matches()) {
mLog.info("Rejecting upload with invalid chars in reqId: %s", reqId);
sendResponse(resp, HttpServletResponse.SC_BAD_REQUEST, fmt, null, null, items);
return Collections.emptyList();
}
}
// empty upload is not a "success"
if (items == null || items.isEmpty()) {
mLog.info("No data in upload for reqId: %s", reqId);
sendResponse(resp, HttpServletResponse.SC_NO_CONTENT, fmt, reqId, null, items);
return Collections.emptyList();
}
// cache the uploaded files in the hash and construct the list of upload IDs
List<Upload> uploads = new ArrayList<Upload>(items.size());
for (FileItem fi : items) {
String name = filenames.get(fi);
if (name == null || name.trim().equals(""))
name = fi.getName();
Upload up = new Upload(acct.getId(), fi, name);
mLog.info("Received multipart: %s", up);
synchronized (mPending) {
mPending.put(up.uuid, up);
}
uploads.add(up);
}
sendResponse(resp, HttpServletResponse.SC_OK, fmt, reqId, uploads, items);
return uploads;
}
use of org.apache.commons.fileupload.FileUploadException in project stanbol by apache.
the class ContentItemReader method readFrom.
@Override
public ContentItem readFrom(Class<ContentItem> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream) throws IOException, WebApplicationException {
//boolean withMetadata = withMetadata(httpHeaders);
ContentItem contentItem = null;
IRI contentItemId = getContentItemId();
if (log.isTraceEnabled()) {
//NOTE: enabling TRACE level logging will copy the parsed content
// into a BYTE array
log.trace("Parse ContentItem from");
log.trace(" - MediaType: {}", mediaType);
log.trace(" - Headers:");
for (Entry<String, List<String>> header : httpHeaders.entrySet()) {
log.trace(" {}: {}", header.getKey(), header.getValue());
}
byte[] content = IOUtils.toByteArray(entityStream);
log.trace("content: \n{}", new String(content, "UTF-8"));
IOUtils.closeQuietly(entityStream);
entityStream = new ByteArrayInputStream(content);
}
Set<String> parsedContentIds = new HashSet<String>();
if (mediaType.isCompatible(MULTIPART)) {
log.debug(" - parse Multipart MIME ContentItem");
//try to read ContentItem from "multipart/from-data"
Graph metadata = null;
FileItemIterator fileItemIterator;
try {
fileItemIterator = fu.getItemIterator(new MessageBodyReaderContext(entityStream, mediaType));
while (fileItemIterator.hasNext()) {
FileItemStream fis = fileItemIterator.next();
if (fis.getFieldName().equals("metadata")) {
if (contentItem != null) {
throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST).entity("The Multipart MIME part with the 'metadata' " + "MUST BE before the MIME part containing the " + "'content'!").build());
}
//only used if not parsed as query param
if (contentItemId == null && fis.getName() != null && !fis.getName().isEmpty()) {
contentItemId = new IRI(fis.getName());
}
metadata = new IndexedGraph();
try {
getParser().parse(metadata, fis.openStream(), fis.getContentType());
} catch (Exception e) {
throw new WebApplicationException(e, Response.status(Response.Status.BAD_REQUEST).entity(String.format("Unable to parse Metadata " + "from Multipart MIME part '%s' (" + "contentItem: %s| contentType: %s)", fis.getFieldName(), fis.getName(), fis.getContentType())).build());
}
} else if (fis.getFieldName().equals("content")) {
contentItem = createContentItem(contentItemId, metadata, fis, parsedContentIds);
} else if (fis.getFieldName().equals("properties") || fis.getFieldName().equals(REQUEST_PROPERTIES_URI.getUnicodeString())) {
//parse the RequestProperties
if (contentItem == null) {
throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST).entity("Multipart MIME parts for " + "Request Properties MUST BE after the " + "MIME parts for 'metadata' AND 'content'").build());
}
MediaType propMediaType = MediaType.valueOf(fis.getContentType());
if (!APPLICATION_JSON_TYPE.isCompatible(propMediaType)) {
throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST).entity("Request Properties (Multipart MIME parts" + "with the name '" + fis.getFieldName() + "') MUST " + "BE encoded as 'appicaltion/json' (encountered: '" + fis.getContentType() + "')!").build());
}
String propCharset = propMediaType.getParameters().get("charset");
if (propCharset == null) {
propCharset = "UTF-8";
}
Map<String, Object> reqProp = ContentItemHelper.initRequestPropertiesContentPart(contentItem);
try {
reqProp.putAll(toMap(new JSONObject(IOUtils.toString(fis.openStream(), propCharset))));
} catch (JSONException e) {
throw new WebApplicationException(e, Response.status(Response.Status.BAD_REQUEST).entity("Unable to parse Request Properties from" + "Multipart MIME parts with the name 'properties'!").build());
}
} else {
//additional metadata as serialised RDF
if (contentItem == null) {
throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST).entity("Multipart MIME parts for additional " + "contentParts MUST BE after the MIME " + "parts for 'metadata' AND 'content'").build());
}
if (fis.getFieldName() == null || fis.getFieldName().isEmpty()) {
throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST).entity("Multipart MIME parts representing " + "ContentParts for additional RDF metadata" + "MUST define the contentParts URI as" + "'name' of the MIME part!").build());
}
Graph graph = new IndexedGraph();
try {
getParser().parse(graph, fis.openStream(), fis.getContentType());
} catch (Exception e) {
throw new WebApplicationException(e, Response.status(Response.Status.BAD_REQUEST).entity(String.format("Unable to parse RDF " + "for ContentPart '%s' ( contentType: %s)", fis.getName(), fis.getContentType())).build());
}
IRI contentPartId = new IRI(fis.getFieldName());
contentItem.addPart(contentPartId, graph);
}
}
if (contentItem == null) {
throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST).entity("The parsed multipart content item does not contain " + "any content. The content is expected to be contained " + "in a MIME part with the name 'content'. This part can " + " be also a 'multipart/alternate' if multiple content " + "parts need to be included in requests.").build());
}
} catch (FileUploadException e) {
throw new WebApplicationException(e, Response.Status.BAD_REQUEST);
}
} else {
//normal content
ContentItemFactory ciFactory = getContentItemFactory();
contentItem = ciFactory.createContentItem(contentItemId, new StreamSource(entityStream, mediaType.toString()));
//add the URI of the main content
parsedContentIds.add(contentItem.getPartUri(0).getUnicodeString());
}
//set the parsed contentIDs to the EnhancementProperties
Map<String, Object> ep = ContentItemHelper.initRequestPropertiesContentPart(contentItem);
parseEnhancementPropertiesFromParameters(ep);
ep.put(PARSED_CONTENT_URIS, Collections.unmodifiableSet(parsedContentIds));
//STANBOL-660: set the language of the content if explicitly parsed in the request
String contentLanguage = getContentLanguage();
if (!StringUtils.isBlank(contentLanguage)) {
//language codes are case insensitive ... so we convert to lower case
contentLanguage = contentLanguage.toLowerCase(Locale.ROOT);
createParsedLanguageAnnotation(contentItem, contentLanguage);
// previously only the dc:language property was set to the contentItem. However this
// information is only used as fallback if no Language annotation is present. However
// if a user explicitly parses the language he expects this language to be used
// so this was change with STANBOL-1417
// EnhancementEngineHelper.set(contentItem.getMetadata(), contentItem.getUri(),
// DC_LANGUAGE, new PlainLiteralImpl(contentLanguage));
}
return contentItem;
}
Aggregations