use of org.apache.commons.fileupload.FileItemIterator in project getting-started-java by GoogleCloudPlatform.
the class UpdateBookServlet method doPost.
@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
BookDao dao = (BookDao) this.getServletContext().getAttribute("dao");
assert ServletFileUpload.isMultipartContent(req);
CloudStorageHelper storageHelper = (CloudStorageHelper) getServletContext().getAttribute("storageHelper");
String newImageUrl = null;
Map<String, String> params = new HashMap<String, String>();
try {
FileItemIterator iter = new ServletFileUpload().getItemIterator(req);
while (iter.hasNext()) {
FileItemStream item = iter.next();
if (item.isFormField()) {
params.put(item.getFieldName(), Streams.asString(item.openStream()));
} else if (!Strings.isNullOrEmpty(item.getName())) {
newImageUrl = storageHelper.uploadFile(item, getServletContext().getInitParameter("bookshelf.bucket"));
}
}
} catch (FileUploadException e) {
throw new IOException(e);
}
try {
Book oldBook = dao.readBook(Long.decode(params.get("id")));
Book book = new Book.Builder().author(params.get("author")).description(params.get("description")).publishedDate(params.get("publishedDate")).title(params.get("title")).imageUrl(null == newImageUrl ? params.get("imageUrl") : newImageUrl).id(Long.decode(params.get("id"))).createdBy(oldBook.getCreatedBy()).createdById(oldBook.getCreatedById()).build();
dao.updateBook(book);
resp.sendRedirect("/read?id=" + params.get("id"));
} catch (Exception e) {
throw new ServletException("Error updating book", e);
}
}
use of org.apache.commons.fileupload.FileItemIterator in project BIMserver by opensourceBIM.
the class BulkUploadServlet method service.
@Override
public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
if (request.getHeader("Origin") != null && !getBimServer().getServerSettingsCache().isHostAllowed(request.getHeader("Origin"))) {
response.setStatus(403);
return;
}
response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
response.setHeader("Access-Control-Allow-Headers", "Content-Type");
String token = (String) request.getSession().getAttribute("token");
ObjectNode result = OBJECT_MAPPER.createObjectNode();
response.setContentType("text/json");
try {
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
long poid = -1;
String comment = null;
if (isMultipart) {
ServletFileUpload upload = new ServletFileUpload();
FileItemIterator iter = upload.getItemIterator(request);
InputStream in = null;
String name = "";
while (iter.hasNext()) {
FileItemStream item = iter.next();
if (item.isFormField()) {
if ("token".equals(item.getFieldName())) {
token = Streams.asString(item.openStream());
} else if ("poid".equals(item.getFieldName())) {
poid = Long.parseLong(Streams.asString(item.openStream()));
} else if ("comment".equals(item.getFieldName())) {
comment = Streams.asString(item.openStream());
}
} else {
name = item.getName();
in = item.openStream();
if (poid != -1) {
ServiceInterface service = getBimServer().getServiceFactory().get(token, AccessMethod.INTERNAL).get(ServiceInterface.class);
SProject mainProject = service.getProjectByPoid(poid);
ZipInputStream zipInputStream = new ZipInputStream(in);
ZipEntry nextEntry = zipInputStream.getNextEntry();
while (nextEntry != null) {
String fullfilename = nextEntry.getName();
if (fullfilename.toLowerCase().endsWith(".ifc") || fullfilename.toLowerCase().endsWith("ifcxml") || fullfilename.toLowerCase().endsWith(".ifczip")) {
BufferedInputStream bufferedInputStream = new BufferedInputStream(zipInputStream);
byte[] initialBytes = ByteUtils.extractHead(bufferedInputStream, 4096);
InputStreamDataSource inputStreamDataSource = new InputStreamDataSource(new FakeClosingInputStream(bufferedInputStream));
inputStreamDataSource.setName(name);
DataHandler ifcFile = new DataHandler(inputStreamDataSource);
if (fullfilename.contains("/")) {
String path = fullfilename.substring(0, fullfilename.lastIndexOf("/"));
String filename = fullfilename.substring(fullfilename.lastIndexOf("/") + 1);
String extension = filename.substring(filename.lastIndexOf(".") + 1);
try {
String schema = service.determineIfcVersion(initialBytes, fullfilename.toLowerCase().endsWith(".ifczip"));
SProject project = getOrCreatePath(service, mainProject, mainProject, path, schema);
SDeserializerPluginConfiguration deserializer = service.getSuggestedDeserializerForExtension(extension, project.getOid());
service.checkinSync(project.getOid(), comment, deserializer.getOid(), -1L, filename, ifcFile, false);
} catch (Exception e) {
LOGGER.error(e.getMessage() + " (" + fullfilename + ")");
}
}
} else {
if (!nextEntry.isDirectory()) {
LOGGER.info("Unknown fileextenstion " + fullfilename);
}
}
nextEntry = zipInputStream.getNextEntry();
}
// DataHandler ifcFile = new DataHandler(inputStreamDataSource);
//
// if (token != null) {
// if (topicId == -1) {
// long newTopicId = service.checkin(poid, comment, deserializerOid, -1L, name, ifcFile, merge, sync);
// result.put("topicId", newTopicId);
// } else {
// ServiceInterface service = getBimServer().getServiceFactory().get(token, AccessMethod.INTERNAL).get(ServiceInterface.class);
// long newTopicId = service.checkinInitiated(topicId, poid, comment, deserializerOid, -1L, name, ifcFile, merge, true);
// result.put("topicId", newTopicId);
// }
// }
} else {
result.put("exception", "No poid");
}
}
}
}
} catch (Exception e) {
LOGGER.error("", e);
// sendException(response, e);
return;
}
response.getWriter().write(result.toString());
}
use of org.apache.commons.fileupload.FileItemIterator in project BIMserver by opensourceBIM.
the class UploadServlet method service.
@Override
public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
if (request.getHeader("Origin") != null && !getBimServer().getServerSettingsCache().isHostAllowed(request.getHeader("Origin"))) {
response.setStatus(403);
return;
}
response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
response.setHeader("Access-Control-Allow-Headers", "Content-Type");
String token = (String) request.getSession().getAttribute("token");
ObjectNode result = OBJECT_MAPPER.createObjectNode();
response.setContentType("text/json");
try {
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
long poid = -1;
String comment = null;
if (isMultipart) {
ServletFileUpload upload = new ServletFileUpload();
FileItemIterator iter = upload.getItemIterator(request);
InputStream in = null;
String name = "";
long deserializerOid = -1;
boolean merge = false;
boolean sync = false;
String compression = null;
String action = null;
long topicId = -1;
try {
while (iter.hasNext()) {
FileItemStream item = iter.next();
if (item.isFormField()) {
if ("action".equals(item.getFieldName())) {
action = Streams.asString(item.openStream());
} else if ("token".equals(item.getFieldName())) {
token = Streams.asString(item.openStream());
} else if ("poid".equals(item.getFieldName())) {
poid = Long.parseLong(Streams.asString(item.openStream()));
} else if ("comment".equals(item.getFieldName())) {
comment = Streams.asString(item.openStream());
} else if ("topicId".equals(item.getFieldName())) {
topicId = Long.parseLong(Streams.asString(item.openStream()));
} else if ("sync".equals(item.getFieldName())) {
sync = Streams.asString(item.openStream()).equals("true");
} else if ("merge".equals(item.getFieldName())) {
merge = Streams.asString(item.openStream()).equals("true");
} else if ("compression".equals(item.getFieldName())) {
compression = Streams.asString(item.openStream());
} else if ("deserializerOid".equals(item.getFieldName())) {
deserializerOid = Long.parseLong(Streams.asString(item.openStream()));
}
} else {
name = item.getName();
in = item.openStream();
if ("file".equals(action)) {
ServiceInterface serviceInterface = getBimServer().getServiceFactory().get(token, AccessMethod.INTERNAL).get(ServiceInterface.class);
SFile file = new SFile();
byte[] data = IOUtils.toByteArray(in);
file.setData(data);
file.setSize(data.length);
file.setFilename(name);
file.setMime(item.getContentType());
result.put("fileId", serviceInterface.uploadFile(file));
} else if (poid != -1) {
InputStream realStream = null;
if ("gzip".equals(compression)) {
realStream = new GZIPInputStream(in);
} else if ("deflate".equals(compression)) {
realStream = new InflaterInputStream(in);
} else {
realStream = in;
}
// When uploading in async mode, we want to return as soon as the whole stream has been read (that's not when the checkin process has finished!)
TriggerOnCloseInputStream triggerOnCloseInputStream = new TriggerOnCloseInputStream(realStream);
InputStreamDataSource inputStreamDataSource = new InputStreamDataSource(triggerOnCloseInputStream);
inputStreamDataSource.setName(name);
DataHandler ifcFile = new DataHandler(inputStreamDataSource);
if (token != null) {
ServiceInterface service = getBimServer().getServiceFactory().get(token, AccessMethod.INTERNAL).get(ServiceInterface.class);
if (topicId == -1) {
if (sync) {
SLongCheckinActionState checkinSync = service.checkinSync(poid, comment, deserializerOid, -1L, name, ifcFile, merge);
result = (ObjectNode) getBimServer().getJsonHandler().getJsonConverter().toJson(checkinSync);
service.cleanupLongAction(checkinSync.getTopicId());
} else {
// When async, we can return as soon as all the data has been read
long newTopicId = service.checkinAsync(poid, comment, deserializerOid, -1L, name, ifcFile, merge);
triggerOnCloseInputStream.await();
result.put("topicId", newTopicId);
}
} else {
if (sync) {
SLongCheckinActionState checkinSync = service.checkinInitiatedSync(topicId, poid, comment, deserializerOid, -1L, name, ifcFile, merge);
result = (ObjectNode) getBimServer().getJsonHandler().getJsonConverter().toJson(checkinSync);
service.cleanupLongAction(checkinSync.getTopicId());
} else {
service.checkinInitiatedAsync(topicId, poid, comment, deserializerOid, -1L, name, ifcFile, merge);
triggerOnCloseInputStream.await();
result.put("topicId", topicId);
}
}
}
} else {
result.put("exception", "No poid");
}
}
}
} catch (MalformedStreamException e) {
LOGGER.error(comment);
LOGGER.error("", e);
}
}
} catch (Exception e) {
LOGGER.error("", e);
sendException(response, e);
return;
}
response.getWriter().write(result.toString());
}
use of org.apache.commons.fileupload.FileItemIterator in project flow by vaadin.
the class StreamReceiverHandler method handleMultipartFileUploadFromInputStream.
private boolean handleMultipartFileUploadFromInputStream(VaadinSession session, VaadinRequest request, StreamReceiver streamReceiver, StateNode owner) throws IOException {
boolean success = true;
long contentLength = getContentLength(request);
// Parse the request
FileItemIterator iter;
try {
iter = getItemIterator(request);
while (iter.hasNext()) {
FileItemStream item = iter.next();
boolean itemSuccess = handleStream(session, streamReceiver, owner, contentLength, item);
success = success && itemSuccess;
}
} catch (FileUploadException e) {
success = false;
getLogger().warn("File upload failed.", e);
}
return success;
}
use of org.apache.commons.fileupload.FileItemIterator in project application by collectionspace.
the class WebUIRequest method initRequest.
private void initRequest(UIUmbrella umbrella, HttpServletRequest request, HttpServletResponse response, List<String> p) throws IOException, UIException {
this.request = request;
this.response = response;
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (isMultipart) {
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload();
// Parse the request
FileItemIterator iter;
try {
iter = upload.getItemIterator(request);
while (iter.hasNext()) {
FileItemStream item = iter.next();
String name = item.getFieldName();
// InputStream stream = item.openStream();
if (item.isFormField()) {
// System.out.println("Form field " + name + " with value "
// + Streams.asString(stream) + " detected.");
} else {
// System.out.println("File field " + name + " with file name "
// + item.getName() + " detected.");
// Process the input stream
contentHeaders = item.getHeaders();
uploadName = item.getName();
ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
if (item != null) {
InputStream stream = item.openStream();
IOUtils.copy(stream, byteOut);
new TeeInputStream(stream, byteOut);
}
bytebody = byteOut.toByteArray();
}
}
} catch (FileUploadException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
body = IOUtils.toString(request.getInputStream(), "UTF-8");
}
this.ppath = p.toArray(new String[0]);
if (!(umbrella instanceof WebUIUmbrella))
throw new UIException("Bad umbrella");
this.umbrella = (WebUIUmbrella) umbrella;
session = calculateSessionId();
}
Aggregations