use of org.glassfish.jersey.media.multipart.BodyPartEntity in project jersey by eclipse-ee4j.
the class MultiPartResource method four.
@Path("four")
@PUT
@Produces("text/plain")
public Response four(MultiPart multiPart) throws IOException {
if (!(multiPart.getBodyParts().size() == 2)) {
return Response.ok("FAILED: Number of body parts is " + multiPart.getBodyParts().size() + " instead of 2").build();
}
BodyPart part0 = multiPart.getBodyParts().get(0);
if (!(part0.getMediaType().equals(new MediaType("text", "plain")))) {
return Response.ok("FAILED: First media type is " + part0.getMediaType()).build();
}
BodyPart part1 = multiPart.getBodyParts().get(1);
if (!(part1.getMediaType().equals(new MediaType("x-application", "x-format")))) {
return Response.ok("FAILED: Second media type is " + part1.getMediaType()).build();
}
BodyPartEntity bpe = (BodyPartEntity) part0.getEntity();
StringBuilder sb = new StringBuilder();
InputStream stream = bpe.getInputStream();
InputStreamReader reader = new InputStreamReader(stream);
char[] buffer = new char[2048];
while (true) {
int n = reader.read(buffer);
if (n < 0) {
break;
}
sb.append(buffer, 0, n);
}
if (!sb.toString().equals("This is the first segment")) {
return Response.ok("FAILED: First part name = " + sb.toString()).build();
}
MultiPartBean bean = part1.getEntityAs(MultiPartBean.class);
if (!bean.getName().equals("myname")) {
return Response.ok("FAILED: Second part name = " + bean.getName()).build();
}
if (!bean.getValue().equals("myvalue")) {
return Response.ok("FAILED: Second part value = " + bean.getValue()).build();
}
return Response.ok("SUCCESS: All tests passed").build();
}
use of org.glassfish.jersey.media.multipart.BodyPartEntity in project jersey by eclipse-ee4j.
the class MultiPartReaderClientSide method readMultiPart.
protected MultiPart readMultiPart(final Class<MultiPart> type, final Type genericType, final Annotation[] annotations, MediaType mediaType, final MultivaluedMap<String, String> headers, final InputStream stream) throws IOException, MIMEParsingException {
mediaType = unquoteMediaTypeParameters(mediaType, "boundary");
final MIMEMessage mimeMessage = new MIMEMessage(stream, mediaType.getParameters().get("boundary"), mimeConfig);
final boolean formData = MediaTypes.typeEqual(mediaType, MediaType.MULTIPART_FORM_DATA_TYPE);
final MultiPart multiPart = formData ? new FormDataMultiPart() : new MultiPart();
final MessageBodyWorkers workers = messageBodyWorkers.get();
multiPart.setMessageBodyWorkers(workers);
final MultivaluedMap<String, String> multiPartHeaders = multiPart.getHeaders();
for (final Map.Entry<String, List<String>> entry : headers.entrySet()) {
final List<String> values = entry.getValue();
for (final String value : values) {
multiPartHeaders.add(entry.getKey(), value);
}
}
final boolean fileNameFix;
if (!formData) {
multiPart.setMediaType(mediaType);
fileNameFix = false;
} else {
// see if the User-Agent header corresponds to some version of MS Internet Explorer
// if so, need to set fileNameFix to true to handle issue http://java.net/jira/browse/JERSEY-759
final String userAgent = headers.getFirst(HttpHeaders.USER_AGENT);
fileNameFix = userAgent != null && userAgent.contains(" MSIE ");
}
for (final MIMEPart mimePart : getMimeParts(mimeMessage)) {
final BodyPart bodyPart = formData ? new FormDataBodyPart(fileNameFix) : new BodyPart();
// Configure providers.
bodyPart.setMessageBodyWorkers(workers);
// Copy headers.
for (final Header header : mimePart.getAllHeaders()) {
bodyPart.getHeaders().add(header.getName(), header.getValue());
}
try {
final String contentType = bodyPart.getHeaders().getFirst("Content-Type");
if (contentType != null) {
bodyPart.setMediaType(MediaType.valueOf(contentType));
}
bodyPart.getContentDisposition();
} catch (final IllegalArgumentException ex) {
throw new BadRequestException(ex);
}
// Copy data into a BodyPartEntity structure.
bodyPart.setEntity(new BodyPartEntity(mimePart));
// Add this BodyPart to our MultiPart.
multiPart.getBodyParts().add(bodyPart);
}
return multiPart;
}
use of org.glassfish.jersey.media.multipart.BodyPartEntity in project jersey by eclipse-ee4j.
the class MultiPartWriter method writeTo.
/**
* Write the entire list of body parts to the output stream, using the
* appropriate provider implementation to serialize each body part's entity.
*
* @param entity the {@link MultiPart} instance to write.
* @param type the class of the object to be written (i.e. {@link MultiPart}.class).
* @param genericType the type of object to be written.
* @param annotations annotations on the resource method that returned this object.
* @param mediaType media type ({@code multipart/*}) of this entity.
* @param headers mutable map of HTTP headers for the entire response.
* @param stream output stream to which the entity should be written.
* @throws java.io.IOException if an I/O error occurs.
* @throws javax.ws.rs.WebApplicationException
* if an HTTP error response
* needs to be produced (only effective if the response is not committed yet).
*/
@Override
public void writeTo(final MultiPart entity, final Class<?> type, final Type genericType, final Annotation[] annotations, final MediaType mediaType, final MultivaluedMap<String, Object> headers, final OutputStream stream) throws IOException, WebApplicationException {
// Verify that there is at least one body part.
if ((entity.getBodyParts() == null) || (entity.getBodyParts().size() < 1)) {
throw new IllegalArgumentException(LocalizationMessages.MUST_SPECIFY_BODY_PART());
}
// If our entity is not nested, make sure the MIME-Version header is set.
if (entity.getParent() == null) {
final Object value = headers.getFirst("MIME-Version");
if (value == null) {
headers.putSingle("MIME-Version", "1.0");
}
}
// Initialize local variables we need.
final Writer writer = new BufferedWriter(new OutputStreamWriter(stream, MessageUtils.getCharset(mediaType)));
// Determine the boundary string to be used, creating one if needed.
final MediaType boundaryMediaType = Boundary.addBoundary(mediaType);
if (boundaryMediaType != mediaType) {
headers.putSingle(HttpHeaders.CONTENT_TYPE, boundaryMediaType.toString());
}
final String boundaryString = boundaryMediaType.getParameters().get("boundary");
// Iterate through the body parts for this message.
boolean isFirst = true;
for (final BodyPart bodyPart : entity.getBodyParts()) {
// Write the leading boundary string
if (isFirst) {
isFirst = false;
writer.write("--");
} else {
writer.write("\r\n--");
}
writer.write(boundaryString);
writer.write("\r\n");
// Write the headers for this body part
final MediaType bodyMediaType = bodyPart.getMediaType();
if (bodyMediaType == null) {
throw new IllegalArgumentException(LocalizationMessages.MISSING_MEDIA_TYPE_OF_BODY_PART());
}
final MultivaluedMap<String, String> bodyHeaders = bodyPart.getHeaders();
bodyHeaders.putSingle("Content-Type", bodyMediaType.toString());
if (bodyHeaders.getFirst("Content-Disposition") == null && bodyPart.getContentDisposition() != null) {
bodyHeaders.putSingle("Content-Disposition", bodyPart.getContentDisposition().toString());
}
// Iterate for the nested body parts
for (final Map.Entry<String, List<String>> entry : bodyHeaders.entrySet()) {
// Write this header and its value(s)
writer.write(entry.getKey());
writer.write(':');
boolean first = true;
for (final String value : entry.getValue()) {
if (first) {
writer.write(' ');
first = false;
} else {
writer.write(',');
}
writer.write(value);
}
writer.write("\r\n");
}
// Mark the end of the headers for this body part
writer.write("\r\n");
writer.flush();
// Write the entity for this body part
Object bodyEntity = bodyPart.getEntity();
if (bodyEntity == null) {
throw new IllegalArgumentException(LocalizationMessages.MISSING_ENTITY_OF_BODY_PART(bodyMediaType));
}
Class bodyClass = bodyEntity.getClass();
if (bodyEntity instanceof BodyPartEntity) {
bodyClass = InputStream.class;
bodyEntity = ((BodyPartEntity) bodyEntity).getInputStream();
}
final MessageBodyWriter bodyWriter = providers.getMessageBodyWriter(bodyClass, bodyClass, EMPTY_ANNOTATIONS, bodyMediaType);
if (bodyWriter == null) {
throw new IllegalArgumentException(LocalizationMessages.NO_AVAILABLE_MBW(bodyClass, mediaType));
}
bodyWriter.writeTo(bodyEntity, bodyClass, bodyClass, EMPTY_ANNOTATIONS, bodyMediaType, bodyHeaders, stream);
}
// Write the final boundary string
writer.write("\r\n--");
writer.write(boundaryString);
writer.write("--\r\n");
writer.flush();
}
use of org.glassfish.jersey.media.multipart.BodyPartEntity in project vnfsdk-refrepo by onap.
the class VTPExecutionResource method storeTestCaseInputFiles.
private Map<String, String> storeTestCaseInputFiles(List<FormDataBodyPart> bodyParts) throws IOException {
Map<String, String> map = new HashMap<>();
if (bodyParts != null) {
for (FormDataBodyPart part : bodyParts) {
String name = part.getContentDisposition().getFileName();
// NOSONAR
String path = VTP_EXECUTION_TEMP_STORE + "/" + name;
File f = new File(path);
if (f.exists()) {
FileUtils.forceDelete(f);
}
FileUtils.forceMkdir(f.getParentFile());
BodyPartEntity fileEntity = (BodyPartEntity) part.getEntity();
java.nio.file.Files.copy(fileEntity.getInputStream(), f.toPath(), StandardCopyOption.REPLACE_EXISTING);
IOUtils.closeQuietly(fileEntity.getInputStream());
map.put(name, path);
}
}
return map;
}
use of org.glassfish.jersey.media.multipart.BodyPartEntity in project vnfsdk-refrepo by onap.
the class VTPScenarioResource method storageTestcases.
@Path("/testcases")
@POST
@ApiOperation(tags = "VTP Scenario", value = "Create test case")
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.APPLICATION_JSON)
@ApiResponses(value = { @ApiResponse(code = HttpStatus.INTERNAL_SERVER_ERROR_500, message = "Failed to perform the operation", response = VTPError.class) })
public Response storageTestcases(@ApiParam(value = "file form data body parts", required = true) @FormDataParam("files") List<FormDataBodyPart> bodyParts) throws VTPException {
bodyParts.forEach(bodyPart -> {
BodyPartEntity entity = (BodyPartEntity) bodyPart.getEntity();
String fileName = bodyPart.getContentDisposition().getFileName();
if (ToolUtil.isYamlFile(new File(fileName))) {
// 1、store the testcase yaml file
Map<String, Object> result = snakeYaml().load(entity.getInputStream());
Map<String, Object> info = (Map<String, Object>) result.get("info");
File yamlFile = new File(VTP_YAML_STORE, info.get(PRODUCT) + File.separator + info.get(SERVICE) + File.separator + fileName);
try {
FileUtils.deleteQuietly(yamlFile);
FileUtils.copyInputStreamToFile(entity.getInputStream(), yamlFile);
} catch (IOException e) {
LOG.error("Save testcase yaml {} failed", yamlFile.getName(), e);
}
} else {
// 2、store the testcase script file
File scriptFile = new File(VTP_SCRIPT_STORE, fileName);
try {
FileUtils.deleteQuietly(scriptFile);
FileUtils.copyInputStreamToFile(entity.getInputStream(), scriptFile);
} catch (IOException e) {
LOG.error("Save testcase script {} failed", scriptFile.getName(), e);
}
}
});
return Response.ok("Save success", MediaType.APPLICATION_JSON).build();
}
Aggregations