use of org.apache.commons.fileupload.FileItemStream in project opencast by opencast.
the class StaticFileRestService method postStaticFile.
@POST
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.TEXT_PLAIN)
@Path("")
@RestQuery(name = "postStaticFile", description = "Post a new static resource", bodyParameter = @RestParameter(description = "The static resource file", isRequired = true, name = "BODY", type = RestParameter.Type.FILE), reponses = { @RestResponse(description = "Returns the id of the uploaded static resource", responseCode = HttpServletResponse.SC_CREATED), @RestResponse(description = "No filename or file to upload found", responseCode = HttpServletResponse.SC_BAD_REQUEST), @RestResponse(description = "The upload size is too big", responseCode = HttpServletResponse.SC_BAD_REQUEST) }, returnDescription = "")
public Response postStaticFile(@Context HttpServletRequest request) {
if (maxUploadSize > 0 && request.getContentLength() > maxUploadSize) {
logger.warn("Preventing upload of static file as its size {} is larger than the max size allowed {}", request.getContentLength(), maxUploadSize);
return Response.status(Status.BAD_REQUEST).build();
}
ProgressInputStream inputStream = null;
try {
String filename = null;
if (ServletFileUpload.isMultipartContent(request)) {
boolean isDone = false;
for (FileItemIterator iter = new ServletFileUpload().getItemIterator(request); iter.hasNext(); ) {
FileItemStream item = iter.next();
if (item.isFormField()) {
continue;
} else {
logger.debug("Processing file item");
filename = item.getName();
inputStream = new ProgressInputStream(item.openStream());
inputStream.addPropertyChangeListener(new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
long totalNumBytesRead = (Long) evt.getNewValue();
if (totalNumBytesRead > maxUploadSize) {
logger.warn("Upload limit of {} bytes reached, returning a bad request.", maxUploadSize);
throw new WebApplicationException(Status.BAD_REQUEST);
}
}
});
isDone = true;
}
if (isDone)
break;
}
} else {
logger.warn("Request is not multi part request, returning a bad request.");
return Response.status(Status.BAD_REQUEST).build();
}
if (filename == null) {
logger.warn("Request was missing the filename, returning a bad request.");
return Response.status(Status.BAD_REQUEST).build();
}
if (inputStream == null) {
logger.warn("Request was missing the file, returning a bad request.");
return Response.status(Status.BAD_REQUEST).build();
}
String uuid = staticFileService.storeFile(filename, inputStream);
try {
return Response.created(getStaticFileURL(uuid)).entity(uuid).build();
} catch (NotFoundException e) {
logger.error("Previous stored file with uuid {} couldn't beren found: {}", uuid, ExceptionUtils.getStackTrace(e));
return Response.serverError().build();
}
} catch (WebApplicationException e) {
return e.getResponse();
} catch (Exception e) {
logger.error("Unable to store file because: {}", ExceptionUtils.getStackTrace(e));
return Response.serverError().build();
} finally {
IOUtils.closeQuietly(inputStream);
}
}
use of org.apache.commons.fileupload.FileItemStream in project opencast by opencast.
the class WorkingFileRepositoryRestEndpoint method restPutInCollection.
@POST
@Produces(MediaType.TEXT_HTML)
@Path(WorkingFileRepository.COLLECTION_PATH_PREFIX + "{collectionId}")
@RestQuery(name = "putInCollection", description = "Store a file in working repository under ./collectionId/filename", returnDescription = "The URL to access the stored file", pathParameters = { @RestParameter(name = "collectionId", description = "the colection identifier", isRequired = true, type = STRING) }, restParameters = { @RestParameter(name = "file", description = "the filename", isRequired = true, type = FILE) }, reponses = { @RestResponse(responseCode = SC_OK, description = "OK, file stored") })
public Response restPutInCollection(@PathParam("collectionId") String collectionId, @Context HttpServletRequest request) throws Exception {
if (ServletFileUpload.isMultipartContent(request)) {
for (FileItemIterator iter = new ServletFileUpload().getItemIterator(request); iter.hasNext(); ) {
FileItemStream item = iter.next();
if (item.isFormField()) {
continue;
}
URI url = this.putInCollection(collectionId, item.getName(), item.openStream());
return Response.ok(url.toString()).build();
}
}
return Response.serverError().status(400).build();
}
use of org.apache.commons.fileupload.FileItemStream in project opencast by opencast.
the class WorkingFileRepositoryRestEndpoint method restPut.
@POST
@Produces(MediaType.TEXT_HTML)
@Path(WorkingFileRepository.MEDIAPACKAGE_PATH_PREFIX + "{mediaPackageID}/{mediaPackageElementID}")
@RestQuery(name = "put", description = "Store a file in working repository under ./mediaPackageID/mediaPackageElementID", returnDescription = "The URL to access the stored file", pathParameters = { @RestParameter(name = "mediaPackageID", description = "the mediapackage identifier", isRequired = true, type = STRING), @RestParameter(name = "mediaPackageElementID", description = "the mediapackage element identifier", isRequired = true, type = STRING) }, reponses = { @RestResponse(responseCode = SC_OK, description = "OK, file stored") }, restParameters = { @RestParameter(name = "file", description = "the filename", isRequired = true, type = FILE) })
public Response restPut(@PathParam("mediaPackageID") String mediaPackageID, @PathParam("mediaPackageElementID") String mediaPackageElementID, @Context HttpServletRequest request) throws Exception {
if (ServletFileUpload.isMultipartContent(request)) {
for (FileItemIterator iter = new ServletFileUpload().getItemIterator(request); iter.hasNext(); ) {
FileItemStream item = iter.next();
if (item.isFormField()) {
continue;
}
URI url = this.put(mediaPackageID, mediaPackageElementID, item.getName(), item.openStream());
return Response.ok(url.toString()).build();
}
}
return Response.serverError().status(400).build();
}
use of org.apache.commons.fileupload.FileItemStream in project pwm by pwm-project.
the class PwmRequest method readFileUploads.
public Map<String, FileUploadItem> readFileUploads(final int maxFileSize, final int maxItems) throws IOException, ServletException, PwmUnrecoverableException {
final Map<String, FileUploadItem> returnObj = new LinkedHashMap<>();
try {
if (ServletFileUpload.isMultipartContent(this.getHttpServletRequest())) {
final ServletFileUpload upload = new ServletFileUpload();
final FileItemIterator iter = upload.getItemIterator(this.getHttpServletRequest());
while (iter.hasNext() && returnObj.size() < maxItems) {
final FileItemStream item = iter.next();
final InputStream inputStream = item.openStream();
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
final long length = IOUtils.copyLarge(inputStream, baos, 0, maxFileSize + 1);
if (length > maxFileSize) {
final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_UNKNOWN, "upload file size limit exceeded");
LOGGER.error(this, errorInformation);
respondWithError(errorInformation);
return Collections.emptyMap();
}
final byte[] outputFile = baos.toByteArray();
final FileUploadItem fileUploadItem = new FileUploadItem(item.getName(), item.getContentType(), new ImmutableByteArray(outputFile));
returnObj.put(item.getFieldName(), fileUploadItem);
}
}
} catch (Exception e) {
LOGGER.error("error reading file upload: " + e.getMessage());
}
return Collections.unmodifiableMap(returnObj);
}
use of org.apache.commons.fileupload.FileItemStream in project canvas_course_manager by tl-its-umich-edu.
the class CourseSupportProcess method getAttachmentContent.
private String getAttachmentContent() {
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload();
StringBuilder csv = new StringBuilder();
try {
// Parse the request
FileItemIterator iter = upload.getItemIterator(request);
while (iter.hasNext()) {
FileItemStream item = iter.next();
InputStream inputStream = item.openStream();
BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
String strLine;
while ((strLine = br.readLine()) != null) {
String csvContent = strLine.trim();
csv.append(csvContent);
csv.append(Utils.CONSTANT_LINE_FEED);
}
M_log.debug(csv);
}
} catch (FileUploadException | IOException e) {
M_log.error("Error getting attachment content from the UI due to " + e.getMessage());
return null;
} catch (Exception e) {
M_log.error("Error getting attachment content from the UI due to " + e.getMessage());
return null;
}
return csv.toString();
}
Aggregations