use of javax.ws.rs.core.MultivaluedMap in project jersey by jersey.
the class FreemarkerViewProcessor method writeTo.
@Override
public void writeTo(final Template template, final Viewable viewable, final MediaType mediaType, final MultivaluedMap<String, Object> httpHeaders, final OutputStream out) throws IOException {
try {
Object model = viewable.getModel();
if (!(model instanceof Map)) {
model = new HashMap<String, Object>() {
{
put("model", viewable.getModel());
}
};
}
Charset encoding = setContentType(mediaType, httpHeaders);
template.process(model, new OutputStreamWriter(out, encoding));
} catch (TemplateException te) {
throw new ContainerException(te);
}
}
use of javax.ws.rs.core.MultivaluedMap in project jersey by jersey.
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 javax.ws.rs.core.MultivaluedMap in project jersey by jersey.
the class FormMultivaluedMapProviderTest method readFrom.
@SuppressWarnings("unchecked")
private static MultivaluedMap<String, String> readFrom(String body) {
try {
InputStream stream = new ByteArrayInputStream(body.getBytes(StandardCharsets.UTF_8));
Class<MultivaluedMap<String, String>> clazz = (Class<MultivaluedMap<String, String>>) (Class<?>) MultivaluedHashMap.class;
return PROVIDER.readFrom(clazz, clazz, new Annotation[] {}, MediaType.APPLICATION_FORM_URLENCODED_TYPE, null, stream);
} catch (IOException e) {
throw new RuntimeException("Unexpected exception", e);
}
}
use of javax.ws.rs.core.MultivaluedMap in project jersey by jersey.
the class RequestUtil method getEntityParameters.
/**
* Returns the form parameters from a request entity as a multi-valued map.
* If the request does not have a POST method, or the media type is not
* x-www-form-urlencoded, then null is returned.
*
* @param request the client request containing the entity to extract parameters from.
* @return a {@link javax.ws.rs.core.MultivaluedMap} containing the entity form parameters.
*/
@SuppressWarnings("unchecked")
public static MultivaluedMap<String, String> getEntityParameters(ClientRequestContext request, MessageBodyWorkers messageBodyWorkers) {
Object entity = request.getEntity();
String method = request.getMethod();
MediaType mediaType = request.getMediaType();
// no entity, not a post or not x-www-form-urlencoded: return empty map
if (entity == null || method == null || !HttpMethod.POST.equalsIgnoreCase(method) || mediaType == null || !mediaType.equals(MediaType.APPLICATION_FORM_URLENCODED_TYPE)) {
return new MultivaluedHashMap<String, String>();
}
// it's ready to go if already expressed as a multi-valued map
if (entity instanceof MultivaluedMap) {
return (MultivaluedMap<String, String>) entity;
}
Type entityType = entity.getClass();
// if the entity is generic, get specific type and class
if (entity instanceof GenericEntity) {
final GenericEntity generic = (GenericEntity) entity;
// overwrite
entityType = generic.getType();
entity = generic.getEntity();
}
final Class entityClass = entity.getClass();
ByteArrayOutputStream out = new ByteArrayOutputStream();
MessageBodyWriter writer = messageBodyWorkers.getMessageBodyWriter(entityClass, entityType, EMPTY_ANNOTATIONS, MediaType.APPLICATION_FORM_URLENCODED_TYPE);
try {
writer.writeTo(entity, entityClass, entityType, EMPTY_ANNOTATIONS, MediaType.APPLICATION_FORM_URLENCODED_TYPE, null, out);
} catch (WebApplicationException wae) {
throw new IllegalStateException(wae);
} catch (IOException ioe) {
throw new IllegalStateException(ioe);
}
ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
MessageBodyReader reader = messageBodyWorkers.getMessageBodyReader(MultivaluedMap.class, MultivaluedMap.class, EMPTY_ANNOTATIONS, MediaType.APPLICATION_FORM_URLENCODED_TYPE);
try {
return (MultivaluedMap<String, String>) reader.readFrom(MultivaluedMap.class, MultivaluedMap.class, EMPTY_ANNOTATIONS, MediaType.APPLICATION_FORM_URLENCODED_TYPE, null, in);
} catch (IOException ioe) {
throw new IllegalStateException(ioe);
}
}
use of javax.ws.rs.core.MultivaluedMap in project jersey by jersey.
the class InMemoryConnector method apply.
/**
* {@inheritDoc}
* <p/>
* Transforms client-side request to server-side and invokes it on provided application ({@link ApplicationHandler}
* instance).
*
* @param clientRequest client side request to be invoked.
*/
@Override
public ClientResponse apply(final ClientRequest clientRequest) {
PropertiesDelegate propertiesDelegate = new MapPropertiesDelegate();
final ContainerRequest containerRequest = new ContainerRequest(baseUri, clientRequest.getUri(), clientRequest.getMethod(), null, propertiesDelegate);
containerRequest.getHeaders().putAll(clientRequest.getStringHeaders());
final ByteArrayOutputStream clientOutput = new ByteArrayOutputStream();
if (clientRequest.getEntity() != null) {
clientRequest.setStreamProvider(new OutboundMessageContext.StreamProvider() {
@Override
public OutputStream getOutputStream(int contentLength) throws IOException {
final MultivaluedMap<String, Object> clientHeaders = clientRequest.getHeaders();
if (contentLength != -1 && !clientHeaders.containsKey(HttpHeaders.CONTENT_LENGTH)) {
containerRequest.getHeaders().putSingle(HttpHeaders.CONTENT_LENGTH, String.valueOf(contentLength));
}
return clientOutput;
}
});
clientRequest.enableBuffering();
try {
clientRequest.writeEntity();
} catch (IOException e) {
final String msg = "Error while writing entity to the output stream.";
LOGGER.log(Level.SEVERE, msg, e);
throw new ProcessingException(msg, e);
}
}
containerRequest.setEntityStream(new ByteArrayInputStream(clientOutput.toByteArray()));
boolean followRedirects = ClientProperties.getValue(clientRequest.getConfiguration().getProperties(), ClientProperties.FOLLOW_REDIRECTS, true);
final InMemoryResponseWriter inMemoryResponseWriter = new InMemoryResponseWriter();
containerRequest.setWriter(inMemoryResponseWriter);
containerRequest.setSecurityContext(new SecurityContext() {
@Override
public Principal getUserPrincipal() {
return null;
}
@Override
public boolean isUserInRole(String role) {
return false;
}
@Override
public boolean isSecure() {
return false;
}
@Override
public String getAuthenticationScheme() {
return null;
}
});
appHandler.handle(containerRequest);
return tryFollowRedirects(followRedirects, createClientResponse(clientRequest, inMemoryResponseWriter), new ClientRequest(clientRequest));
}
Aggregations