Refine search
public void parse(String filePath, ContentHandler handler, Metadata metadata, ParseContext context) throws FileNotFoundException { File pdfFile = new File(filePath); ContentDisposition cd = new ContentDisposition( "form-data; name=\"input\"; filename=\"" + pdfFile.getName() + "\""); Attachment att = new Attachment("input", new FileInputStream(pdfFile), cd); MultipartBody body = new MultipartBody(att); Response response = WebClient .create(restHostUrlStr + GROBID_PROCESSHEADER_PATH) .accept(MediaType.APPLICATION_XML).type(MediaType.MULTIPART_FORM_DATA) .post(body); try { String resp = response.readEntity(String.class); Metadata teiMet = new TEIDOMParser().parse(resp, context); for (String key : teiMet.names()) { metadata.add("grobid:header_" + key, teiMet.get(key)); } } catch (Exception e) { LOG.warn("Couldn't read response", e); } }
@POST @Consumes("multipart/form-data") @Produces("text/xml") @Path("form") public StreamingOutput getXMLFromMultipart(Attachment att, @Context final UriInfo info) { return produceOutput(att.getObject(InputStream.class), att.getHeaders(), info, "xml"); }
@POST @Path("/books/attachments") @Produces("text/xml") public Response addBookFromAttachments() throws Exception { Collection<Attachment> handlers = AttachmentUtils.getChildAttachments(context); for (Attachment a : handlers) { if ("book2".equals(a.getContentId())) { return readBookFromInputStream(a.getDataHandler().getInputStream()); } } throw new WebApplicationException(500); }
@POST @Consumes(MediaType.MULTIPART_FORM_DATA) @Path("/") public ConsumerRegistration register(MultipartBody body) { String appName = body.getAttachmentObject("appName", String.class); String appURI = body.getAttachmentObject("appURI", String.class); String appRedirectURI = body.getAttachmentObject("appRedirectURI", String.class); String appDesc = body.getAttachmentObject("appDescription", String.class); Attachment att = body.getAttachment("appLogo"); if (att != null) { InputStream logoStream = att.getObject(InputStream.class); CachedOutputStream cos = new CachedOutputStream(); try { ub.path("logo").path(appName.toLowerCase()); ContentDisposition cd = att.getContentDisposition(); if (cd != null && cd.getParameter("filename") != null) { ub.path(cd.getParameter("filename"));
/** * Save/Update the given import configuration. * Prepare the file to be processed with Camel routes * * @param file file * @param importConfigId config * @return OK / NOK Http Code. */ @POST @Path("/oneshot") @Consumes(MediaType.MULTIPART_FORM_DATA) @Produces(MediaType.APPLICATION_JSON) public Response processOneshotImportConfigurationCSV(@Multipart(value = "importConfigId") String importConfigId, @Multipart(value = "file") Attachment file) { try { java.nio.file.Path path = Paths.get(configSharingService.getProperty(RouterConstants.IMPORT_ONESHOT_UPLOAD_DIR) + importConfigId + ".csv"); Files.deleteIfExists(path); InputStream in = file.getObject(InputStream.class); Files.copy(in, path); } catch (IOException e) { logger.error("Error processing one shot configuration CSV", e); return Response.serverError().build(); } return Response.ok().build(); } }
@Path("/books/file/semicolon") @Consumes("multipart/form-data") @Produces("text/plain") @POST public String addBookFileNameSemicolon(@Multipart("a") Attachment att) { return att.getObject(String.class) + ", filename:" + att.getContentDisposition().getParameter("filename"); }
@POST @Path("/books/formimage") @Consumes("multipart/form-data") @Produces("multipart/form-data") public MultipartBody addBookFormImage(MultipartBody image) throws Exception { List<Attachment> atts = image.getAllAttachments(); if (atts.size() != 1) { throw new WebApplicationException(); } List<Attachment> newAtts = new ArrayList<>(); Attachment at = atts.get(0); MultivaluedMap<String, String> headers = at.getHeaders(); if (!"http://host/bar".equals(headers.getFirst("Content-Location"))) { throw new WebApplicationException(); } if (!"custom".equals(headers.getFirst("Custom-Header"))) { throw new WebApplicationException(); } headers.putSingle("Content-Location", "http://host/location"); newAtts.add(new Attachment(at.getContentId(), at.getDataHandler(), headers)); return new MultipartBody(newAtts); }
@GET @Path("/content/string") @Produces("multipart/mixed") public Attachment getAttachmentWithStringContent() throws Exception { return new Attachment("Response_XML_Payload", "application/xml", "<Book><id>888</id></Book>"); }
/** * Uploads a file encoded in a multipart/form message. * * @param multipart * the multiPart object containing the file to be uploaded * @return a URI with the (custom) uploaded:// scheme and a unique * identifier to be used future ingests. Returns 202 if request succeeds */ @POST @Consumes(MediaType.MULTIPART_FORM_DATA) public Response upload(MultipartBody multipart){ Attachment file = multipart.getAttachment("file"); if (file == null) { return Response.status(400).entity("Missing file part").type(MediaType.TEXT_PLAIN).build(); } InputStream fileStream = file.getObject(InputStream.class); String uploaded; try { uploaded = m_management.putTempStream(getContext(), fileStream); logger.debug("File uploaded: ", uploaded); } catch (ServerException e) { logger.error(e.toString()); return handleException(e, false); } return Response.status(Response.Status.ACCEPTED).entity(uploaded).type( MediaType.TEXT_PLAIN).build(); } }
@POST @Consumes("multipart/form-data") public Response addBook(final MultipartBody body) throws Exception { for (final Attachment attachment: body.getAllAttachments()) { final DataHandler handler = attachment.getDataHandler(); if (handler != null) { final String source = handler.getName(); final LuceneDocumentMetadata metadata = new LuceneDocumentMetadata() .withSource(source) .withField("modified", Date.class); final Document document = extractor.extract(handler.getInputStream(), metadata); if (document != null) { final IndexWriter writer = getIndexWriter(); try { writer.addDocument(document); writer.commit(); } finally { writer.close(); } } } } return Response.ok().build(); }
@Test public void testLargeHeader() throws Exception { InputStream is1 = getClass().getResourceAsStream("/org/apache/cxf/systest/jaxrs/resources/java.jpg"); String address = "http://localhost:" + PORT + "/bookstore/books/image"; WebClient client = WebClient.create(address); client.type("multipart/mixed").accept("multipart/mixed"); WebClient.getConfig(client).getRequestContext().put("support.type.as.multipart", "true"); StringBuilder sb = new StringBuilder(); sb.append("form-data;"); for (int i = 0; i < 10000; i++) { sb.append("aaaaaaaaaa"); } MultivaluedMap<String, String> headers = new MultivaluedHashMap<>(); headers.putSingle("Content-ID", "root"); headers.putSingle("Content-Type", "application/octet-stream"); headers.putSingle("Content-Disposition", sb.toString()); DataHandler handler = new DataHandler(new InputStreamDataSource(is1, "application/octet-stream")); Attachment att = new Attachment(headers, handler, null); Response response = client.post(att); assertEquals(response.getStatus(), 413); client.close(); }
dh = (DataHandler)obj; } else if (DataSource.class.isAssignableFrom(obj.getClass())) { dh = new DataHandler((DataSource)obj); } else if (File.class.isAssignableFrom(obj.getClass())) { File f = (File)obj; ContentDisposition cd = mainMediaType.startsWith(MediaType.MULTIPART_FORM_DATA) ? new ContentDisposition("form-data;name=file;filename=" + f.getName()) : null; return new Attachment(AttachmentUtil.BODY_ATTACHMENT_ID, Files.newInputStream(f.toPath()), cd); } else if (Attachment.class.isAssignableFrom(obj.getClass())) { Attachment att = (Attachment)obj; if (att.getObject() == null) { return att; dh = getHandlerForObject(att.getObject(), att.getObject().getClass(), new Annotation[]{}, att.getContentType().toString(), id); return new Attachment(att.getContentId(), dh, att.getHeaders()); } else if (byte[].class.isAssignableFrom(obj.getClass())) { ByteDataSource source = new ByteDataSource((byte[])obj); source.setContentType(mimeType); dh = new DataHandler(source); } else { dh = getHandlerForObject(obj, cls, genericType, anns, mimeType, id); headers.putSingle("Content-Type", mimeType); return new Attachment(contentId, dh, headers);
@Test public void testAddBookJaxbJsonImageAttachments() throws Exception { String address = "http://localhost:" + PORT + "/bookstore/books/jaxbimagejson"; WebClient client = WebClient.create(address); client.type("multipart/mixed").accept("multipart/mixed"); Book jaxb = new Book("jaxb", 1L); Book json = new Book("json", 2L); InputStream is1 = getClass().getResourceAsStream("/org/apache/cxf/systest/jaxrs/resources/java.jpg"); List<Attachment> objects = new ArrayList<>(); objects.add(new Attachment("<theroot>", MediaType.APPLICATION_XML, jaxb)); objects.add(new Attachment("thejson", MediaType.APPLICATION_JSON, json)); objects.add(new Attachment("theimage", MediaType.APPLICATION_OCTET_STREAM, is1)); Collection<? extends Attachment> coll = client.postAndGetCollection(objects, Attachment.class); List<Attachment> result = new ArrayList<>(coll); Book jaxb2 = readBookFromInputStream(result.get(0).getDataHandler().getInputStream()); assertEquals("jaxb", jaxb2.getName()); assertEquals(1L, jaxb2.getId()); Book json2 = readJSONBookFromInputStream(result.get(1).getDataHandler().getInputStream()); assertEquals("json", json2.getName()); assertEquals(2L, json2.getId()); InputStream is2 = result.get(2).getDataHandler().getInputStream(); byte[] image1 = IOUtils.readBytesFromStream( getClass().getResourceAsStream("/org/apache/cxf/systest/jaxrs/resources/java.jpg")); byte[] image2 = IOUtils.readBytesFromStream(is2); assertTrue(Arrays.equals(image1, image2)); }
@Test public void testUploadImageFromForm() throws Exception { InputStream is1 = getClass().getResourceAsStream("/org/apache/cxf/systest/jaxrs/resources/java.jpg"); String address = "http://localhost:" + PORT + "/bookstore/books/formimage"; WebClient client = WebClient.create(address); HTTPConduit conduit = WebClient.getConfig(client).getHttpConduit(); conduit.getClient().setReceiveTimeout(1000000); conduit.getClient().setConnectionTimeout(1000000); client.type("multipart/form-data").accept("multipart/form-data"); ContentDisposition cd = new ContentDisposition("attachment;filename=java.jpg"); MultivaluedMap<String, String> headers = new MetadataMap<>(); headers.putSingle("Content-ID", "image"); headers.putSingle("Content-Disposition", cd.toString()); headers.putSingle("Content-Location", "http://host/bar"); headers.putSingle("custom-header", "custom"); Attachment att = new Attachment(is1, headers); MultipartBody body = new MultipartBody(att); MultipartBody body2 = client.post(body, MultipartBody.class); InputStream is2 = body2.getRootAttachment().getDataHandler().getInputStream(); byte[] image1 = IOUtils.readBytesFromStream( getClass().getResourceAsStream("/org/apache/cxf/systest/jaxrs/resources/java.jpg")); byte[] image2 = IOUtils.readBytesFromStream(is2); assertTrue(Arrays.equals(image1, image2)); ContentDisposition cd2 = body2.getRootAttachment().getContentDisposition(); assertEquals("attachment;filename=java.jpg", cd2.toString()); assertEquals("java.jpg", cd2.getParameter("filename")); assertEquals("http://host/location", body2.getRootAttachment().getHeader("Content-Location")); }
@Test public void testUploadImageFromForm2() throws Exception { File file = new File(getClass().getResource("/org/apache/cxf/systest/jaxrs/resources/java.jpg") .toURI().getPath()); String address = "http://localhost:" + PORT + "/bookstore/books/formimage2"; WebClient client = WebClient.create(address); client.type("multipart/form-data").accept("multipart/form-data"); WebClient.getConfig(client).getRequestContext().put("support.type.as.multipart", "true"); MultipartBody body2 = client.post(file, MultipartBody.class); InputStream is2 = body2.getRootAttachment().getDataHandler().getInputStream(); byte[] image1 = IOUtils.readBytesFromStream( getClass().getResourceAsStream("/org/apache/cxf/systest/jaxrs/resources/java.jpg")); byte[] image2 = IOUtils.readBytesFromStream(is2); assertTrue(Arrays.equals(image1, image2)); ContentDisposition cd2 = body2.getRootAttachment().getContentDisposition(); assertEquals("form-data;name=file;filename=java.jpg", cd2.toString()); assertEquals("java.jpg", cd2.getParameter("filename")); }
private <T> Object fromAttachment(Attachment multipart, Class<T> c, Type t, Annotation[] anns) throws IOException { if (DataHandler.class.isAssignableFrom(c)) { return multipart.getDataHandler(); } else if (DataSource.class.isAssignableFrom(c)) { return multipart.getDataHandler().getDataSource(); } else if (Attachment.class.isAssignableFrom(c)) { return multipart; } else { if (mediaTypeSupported(multipart.getContentType())) { mc.put("org.apache.cxf.multipart.embedded", true); mc.put("org.apache.cxf.multipart.embedded.ctype", multipart.getContentType()); mc.put("org.apache.cxf.multipart.embedded.input", multipart.getDataHandler().getInputStream()); anns = new Annotation[]{}; } MessageBodyReader<T> r = mc.getProviders().getMessageBodyReader(c, t, anns, multipart.getContentType()); if (r != null) { InputStream is = multipart.getDataHandler().getInputStream(); return r.readFrom(c, t, anns, multipart.getContentType(), multipart.getHeaders(), is); } } return null; }
private Map<String, String> doTestAddBookJaxbJsonImageWebClient(String multipartType) throws Exception { String address = "http://localhost:" + PORT + "/bookstore/books/jaxbjsonimage"; WebClient client = WebClient.create(address); WebClient.getConfig(client).getInInterceptors().add(new LoggingInInterceptor()); client.type(multipartType).accept(multipartType); Collection<? extends Attachment> coll = client.postAndGetCollection(objects, Attachment.class); List<Attachment> result = new ArrayList<>(coll); Book jaxb2 = readBookFromInputStream(result.get(0).getDataHandler().getInputStream()); assertEquals("jaxb", jaxb2.getName()); assertEquals(1L, jaxb2.getId()); Book json2 = readJSONBookFromInputStream(result.get(1).getDataHandler().getInputStream()); assertEquals("json", json2.getName()); assertEquals(2L, json2.getId()); InputStream is2 = result.get(2).getDataHandler().getInputStream(); byte[] image1 = IOUtils.readBytesFromStream( getClass().getResourceAsStream("/org/apache/cxf/systest/jaxrs/resources/java.jpg"));
jwsSequence = IOUtils.readStringFromStream(sigPart.getDataHandler().getInputStream()); } catch (IOException ex) { throw ExceptionUtils.toBadRequestException(null, null); InputStream dataPartStream = null; try { dataPartStream = dataPart.getDataHandler().getDataSource().getInputStream(); } catch (IOException ex) { throw ExceptionUtils.toBadRequestException(ex, null); newStream = jwsStream; Attachment newDataPart = new Attachment(newStream, dataPart.getHeaders()); atts.add(i, newDataPart);
Message m, boolean decode) { List<Attachment> atts = body.getAllAttachments(); checkNumberOfParts(m, atts.size()); for (Attachment a : atts) { ContentDisposition cd = a.getContentDisposition(); if (cd != null && !MULTIPART_FORM_DATA_TYPE.equalsIgnoreCase(cd.getType())) { continue; String contentId = a.getContentId(); String name = StringUtils.isEmpty(cdName) ? contentId : cdName.replace("\"", "").replace("'", ""); if (StringUtils.isEmpty(name)) { String value = IOUtils.toString(a.getDataHandler().getInputStream()); params.add(HttpUtils.urlDecode(name), decode ? HttpUtils.urlDecode(value) : value);
Attachment file = multipartBody.getAttachment( "files[]" ); String fileName = file.getContentDisposition().getParameter( "filename" ); IOUtils.copy( file.getDataHandler().getInputStream(), new FileOutputStream( tmpFile.toFile() ) ); FileMetadata fileMetadata = new FileMetadata( fileName, Files.size(tmpFile), "theurl" ); fileMetadata.setServerFileName( tmpFile.toString() );