use of org.apache.commons.fileupload.FileItemIterator 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.FileItemIterator in project jena by apache.
the class SPARQL_Upload method uploadWorker.
/** Process an HTTP file upload of RDF with additiona name field for the graph name.
* We can't stream straight into a dataset because the graph name can be after the data.
* @return graph name and count
*/
// ?? Combine with Upload.fileUploadWorker
// Difference is the handling of names for graphs.
private static UploadDetails uploadWorker(HttpAction action, String base) {
DatasetGraph dsgTmp = DatasetGraphFactory.create();
ServletFileUpload upload = new ServletFileUpload();
String graphName = null;
boolean isQuads = false;
long count = -1;
String name = null;
ContentType ct = null;
Lang lang = null;
try {
FileItemIterator iter = upload.getItemIterator(action.request);
while (iter.hasNext()) {
FileItemStream item = iter.next();
String fieldName = item.getFieldName();
InputStream stream = item.openStream();
if (item.isFormField()) {
// Graph name.
String value = Streams.asString(stream, "UTF-8");
if (fieldName.equals(HttpNames.paramGraph)) {
graphName = value;
if (graphName != null && !graphName.equals("") && !graphName.equals(HttpNames.valueDefault)) {
IRI iri = IRIResolver.parseIRI(value);
if (iri.hasViolation(false))
ServletOps.errorBadRequest("Bad IRI: " + graphName);
if (iri.getScheme() == null)
ServletOps.errorBadRequest("Bad IRI: no IRI scheme name: " + graphName);
if (iri.getScheme().equalsIgnoreCase("http") || iri.getScheme().equalsIgnoreCase("https")) {
// Redundant??
if (iri.getRawHost() == null)
ServletOps.errorBadRequest("Bad IRI: no host name: " + graphName);
if (iri.getRawPath() == null || iri.getRawPath().length() == 0)
ServletOps.errorBadRequest("Bad IRI: no path: " + graphName);
if (iri.getRawPath().charAt(0) != '/')
ServletOps.errorBadRequest("Bad IRI: Path does not start '/': " + graphName);
}
}
} else if (fieldName.equals(HttpNames.paramDefaultGraphURI))
graphName = null;
else
// Add file type?
action.log.info(format("[%d] Upload: Field=%s ignored", action.id, fieldName));
} else {
// Process the input stream
name = item.getName();
if (name == null || name.equals("") || name.equals("UNSET FILE NAME"))
ServletOps.errorBadRequest("No name for content - can't determine RDF syntax");
String contentTypeHeader = item.getContentType();
ct = ContentType.create(contentTypeHeader);
lang = RDFLanguages.contentTypeToLang(ct.getContentType());
if (lang == null) {
lang = RDFLanguages.filenameToLang(name);
// present we wrap the stream accordingly
if (name.endsWith(".gz"))
stream = new GZIPInputStream(stream);
}
if (lang == null)
// Desperate.
lang = RDFLanguages.RDFXML;
isQuads = RDFLanguages.isQuads(lang);
action.log.info(format("[%d] Upload: Filename: %s, Content-Type=%s, Charset=%s => %s", action.id, name, ct.getContentType(), ct.getCharset(), lang.getName()));
StreamRDF x = StreamRDFLib.dataset(dsgTmp);
StreamRDFCounting dest = StreamRDFLib.count(x);
ActionSPARQL.parse(action, dest, stream, lang, base);
count = dest.count();
}
}
if (graphName == null || graphName.equals(""))
graphName = HttpNames.valueDefault;
if (isQuads)
graphName = null;
return new UploadDetails(graphName, dsgTmp, count);
} catch (ActionErrorException ex) {
throw ex;
} catch (Exception ex) {
ServletOps.errorOccurred(ex);
return null;
}
}
use of org.apache.commons.fileupload.FileItemIterator in project Lucee by lucee.
the class FormImpl method initializeMultiPart.
private void initializeMultiPart(PageContext pc, boolean scriptProteced) {
// get temp directory
Resource tempDir = ((ConfigImpl) pc.getConfig()).getTempDirectory();
Resource tempFile;
// Create a new file upload handler
final String encoding = getEncoding();
FileItemFactory factory = tempDir instanceof File ? new DiskFileItemFactory(DiskFileItemFactory.DEFAULT_SIZE_THRESHOLD, (File) tempDir) : new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setHeaderEncoding(encoding);
// ServletRequestContext c = new ServletRequestContext(pc.getHttpServletRequest());
HttpServletRequest req = pc.getHttpServletRequest();
ServletRequestContext context = new ServletRequestContext(req) {
@Override
public String getCharacterEncoding() {
return encoding;
}
};
// Parse the request
try {
FileItemIterator iter = upload.getItemIterator(context);
// byte[] value;
InputStream is;
ArrayList<URLItem> list = new ArrayList<URLItem>();
String fileName;
while (iter.hasNext()) {
FileItemStream item = iter.next();
is = IOUtil.toBufferedInputStream(item.openStream());
if (item.getContentType() == null || StringUtil.isEmpty(item.getName())) {
list.add(new URLItem(item.getFieldName(), new String(IOUtil.toBytes(is), encoding), false));
} else {
fileName = getFileName();
tempFile = tempDir.getRealResource(fileName);
_fileItems.put(fileName, new Item(tempFile, item.getContentType(), item.getName(), item.getFieldName()));
String value = tempFile.toString();
IOUtil.copy(is, tempFile, true);
list.add(new URLItem(item.getFieldName(), value, false));
}
}
raw = list.toArray(new URLItem[list.size()]);
fillDecoded(raw, encoding, scriptProteced, pc.getApplicationContext().getSameFieldAsArray(SCOPE_FORM));
} catch (Exception e) {
SystemOut.printDate(e);
// throw new PageRuntimeException(Caster.toPageException(e));
fillDecodedEL(new URLItem[0], encoding, scriptProteced, pc.getApplicationContext().getSameFieldAsArray(SCOPE_FORM));
initException = e;
}
}
use of org.apache.commons.fileupload.FileItemIterator in project flow by vaadin.
the class StreamReceiverHandler method doHandleMultipartFileUpload.
/**
* Method used to stream content from a multipart request to given
* StreamVariable.
* <p>
* This method takes care of locking the session as needed and does not
* assume the caller has locked the session. This allows the session to be
* locked only when needed and not when handling the upload data.
*
* @param session
* The session containing the stream variable
* @param request
* The upload request
* @param response
* The upload response
* @param streamReceiver
* the receiver containing the destination stream variable
* @param owner
* The owner of the stream
* @throws IOException
* If there is a problem reading the request or writing the
* response
*/
protected void doHandleMultipartFileUpload(VaadinSession session, VaadinRequest request, VaadinResponse response, StreamReceiver streamReceiver, StateNode owner) throws IOException {
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload();
long contentLength = getContentLength(request);
// Parse the request
FileItemIterator iter;
try {
iter = upload.getItemIterator((HttpServletRequest) request);
while (iter.hasNext()) {
FileItemStream item = iter.next();
handleStream(session, streamReceiver, owner, contentLength, item);
}
} catch (FileUploadException e) {
getLogger().warn("File upload failed.", e);
}
sendUploadResponse(response);
}
use of org.apache.commons.fileupload.FileItemIterator in project validator by validator.
the class MultipartFormDataFilter method doFilter.
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
if (ServletFileUpload.isMultipartContent(request)) {
try {
boolean utf8 = false;
String contentType = null;
Map<String, String[]> params = new HashMap<>();
InputStream fileStream = null;
ServletFileUpload upload = new ServletFileUpload();
FileItemIterator iter = upload.getItemIterator(request);
while (iter.hasNext()) {
FileItemStream fileItemStream = iter.next();
if (fileItemStream.isFormField()) {
String fieldName = fileItemStream.getFieldName();
if ("content".equals(fieldName) || "fragment".equals(fieldName)) {
utf8 = true;
String[] parser = params.get("parser");
if (parser != null && parser[0].startsWith("xml")) {
contentType = "application/xml";
} else {
contentType = "text/html";
}
String[] css = params.get("css");
if (css != null && "yes".equals(css[0])) {
contentType = "text/css";
}
request.setAttribute("nu.validator.servlet.MultipartFormDataFilter.type", "textarea");
fileStream = fileItemStream.openStream();
break;
} else {
putParam(params, fieldName, utf8ByteStreamToString(fileItemStream.openStream()));
}
} else {
String fileName = fileItemStream.getName();
if (fileName != null) {
putParam(params, fileItemStream.getFieldName(), fileName);
request.setAttribute("nu.validator.servlet.MultipartFormDataFilter.filename", fileName);
Matcher m = EXTENSION.matcher(fileName);
if (m.matches()) {
contentType = EXTENSION_TO_TYPE.get(m.group(1));
}
}
if (contentType == null) {
contentType = "text/html";
}
request.setAttribute("nu.validator.servlet.MultipartFormDataFilter.type", "file");
fileStream = fileItemStream.openStream();
break;
}
}
if (fileStream == null) {
fileStream = new ByteArrayInputStream(new byte[0]);
}
if (contentType == null) {
contentType = "text/html";
}
chain.doFilter(new RequestWrapper(request, params, contentType, utf8, fileStream), response);
} catch (CharacterCodingException | FileUploadException e) {
response.sendError(415, e.getMessage());
} catch (IOException e) {
response.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage());
}
} else {
chain.doFilter(req, res);
}
}
Aggregations