use of javax.ws.rs.core.MediaType in project jersey by jersey.
the class CharsetTest method _test.
@Override
public <T> void _test(T in, Class resource, MediaType m) {
WebTarget t = target(resource.getSimpleName());
for (String charset : CHARSETS) {
Map<String, String> p = new HashMap<>();
p.put("charset", charset);
MediaType _m = new MediaType(m.getType(), m.getSubtype(), p);
Response rib = t.request().post(Entity.entity(in, _m));
byte[] inBytes = getRequestEntity();
byte[] outBytes = getEntityAsByteArray(rib);
_verify(inBytes, outBytes);
}
}
use of javax.ws.rs.core.MediaType in project jersey by jersey.
the class ModelProcessorUtil method enhanceResource.
/**
* Enhance the runtime resource referenced by {@code resource} parameter with a list of additional methods.
*
* The new {@code methods} are added to the runtime resource. In case of method conflicts, the existing resource methods
* will be preserved and will not be 'overridden' by any new method from the {@code methods} list.
* Overriding check takes into account media types of methods so that new resource methods with same HTTP method
* can be defined only for a more more specific media type.
*
* @param resource Runtime resource to be enhanced.
* @param enhancedModelBuilder Builder for the enhanced resource model to be used.
* @param methods List of enhancing methods.
* @param extended This flag will initialize the property
* {@link org.glassfish.jersey.server.model.ResourceMethod#isExtended()}.
*/
public static void enhanceResource(RuntimeResource resource, ResourceModel.Builder enhancedModelBuilder, List<Method> methods, boolean extended) {
final Resource firstResource = resource.getResources().get(0);
if (methodsSuitableForResource(firstResource, methods)) {
for (Method method : methods) {
final Set<MediaType> produces = new HashSet<>(method.produces);
for (ResourceMethod resourceMethod : resource.getResourceMethods()) {
for (final MediaType produce : method.produces) {
if (ModelProcessorUtil.isMethodOverridden(resourceMethod, method.httpMethod, method.consumes.get(0), produce)) {
produces.remove(produce);
}
}
}
if (!produces.isEmpty()) {
final Resource parentResource = resource.getParentResources().get(0);
if (parentResource != null && method.path != null) {
continue;
}
final Resource.Builder resourceBuilder = Resource.builder(firstResource.getPath());
final Resource.Builder builder = method.path != null ? resourceBuilder.addChildResource(method.path) : resourceBuilder;
final ResourceMethod.Builder methodBuilder = builder.addMethod(method.httpMethod).consumes(method.consumes).produces(produces);
if (method.inflector != null) {
methodBuilder.handledBy(method.inflector);
} else {
methodBuilder.handledBy(method.inflectorClass);
}
methodBuilder.extended(extended);
final Resource newResource = resourceBuilder.build();
if (parentResource != null) {
final Resource.Builder parentBuilder = Resource.builder(parentResource.getPath());
parentBuilder.addChildResource(newResource);
enhancedModelBuilder.addResource(parentBuilder.build());
} else {
enhancedModelBuilder.addResource(newResource);
}
}
}
}
for (RuntimeResource child : resource.getChildRuntimeResources()) {
enhanceResource(child, enhancedModelBuilder, methods, extended);
}
}
use of javax.ws.rs.core.MediaType in project jersey by jersey.
the class IntrospectionModeller method doCreateResourceBuilder.
private Resource.Builder doCreateResourceBuilder() {
if (!disableValidation) {
checkForNonPublicMethodIssues();
}
final Class<?> annotatedResourceClass = ModelHelper.getAnnotatedResourceClass(handlerClass);
final Path rPathAnnotation = annotatedResourceClass.getAnnotation(Path.class);
final boolean keepEncodedParams = (null != annotatedResourceClass.getAnnotation(Encoded.class));
final List<MediaType> defaultConsumedTypes = extractMediaTypes(annotatedResourceClass.getAnnotation(Consumes.class));
final List<MediaType> defaultProducedTypes = extractMediaTypes(annotatedResourceClass.getAnnotation(Produces.class));
final Collection<Class<? extends Annotation>> defaultNameBindings = ReflectionHelper.getAnnotationTypes(annotatedResourceClass, NameBinding.class);
final MethodList methodList = new MethodList(handlerClass);
final List<Parameter> resourceClassParameters = new LinkedList<>();
checkResourceClassSetters(methodList, keepEncodedParams, resourceClassParameters);
checkResourceClassFields(keepEncodedParams, InvocableValidator.isSingleton(handlerClass), resourceClassParameters);
Resource.Builder resourceBuilder;
if (null != rPathAnnotation) {
resourceBuilder = Resource.builder(rPathAnnotation.value());
} else {
resourceBuilder = Resource.builder();
}
boolean extended = false;
if (handlerClass.isAnnotationPresent(ExtendedResource.class)) {
resourceBuilder.extended(true);
extended = true;
}
resourceBuilder.name(handlerClass.getName());
addResourceMethods(resourceBuilder, methodList, resourceClassParameters, keepEncodedParams, defaultConsumedTypes, defaultProducedTypes, defaultNameBindings, extended);
addSubResourceMethods(resourceBuilder, methodList, resourceClassParameters, keepEncodedParams, defaultConsumedTypes, defaultProducedTypes, defaultNameBindings, extended);
addSubResourceLocators(resourceBuilder, methodList, resourceClassParameters, keepEncodedParams, extended);
if (LOGGER.isLoggable(Level.FINEST)) {
LOGGER.finest(LocalizationMessages.NEW_AR_CREATED_BY_INTROSPECTION_MODELER(resourceBuilder.toString()));
}
return resourceBuilder;
}
use of javax.ws.rs.core.MediaType in project jersey by jersey.
the class JaxbStringReaderProviderTest method stringReaderDoesNotReadExternalDtds.
@Test
public void stringReaderDoesNotReadExternalDtds() {
Provider<SAXParserFactory> saxParserFactoryProvider = new Provider<SAXParserFactory>() {
final SaxParserFactoryInjectionProvider spf = new SaxParserFactoryInjectionProvider(new CommonConfig(RuntimeType.SERVER, ComponentBag.INCLUDE_ALL));
@Override
public SAXParserFactory get() {
return spf.get();
}
};
JaxbStringReaderProvider.RootElementProvider provider = new JaxbStringReaderProvider.RootElementProvider(saxParserFactoryProvider, new Providers() {
@Override
public <T> MessageBodyReader<T> getMessageBodyReader(Class<T> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
return null;
}
@Override
public <T> MessageBodyWriter<T> getMessageBodyWriter(Class<T> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
return null;
}
@Override
public <T extends Throwable> ExceptionMapper<T> getExceptionMapper(Class<T> type) {
return null;
}
@Override
public <T> ContextResolver<T> getContextResolver(Class<T> contextType, MediaType mediaType) {
return null;
}
});
String content = "<!DOCTYPE x SYSTEM 'file:///no-such-file'> <rootObject/>";
provider.getConverter(RootObject.class, null, null).fromString(content);
}
use of javax.ws.rs.core.MediaType 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();
}
Aggregations