use of java.lang.reflect.Type in project morphia by mongodb.
the class ReflectionUtils method getParameterizedClass.
/**
* Get the class that parameterizes the Field supplied, at the index supplied (field can be parameterized with multiple param classes).
*
* @param field the field
* @param index the index of the parameterizing class
* @return the class that parameterizes the field, or null if field is not parameterized
*/
public static Class getParameterizedClass(final Field field, final int index) {
if (field.getGenericType() instanceof ParameterizedType) {
final ParameterizedType type = (ParameterizedType) field.getGenericType();
if ((type.getActualTypeArguments() != null) && (type.getActualTypeArguments().length <= index)) {
return null;
}
final Type paramType = type.getActualTypeArguments()[index];
if (paramType instanceof GenericArrayType) {
final Class arrayType = (Class) ((GenericArrayType) paramType).getGenericComponentType();
return Array.newInstance(arrayType, 0).getClass();
} else {
if (paramType instanceof ParameterizedType) {
final ParameterizedType paramPType = (ParameterizedType) paramType;
return (Class) paramPType.getRawType();
} else {
if (paramType instanceof TypeVariable) {
// from the T/V/X
throw new MappingException("Generic Typed Class not supported: <" + ((TypeVariable) paramType).getName() + "> = " + ((TypeVariable) paramType).getBounds()[0]);
} else if (paramType instanceof Class) {
return (Class) paramType;
} else {
throw new MappingException("Unknown type... pretty bad... call for help, wave your hands... yeah!");
}
}
}
}
return getParameterizedClass(field.getType());
}
use of java.lang.reflect.Type in project morphia by mongodb.
the class ReflectionUtils method getClass.
/**
* Get the underlying class for a type, or null if the type is a variable type.
*
* @param type the type
* @return the underlying class
*/
public static Class<?> getClass(final Type type) {
if (type instanceof Class) {
return (Class) type;
} else if (type instanceof ParameterizedType) {
return getClass(((ParameterizedType) type).getRawType());
} else if (type instanceof GenericArrayType) {
final Type componentType = ((GenericArrayType) type).getGenericComponentType();
final Class<?> componentClass = getClass(componentType);
if (componentClass != null) {
return Array.newInstance(componentClass, 0).getClass();
} else {
LOG.debug("************ ReflectionUtils.getClass 1st else");
LOG.debug("************ type = " + type);
return null;
}
} else {
LOG.debug("************ ReflectionUtils.getClass final else");
LOG.debug("************ type = " + type);
return null;
}
}
use of java.lang.reflect.Type in project jersey by jersey.
the class GenericMethodListTest method testGeneriInterfaceClasses.
@Test
public void testGeneriInterfaceClasses() {
MethodList ml = new MethodList(IResource.class);
Iterator<AnnotatedMethod> i = ml.iterator();
assertTrue(i.hasNext());
AnnotatedMethod am = i.next();
Method m = am.getMethod();
Type[] types = m.getGenericParameterTypes();
assertTrue(types[0] instanceof TypeVariable);
assertTrue(types[1] instanceof Class);
assertTrue(types[2] instanceof TypeVariable);
}
use of java.lang.reflect.Type in project jersey by jersey.
the class WebResourceFactory method invoke.
@Override
@SuppressWarnings("unchecked")
public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable {
if (args == null && method.getName().equals("toString")) {
return toString();
}
if (args == null && method.getName().equals("hashCode")) {
//unique instance in the JVM, and no need to override
return hashCode();
}
if (args != null && args.length == 1 && method.getName().equals("equals")) {
//unique instance in the JVM, and no need to override
return equals(args[0]);
}
// get the interface describing the resource
final Class<?> proxyIfc = proxy.getClass().getInterfaces()[0];
// response type
final Class<?> responseType = method.getReturnType();
// determine method name
String httpMethod = getHttpMethodName(method);
if (httpMethod == null) {
for (final Annotation ann : method.getAnnotations()) {
httpMethod = getHttpMethodName(ann.annotationType());
if (httpMethod != null) {
break;
}
}
}
// create a new UriBuilder appending the @Path attached to the method
WebTarget newTarget = addPathFromAnnotation(method, target);
if (httpMethod == null) {
if (newTarget == target) {
// no path annotation on the method -> fail
throw new UnsupportedOperationException("Not a resource method.");
} else if (!responseType.isInterface()) {
// not interface - can't help here
throw new UnsupportedOperationException("Return type not an interface");
}
}
// process method params (build maps of (Path|Form|Cookie|Matrix|Header..)Params
// and extract entity type
final MultivaluedHashMap<String, Object> headers = new MultivaluedHashMap<String, Object>(this.headers);
final LinkedList<Cookie> cookies = new LinkedList<>(this.cookies);
final Form form = new Form();
form.asMap().putAll(this.form.asMap());
final Annotation[][] paramAnns = method.getParameterAnnotations();
Object entity = null;
Type entityType = null;
for (int i = 0; i < paramAnns.length; i++) {
final Map<Class, Annotation> anns = new HashMap<>();
for (final Annotation ann : paramAnns[i]) {
anns.put(ann.annotationType(), ann);
}
Annotation ann;
Object value = args[i];
if (!hasAnyParamAnnotation(anns)) {
entityType = method.getGenericParameterTypes()[i];
entity = value;
} else {
if (value == null && (ann = anns.get(DefaultValue.class)) != null) {
value = ((DefaultValue) ann).value();
}
if (value != null) {
if ((ann = anns.get(PathParam.class)) != null) {
newTarget = newTarget.resolveTemplate(((PathParam) ann).value(), value);
} else if ((ann = anns.get((QueryParam.class))) != null) {
if (value instanceof Collection) {
newTarget = newTarget.queryParam(((QueryParam) ann).value(), convert((Collection) value));
} else {
newTarget = newTarget.queryParam(((QueryParam) ann).value(), value);
}
} else if ((ann = anns.get((HeaderParam.class))) != null) {
if (value instanceof Collection) {
headers.addAll(((HeaderParam) ann).value(), convert((Collection) value));
} else {
headers.addAll(((HeaderParam) ann).value(), value);
}
} else if ((ann = anns.get((CookieParam.class))) != null) {
final String name = ((CookieParam) ann).value();
Cookie c;
if (value instanceof Collection) {
for (final Object v : ((Collection) value)) {
if (!(v instanceof Cookie)) {
c = new Cookie(name, v.toString());
} else {
c = (Cookie) v;
if (!name.equals(((Cookie) v).getName())) {
// is this the right thing to do? or should I fail? or ignore the difference?
c = new Cookie(name, c.getValue(), c.getPath(), c.getDomain(), c.getVersion());
}
}
cookies.add(c);
}
} else {
if (!(value instanceof Cookie)) {
cookies.add(new Cookie(name, value.toString()));
} else {
c = (Cookie) value;
if (!name.equals(((Cookie) value).getName())) {
// is this the right thing to do? or should I fail? or ignore the difference?
cookies.add(new Cookie(name, c.getValue(), c.getPath(), c.getDomain(), c.getVersion()));
}
}
}
} else if ((ann = anns.get((MatrixParam.class))) != null) {
if (value instanceof Collection) {
newTarget = newTarget.matrixParam(((MatrixParam) ann).value(), convert((Collection) value));
} else {
newTarget = newTarget.matrixParam(((MatrixParam) ann).value(), value);
}
} else if ((ann = anns.get((FormParam.class))) != null) {
if (value instanceof Collection) {
for (final Object v : ((Collection) value)) {
form.param(((FormParam) ann).value(), v.toString());
}
} else {
form.param(((FormParam) ann).value(), value.toString());
}
}
}
}
}
if (httpMethod == null) {
// the method is a subresource locator
return WebResourceFactory.newResource(responseType, newTarget, true, headers, cookies, form);
}
// accepted media types
Produces produces = method.getAnnotation(Produces.class);
if (produces == null) {
produces = proxyIfc.getAnnotation(Produces.class);
}
final String[] accepts = (produces == null) ? EMPTY : produces.value();
// determine content type
String contentType = null;
if (entity != null) {
final List<Object> contentTypeEntries = headers.get(HttpHeaders.CONTENT_TYPE);
if ((contentTypeEntries != null) && (!contentTypeEntries.isEmpty())) {
contentType = contentTypeEntries.get(0).toString();
} else {
Consumes consumes = method.getAnnotation(Consumes.class);
if (consumes == null) {
consumes = proxyIfc.getAnnotation(Consumes.class);
}
if (consumes != null && consumes.value().length > 0) {
contentType = consumes.value()[0];
}
}
}
Invocation.Builder builder = newTarget.request().headers(// this resets all headers so do this first
headers).accept(// if @Produces is defined, propagate values into Accept header; empty array is NO-OP
accepts);
for (final Cookie c : cookies) {
builder = builder.cookie(c);
}
final Object result;
if (entity == null && !form.asMap().isEmpty()) {
entity = form;
contentType = MediaType.APPLICATION_FORM_URLENCODED;
} else {
if (contentType == null) {
contentType = MediaType.APPLICATION_OCTET_STREAM;
}
if (!form.asMap().isEmpty()) {
if (entity instanceof Form) {
((Form) entity).asMap().putAll(form.asMap());
} else {
// TODO: should at least log some warning here
}
}
}
final GenericType responseGenericType = new GenericType(method.getGenericReturnType());
if (entity != null) {
if (entityType instanceof ParameterizedType) {
entity = new GenericEntity(entity, entityType);
}
result = builder.method(httpMethod, Entity.entity(entity, contentType), responseGenericType);
} else {
result = builder.method(httpMethod, responseGenericType);
}
return result;
}
use of java.lang.reflect.Type in project jersey by jersey.
the class NaiveResourceMappingContext method buildMappings.
private void buildMappings() {
if (mappings != null) {
return;
}
mappings = new HashMap<>();
erc.getResourceModel().accept(new ResourceModelVisitor() {
Deque<PathPattern> stack = new LinkedList<>();
private void processComponents(final ResourceModelComponent component) {
final List<? extends ResourceModelComponent> components = component.getComponents();
if (components != null) {
for (final ResourceModelComponent rc : components) {
rc.accept(this);
}
}
}
@Override
public void visitInvocable(final Invocable invocable) {
processComponents(invocable);
}
@Override
public void visitRuntimeResource(final RuntimeResource runtimeResource) {
processComponents(runtimeResource);
}
@Override
public void visitResourceModel(final ResourceModel resourceModel) {
processComponents(resourceModel);
}
@Override
public void visitResourceHandlerConstructor(final HandlerConstructor handlerConstructor) {
processComponents(handlerConstructor);
}
@Override
public void visitMethodHandler(final MethodHandler methodHandler) {
processComponents(methodHandler);
}
@Override
public void visitChildResource(final Resource resource) {
visitResourceIntl(resource, false);
}
@Override
public void visitResource(final Resource resource) {
visitResourceIntl(resource, true);
}
private void visitResourceIntl(final Resource resource, final boolean isRoot) {
try {
stack.addLast(resource.getPathPattern());
processComponents(resource);
if (isRoot) {
Class likelyToBeRoot = null;
for (final Class next : resource.getHandlerClasses()) {
if (!(Inflector.class.isAssignableFrom(next))) {
likelyToBeRoot = next;
}
}
if (likelyToBeRoot != null) {
mappings.put(likelyToBeRoot, getMapping(getTemplate()));
}
}
} finally {
stack.removeLast();
}
}
@Override
public void visitResourceMethod(final ResourceMethod resourceMethod) {
if (resourceMethod.isExtended()) {
return;
}
if (ResourceMethod.JaxrsType.SUB_RESOURCE_LOCATOR.equals(resourceMethod.getType())) {
if (resourceMethod.getInvocable() != null) {
final Invocable i = resourceMethod.getInvocable();
final Type type = i.getResponseType();
final StringBuilder template = getTemplate();
mappings.put((Class) type, getMapping(template));
// Process sub resources ?
Resource.Builder builder = Resource.builder(i.getRawResponseType());
if (builder == null) {
// for example in the case the return type of the sub resource locator is Object
builder = Resource.builder().path(resourceMethod.getParent().getPath());
}
final Resource subResource = builder.build();
visitChildResource(subResource);
}
}
processComponents(resourceMethod);
}
private StringBuilder getTemplate() {
final StringBuilder template = new StringBuilder();
for (final PathPattern pp : stack) {
final String ppTemplate = pp.getTemplate().getTemplate();
final int tlength = template.length();
if (tlength > 0) {
if (template.charAt(tlength - 1) == '/') {
if (ppTemplate.startsWith("/")) {
template.append(ppTemplate, 1, ppTemplate.length());
} else {
template.append(ppTemplate);
}
} else {
if (ppTemplate.startsWith("/")) {
template.append(ppTemplate);
} else {
template.append("/");
template.append(ppTemplate);
}
}
} else {
template.append(ppTemplate);
}
}
return template;
}
});
}
Aggregations