use of javax.servlet.http.Part in project sling by apache.
the class StreamedUploadOperation method doRun.
@Override
protected void doRun(SlingHttpServletRequest request, PostResponse response, List<Modification> changes) throws PersistenceException {
@SuppressWarnings("unchecked") Iterator<Part> partsIterator = (Iterator<Part>) request.getAttribute("request-parts-iterator");
Map<String, List<String>> formFields = new HashMap<>();
boolean streamingBodies = false;
while (partsIterator.hasNext()) {
Part part = partsIterator.next();
String name = part.getName();
if (isFormField(part)) {
addField(formFields, name, part);
if (streamingBodies) {
LOG.warn("Form field {} was sent after the bodies started to be streamed. " + "Will not have been available to all streamed bodies. " + "It is recommended to send all form fields before streamed bodies in the POST ", name);
}
} else {
streamingBodies = true;
// process the file body and commit.
writeContent(request.getResourceResolver(), part, formFields, response, changes);
}
}
}
use of javax.servlet.http.Part in project sling by apache.
the class StreamingUploadOperationTest method test.
@Test
public void test() throws PersistenceException, RepositoryException, UnsupportedEncodingException {
List<Modification> changes = new ArrayList<>();
PostResponse response = new AbstractPostResponse() {
@Override
protected void doSend(HttpServletResponse response) throws IOException {
}
@Override
public void onChange(String type, String... arguments) {
}
@Override
public String getPath() {
return "/test/upload/location";
}
};
List<Part> partsList = new ArrayList<>();
partsList.add(new MockPart("formfield1", null, null, 0, new ByteArrayInputStream("testformfield1".getBytes("UTF-8")), Collections.EMPTY_MAP));
partsList.add(new MockPart("formfield2", null, null, 0, new ByteArrayInputStream("testformfield2".getBytes("UTF-8")), Collections.EMPTY_MAP));
partsList.add(new MockPart("test1.txt", "text/plain", "test1bad.txt", 4, new ByteArrayInputStream("test".getBytes("UTF-8")), Collections.EMPTY_MAP));
partsList.add(new MockPart("*", "text/plain2", "test2.txt", 8, new ByteArrayInputStream("test1234".getBytes("UTF-8")), Collections.EMPTY_MAP));
partsList.add(new MockPart("badformfield2", null, null, 0, new ByteArrayInputStream("testbadformfield2".getBytes("UTF-8")), Collections.EMPTY_MAP));
final Iterator<Part> partsIterator = partsList.iterator();
final Map<String, Resource> repository = new HashMap<>();
final ResourceResolver resourceResolver = new MockResourceResolver() {
@Override
public Resource getResource(String path) {
Resource resource = repository.get(path);
if (resource == null) {
if ("/test/upload/location".equals(path)) {
resource = new MockRealResource(this, path, "sling:Folder");
repository.put(path, resource);
LOG.debug("Created {} ", path);
}
}
LOG.debug("Resource {} is {} {}", path, resource, ResourceUtil.isSyntheticResource(resource));
return resource;
}
@Override
public Iterable<Resource> getChildren(Resource resource) {
return null;
}
@Override
public void delete(Resource resource) throws PersistenceException {
}
@Override
public Resource create(Resource resource, String s, Map<String, Object> map) throws PersistenceException {
Resource childResource = resource.getChild(s);
if (childResource != null) {
throw new IllegalArgumentException("Child " + s + " already exists ");
}
Resource newResource = new MockRealResource(this, resource.getPath() + "/" + s, (String) map.get("sling:resourceType"), map);
repository.put(newResource.getPath(), newResource);
return newResource;
}
@Override
public void revert() {
}
@Override
public void commit() throws PersistenceException {
LOG.debug("Committing");
for (Map.Entry<String, Resource> e : repository.entrySet()) {
LOG.debug("Committing {} ", e.getKey());
Resource r = e.getValue();
ModifiableValueMap vm = r.adaptTo(ModifiableValueMap.class);
for (Map.Entry<String, Object> me : vm.entrySet()) {
if (me.getValue() instanceof InputStream) {
try {
String value = IOUtils.toString((InputStream) me.getValue());
LOG.debug("Converted {} {} ", me.getKey(), value);
vm.put(me.getKey(), value);
} catch (IOException e1) {
throw new PersistenceException("Failed to commit input stream", e1);
}
}
}
LOG.debug("Converted {} ", vm);
}
LOG.debug("Committted {} ", repository);
}
@Override
public boolean hasChanges() {
return false;
}
};
SlingHttpServletRequest request = new MockSlingHttpServlet3Request(null, null, null, null, null) {
@Override
public Object getAttribute(String name) {
if ("request-parts-iterator".equals(name)) {
return partsIterator;
}
return super.getAttribute(name);
}
@Override
public ResourceResolver getResourceResolver() {
return resourceResolver;
}
};
streamedUplodOperation.doRun(request, response, changes);
{
Resource r = repository.get("/test/upload/location/test1.txt");
Assert.assertNotNull(r);
ValueMap m = r.adaptTo(ValueMap.class);
Assert.assertNotNull(m);
Assert.assertEquals("nt:file", m.get("jcr:primaryType"));
}
{
Resource r = repository.get("/test/upload/location/test1.txt/jcr:content");
Assert.assertNotNull(r);
ValueMap m = r.adaptTo(ValueMap.class);
Assert.assertNotNull(m);
Assert.assertEquals("nt:resource", m.get("jcr:primaryType"));
Assert.assertTrue(m.get("jcr:lastModified") instanceof Calendar);
Assert.assertEquals("text/plain", m.get("jcr:mimeType"));
Assert.assertEquals("test", m.get("jcr:data"));
}
{
Resource r = repository.get("/test/upload/location/test2.txt");
Assert.assertNotNull(r);
ValueMap m = r.adaptTo(ValueMap.class);
Assert.assertNotNull(m);
Assert.assertEquals("nt:file", m.get("jcr:primaryType"));
}
{
Resource r = repository.get("/test/upload/location/test2.txt/jcr:content");
Assert.assertNotNull(r);
ValueMap m = r.adaptTo(ValueMap.class);
Assert.assertNotNull(m);
Assert.assertEquals("nt:resource", m.get("jcr:primaryType"));
Assert.assertTrue(m.get("jcr:lastModified") instanceof Calendar);
Assert.assertEquals("text/plain2", m.get("jcr:mimeType"));
Assert.assertEquals("test1234", m.get("jcr:data"));
}
}
use of javax.servlet.http.Part in project tomee by apache.
the class CommonsFileUploadPartFactory method read.
public static Collection<Part> read(final HttpRequestImpl request) {
// mainly for testing
// Create a new file upload handler
final DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setRepository(REPO);
final ServletFileUpload upload = new ServletFileUpload();
upload.setFileItemFactory(factory);
final List<Part> parts = new ArrayList<>();
try {
final List<FileItem> items = upload.parseRequest(new ServletRequestContext(request));
final String enc = request.getCharacterEncoding();
for (final FileItem item : items) {
final CommonsFileUploadPart part = new CommonsFileUploadPart(item, null);
parts.add(part);
if (part.getSubmittedFileName() == null) {
String name = part.getName();
String value = null;
try {
String encoding = request.getCharacterEncoding();
if (encoding == null) {
if (enc == null) {
encoding = "UTF-8";
} else {
encoding = enc;
}
}
value = part.getString(encoding);
} catch (final UnsupportedEncodingException uee) {
try {
value = part.getString("UTF-8");
} catch (final UnsupportedEncodingException e) {
// not possible
}
}
request.addInternalParameter(name, value);
}
}
return parts;
} catch (final FileUploadException e) {
throw new IllegalStateException(e);
}
}
use of javax.servlet.http.Part in project XRTB by benmfaul.
the class WebCampaign method multiPart.
public String multiPart(Request baseRequest, HttpServletRequest request, MultipartConfigElement config) throws Exception {
HttpSession session = request.getSession(false);
String user = (String) session.getAttribute("user");
User u = db.getUser(user);
if (u == null)
throw new Exception("No such user");
baseRequest.setAttribute(Request.__MULTIPART_CONFIG_ELEMENT, config);
Collection<Part> parts = request.getParts();
for (Part part : parts) {
System.out.println("" + part.getName());
}
Part filePart = request.getPart("file");
InputStream imageStream = filePart.getInputStream();
byte[] resultBuff = new byte[0];
byte[] buff = new byte[1024];
int k = -1;
while ((k = imageStream.read(buff, 0, buff.length)) > -1) {
// temp buffer size
byte[] tbuff = new byte[resultBuff.length + k];
// = bytes already
// read + bytes last
// read
// copy
System.arraycopy(resultBuff, 0, tbuff, 0, resultBuff.length);
// previous
// bytes
// copy
System.arraycopy(buff, 0, tbuff, resultBuff.length, k);
// current
// lot
// call the temp buffer as your result buff
resultBuff = tbuff;
}
System.out.println(resultBuff.length + " bytes read.");
if (k == 0) {
// no file provided
throw new Exception("No file provided");
} else {
byte[] bytes = new byte[1024];
Part namePart = request.getPart("name");
InputStream nameStream = namePart.getInputStream();
int rc = nameStream.read(bytes);
String name = new String(bytes, 0, rc);
FileOutputStream fos = new FileOutputStream(u.directory + "/" + name);
fos.write(resultBuff);
fos.close();
}
Map response = new HashMap();
response.put("images", getFiles(u));
return getString(response);
}
use of javax.servlet.http.Part in project dropbox-sdk-java by dropbox.
the class DropboxBrowse method doUpload.
// -------------------------------------------------------------------------------------------
// POST /upload
// -------------------------------------------------------------------------------------------
public void doUpload(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
MultipartConfigElement multipartConfigElement = new MultipartConfigElement("/tmp");
request.setAttribute("org.eclipse.multipartConfig", multipartConfigElement);
if (!common.checkPost(request, response))
return;
User user = common.requireLoggedInUser(request, response);
if (user == null)
return;
DbxClientV2 dbxClient = requireDbxClient(request, response, user);
if (dbxClient == null)
return;
try {
// Just call getParts() to trigger the too-large exception.
request.getParts();
} catch (IllegalStateException ex) {
response.sendError(400, "Request too large");
return;
}
String targetFolder = slurpUtf8Part(request, response, "targetFolder", 1024);
if (targetFolder == null)
return;
Part filePart = request.getPart("file");
if (filePart == null) {
response.sendError(400, "Field \"file\" is missing.");
return;
}
String fileName = filePart.getName();
if (fileName == null) {
response.sendError(400, "Field \"file\" has no name.");
return;
}
// Upload file to Dropbox
String fullTargetPath = targetFolder + "/" + fileName;
FileMetadata metadata;
try {
metadata = dbxClient.files().upload(fullTargetPath).uploadAndFinish(filePart.getInputStream());
} catch (DbxException ex) {
common.handleDbxException(response, user, ex, "upload(" + jq(fullTargetPath) + ", ...)");
return;
} catch (IOException ex) {
response.sendError(400, "Error getting file data from you.");
return;
}
// Display uploaded file metadata.
response.setContentType("text/html");
response.setCharacterEncoding("utf-8");
PrintWriter out = new PrintWriter(new OutputStreamWriter(response.getOutputStream(), "UTF-8"));
out.println("<html>");
out.println("<head><title>File uploaded: " + escapeHtml4(metadata.getPathLower()) + "</title></head>");
out.println("<body>");
out.println("<h2>File uploaded: " + escapeHtml4(metadata.getPathLower()) + "</h2>");
out.println("<pre>");
out.print(escapeHtml4(metadata.toStringMultiline()));
out.println("</pre>");
out.println("</body>");
out.println("</html>");
out.flush();
}
Aggregations