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));
}
use of javax.ws.rs.core.MultivaluedMap in project jersey by jersey.
the class EntityTypesTest method testFormMultivaluedMapRepresentation.
@Test
public void testFormMultivaluedMapRepresentation() {
final MultivaluedMap<String, String> fp = new MultivaluedStringMap();
fp.add("Email", "johndoe@gmail.com");
fp.add("Passwd", "north 23AZ");
fp.add("service", "cl");
fp.add("source", "Gulp-CalGul-1.05");
fp.add("source", "foo.java");
fp.add("source", "bar.java");
final WebTarget target = target("FormMultivaluedMapResource");
final MultivaluedMap _fp = target.request().post(Entity.entity(fp, "application/x-www-form-urlencoded"), MultivaluedMap.class);
assertEquals(fp, _fp);
}
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 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 midpoint by Evolveum.
the class MidpointAbstractProvider method readFrom.
@Override
public T readFrom(Class<T> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream) throws IOException, WebApplicationException {
if (entityStream == null) {
return null;
}
PrismParser parser = getParser(entityStream);
T object;
try {
LOGGER.info("type of request: {}", type);
if (PrismObject.class.isAssignableFrom(type)) {
object = (T) parser.parse();
} else {
// TODO consider prescribing type here (if no convertor is specified)
object = parser.parseRealValue();
}
if (object != null && !type.isAssignableFrom(object.getClass())) {
// TODO treat multivalues here
Optional<Annotation> convertorAnnotation = Arrays.stream(annotations).filter(a -> a instanceof Convertor).findFirst();
if (convertorAnnotation.isPresent()) {
Class<? extends ConvertorInterface> convertorClass = ((Convertor) convertorAnnotation.get()).value();
ConvertorInterface convertor;
try {
convertor = convertorClass.newInstance();
} catch (InstantiationException | IllegalAccessException e) {
throw new SystemException("Couldn't instantiate convertor class " + convertorClass, e);
}
object = (T) convertor.convert(object);
}
}
return object;
} catch (SchemaException ex) {
throw new WebApplicationException(ex);
}
}
Aggregations