private static synchronized void checkClientExceptionMapper() {
   if (ResteasyProviderFactory.getInstance().getClientExceptionMapper(Exception.class) == null) {
     Type exceptionType =
         Types.getActualTypeArgumentsOfAnInterface(
             ApacheHttpClient4ExceptionMapper.class, ClientExceptionMapper.class)[0];
     ResteasyProviderFactory.getInstance()
         .addClientExceptionMapper(new ApacheHttpClient4ExceptionMapper(), exceptionType);
   }
 }
Пример #2
0
 protected boolean isWrapped(
     Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
   if ((Collection.class.isAssignableFrom(type) || type.isArray()) && genericType != null) {
     Class<?> baseType = Types.getCollectionBaseType(type, genericType);
     return baseType != null
         && Variable.class.isAssignableFrom(baseType)
         && !IgnoredMediaTypes.ignored(baseType, annotations, mediaType);
   }
   return false;
 }
Пример #3
0
 public ResourceLocator(ResourceClass resourceClass, Method method, Method annotatedMethod) {
   this.resourceClass = resourceClass;
   this.annotatedMethod = annotatedMethod;
   this.method = method;
   // we initialize generic types based on the method of the resource class rather than the Method
   // that is actually
   // annotated.  This is so we have the appropriate generic type information.
   this.genericReturnType =
       Types.resolveTypeVariables(resourceClass.getClazz(), method.getGenericReturnType());
   this.returnType = Types.getRawType(genericReturnType);
   this.params = new MethodParameter[method.getParameterTypes().length];
   for (int i = 0; i < method.getParameterTypes().length; i++) {
     this.params[i] =
         new MethodParameter(
             this,
             method.getParameterTypes()[i],
             method.getGenericParameterTypes()[i],
             annotatedMethod.getParameterAnnotations()[i]);
   }
 }
Пример #4
0
  public void writeTo(
      Object entry,
      Class<?> type,
      Type genericType,
      Annotation[] annotations,
      MediaType mediaType,
      MultivaluedMap<String, Object> httpHeaders,
      OutputStream entityStream)
      throws IOException, WebApplicationException {
    JAXBContextFinder finder = getFinder(mediaType);
    if (finder == null) {
      throw new JAXBMarshalException("Unable to find JAXBContext for media type: " + mediaType);
    }
    Class baseType = Types.getCollectionBaseType(type, genericType);
    try {
      JAXBContext ctx =
          finder.findCacheContext(mediaType, annotations, JaxbCollection.class, baseType);
      JaxbCollection col = new JaxbCollection();
      if (type.isArray()) {
        Object[] array = (Object[]) entry;
        for (Object obj : array) {
          col.getValue().add(obj);
        }
      } else {
        Collection collection = (Collection) entry;
        for (Object obj : collection) col.getValue().add(obj);
      }

      String element = "collection";
      String namespaceURI = "";
      String prefix = "";

      Wrapped wrapped = FindAnnotation.findAnnotation(annotations, Wrapped.class);
      if (wrapped != null) {
        element = wrapped.element();
        namespaceURI = wrapped.namespace();
        prefix = wrapped.prefix();
      }

      JAXBElement<JaxbCollection> collection =
          new JAXBElement<JaxbCollection>(
              new QName(namespaceURI, element, prefix), JaxbCollection.class, col);
      Marshaller marshaller = ctx.createMarshaller();
      AbstractJAXBProvider.decorateMarshaller(baseType, annotations, mediaType, marshaller);
      marshaller.marshal(collection, entityStream);
    } catch (JAXBException e) {
      throw new JAXBMarshalException(e);
    }
  }
  @Override
  public void writeTo(
      JAXBElement<?> t,
      Class<?> type,
      Type genericType,
      Annotation[] annotations,
      MediaType mediaType,
      MultivaluedMap<String, Object> httpHeaders,
      OutputStream outputStream)
      throws IOException {

    Class<?> typeArg = Object.class;
    if (genericType != null) typeArg = Types.getTypeArgument(genericType);
    super.writeTo(t, typeArg, genericType, annotations, mediaType, httpHeaders, outputStream);
  }
Пример #6
0
 protected boolean isWrapped(
     Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
   if ((Collection.class.isAssignableFrom(type) || type.isArray()) && genericType != null) {
     Class baseType = Types.getCollectionBaseType(type, genericType);
     if (baseType == null) return false;
     return (baseType.isAnnotationPresent(XmlRootElement.class)
             || baseType.isAnnotationPresent(XmlType.class)
             || baseType.isAnnotationPresent(XmlSeeAlso.class)
             || JAXBElement.class.equals(baseType))
         && (FindAnnotation.findAnnotation(baseType, annotations, DoNotUseJAXBProvider.class)
             == null)
         && !IgnoredMediaTypes.ignored(baseType, annotations, mediaType);
   }
   return false;
 }
Пример #7
0
  @Test
  public void testGetImplementationReflection() throws Exception {
    Class updatableResource = BackendDataCenterResource.class.getInterfaces()[0].getInterfaces()[0];
    Assert.assertEquals(updatableResource, UpdatableResource.class);
    Method update = null;
    for (Method method : updatableResource.getMethods()) {
      if (method.getName().equals("update")) update = method;
    }
    Assert.assertNotNull(update);

    Method implemented = Types.getImplementingMethod(BackendDataCenterResource.class, update);

    Method actual = null;
    for (Method method : BackendDataCenterResource.class.getMethods()) {
      if (method.getName().equals("update") && !method.isSynthetic()) actual = method;
    }

    Assert.assertEquals(implemented, actual);
  }
Пример #8
0
  private static Method findAnnotatedInterfaceMethod(
      Class<?> root, Class<?> iface, Method implementation) {
    for (Method method : iface.getMethods()) {
      if (method.isSynthetic()) continue;

      if (!method.getName().equals(implementation.getName())) continue;
      if (method.getParameterTypes().length != implementation.getParameterTypes().length) continue;

      Method actual = Types.getImplementingMethod(root, method);
      if (!actual.equals(implementation)) continue;

      if (method.isAnnotationPresent(Path.class) || IsHttpMethod.getHttpMethods(method) != null)
        return method;
    }
    for (Class<?> extended : iface.getInterfaces()) {
      Method m = findAnnotatedInterfaceMethod(root, extended, implementation);
      if (m != null) return m;
    }
    return null;
  }
 public JAXBElement<?> readFrom(
     Class<JAXBElement<?>> type,
     Type genericType,
     Annotation[] annotations,
     MediaType mediaType,
     MultivaluedMap<String, String> httpHeaders,
     InputStream entityStream)
     throws IOException {
   NoContent.contentLengthCheck(httpHeaders);
   Class<?> typeArg = Object.class;
   if (genericType != null) typeArg = Types.getTypeArgument(genericType);
   JAXBContext jaxb = null;
   try {
     jaxb = findJAXBContext(typeArg, annotations, mediaType, true);
   } catch (JAXBException e) {
     throw new JAXBUnmarshalException(e);
   }
   JAXBElement<?> result;
   try {
     Unmarshaller unmarshaller = jaxb.createUnmarshaller();
     unmarshaller = decorateUnmarshaller(type, annotations, mediaType, unmarshaller);
     if (suppressExpandEntityExpansion()) {
       unmarshaller = new ExternalEntityUnmarshaller(unmarshaller);
       SAXSource source = new SAXSource(new InputSource(entityStream));
       result = unmarshaller.unmarshal(source, (Class<?>) typeArg);
     } else {
       JAXBElement<?> e =
           unmarshaller.unmarshal(new StreamSource(entityStream), (Class<?>) typeArg);
       result = e;
     }
     ;
   } catch (JAXBException e) {
     throw new JAXBUnmarshalException(e);
   }
   JAXBElement<?> element = result;
   return element;
 }
Пример #10
0
  public ResourceMethod(
      Class<?> clazz,
      Method method,
      InjectorFactory injector,
      ResourceFactory resource,
      ResteasyProviderFactory providerFactory,
      Set<String> httpMethods) {
    this.injector = injector;
    this.resource = resource;
    this.parentProviderFactory = providerFactory;
    this.httpMethods = httpMethods;
    this.resourceClass = clazz;
    this.method = method;

    resourceInfo =
        new ResourceInfo() {
          @Override
          public Method getResourceMethod() {
            return ResourceMethod.this.method;
          }

          @Override
          public Class<?> getResourceClass() {
            return ResourceMethod.this.resourceClass;
          }
        };

    this.resourceMethodProviderFactory = new ResteasyProviderFactory(providerFactory);
    for (DynamicFeature feature : providerFactory.getServerDynamicFeatures()) {
      feature.configure(resourceInfo, new FeatureContextDelegate(resourceMethodProviderFactory));
    }

    this.methodInjector =
        injector.createMethodInjector(clazz, method, resourceMethodProviderFactory);

    Produces p = method.getAnnotation(Produces.class);
    if (p == null) p = clazz.getAnnotation(Produces.class);
    if (p == null) p = method.getDeclaringClass().getAnnotation(Produces.class);
    Consumes c = methodConsumes = method.getAnnotation(Consumes.class);
    if (c == null) c = clazz.getAnnotation(Consumes.class);
    if (c == null) c = method.getDeclaringClass().getAnnotation(Consumes.class);

    if (p != null) {
      produces = new MediaType[p.value().length];
      int i = 0;
      for (String mediaType : p.value()) {
        produces[i++] = MediaType.valueOf(mediaType);
        preferredProduces.add(WeightedMediaType.valueOf(mediaType));
      }
    }
    if (c != null) {
      consumes = new MediaType[c.value().length];
      int i = 0;
      for (String mediaType : c.value()) {
        consumes[i++] = MediaType.valueOf(mediaType);
        preferredConsumes.add(WeightedMediaType.valueOf(mediaType));
      }
    }
    Collections.sort(preferredProduces);
    Collections.sort(preferredConsumes);

    requestFilters =
        resourceMethodProviderFactory
            .getContainerRequestFilterRegistry()
            .postMatch(resourceClass, method);
    responseFilters =
        resourceMethodProviderFactory
            .getContainerResponseFilterRegistry()
            .postMatch(resourceClass, method);
    writerInterceptors =
        resourceMethodProviderFactory
            .getServerWriterInterceptorRegistry()
            .postMatch(resourceClass, method);

    // we register with parent to lisen for redeploy evens
    providerFactory.getContainerRequestFilterRegistry().getListeners().add(this);
    providerFactory.getContainerResponseFilterRegistry().getListeners().add(this);
    providerFactory.getServerWriterInterceptorRegistry().getListeners().add(this);
    /*
       We get the genericReturnType for the case of:

       interface Foo<T> {
          @GET
          List<T> get();
       }

       public class FooImpl implements Foo<Customer> {
           public List<Customer> get() {...}
       }
    */
    genericReturnType = Types.getGenericReturnTypeOfGenericInterfaceMethod(clazz, method);
    ContextResolver<GeneralValidator> resolver =
        providerFactory.getContextResolver(GeneralValidator.class, MediaType.WILDCARD_TYPE);
    if (resolver != null) {
      validator =
          providerFactory
              .getContextResolver(GeneralValidator.class, MediaType.WILDCARD_TYPE)
              .getContext(null);
    }
  }
Пример #11
0
  // this is synchronized in conjunction with finalize to protect against premature finalize called
  // by the GC
  protected synchronized <T2> Object readFrom(
      Class<T2> type, Type genericType, MediaType media, Annotation[] annotations) {
    Type useGeneric = genericType == null ? type : genericType;
    Class<?> useType = type;
    boolean isMarshalledEntity = false;
    if (type.equals(MarshalledEntity.class)) {
      isMarshalledEntity = true;
      ParameterizedType param = (ParameterizedType) useGeneric;
      useGeneric = param.getActualTypeArguments()[0];
      useType = Types.getRawType(useGeneric);
    }

    Providers current = ResteasyProviderFactory.getContextData(Providers.class);
    ResteasyProviderFactory.pushContext(Providers.class, providerFactory);
    Object obj = null;
    try {
      InputStream is = streamFactory.getInputStream();
      if (is == null) {
        throw new ClientResponseFailure(Messages.MESSAGES.inputStreamEmpty(), this);
      }
      if (isMarshalledEntity) {
        is = new InputStreamToByteArray(is);
      }

      final Object finalObj =
          new ClientReaderInterceptorContext(
                  readerInterceptors,
                  providerFactory,
                  useType,
                  useGeneric,
                  annotations,
                  media,
                  getResponseHeaders(),
                  new InputStreamWrapper(is),
                  attributes)
              .proceed();
      obj = finalObj;
      if (isMarshalledEntity) {
        InputStreamToByteArray isba = (InputStreamToByteArray) is;
        final byte[] bytes = isba.toByteArray();
        return new MarshalledEntity() {
          @Override
          public byte[] getMarshalledBytes() {
            return bytes;
          }

          @Override
          public Object getEntity() {
            return finalObj;
          }
        };
      } else {
        return (T2) finalObj;
      }

    } catch (Exception e) {
      if (e instanceof ReaderException) {
        throw (ReaderException) e;
      } else {
        throw new ReaderException(e);
      }
    } finally {
      ResteasyProviderFactory.popContextData(Providers.class);
      if (current != null) ResteasyProviderFactory.pushContext(Providers.class, current);
      if (obj instanceof ProvidersContextRetainer) {
        ((ProvidersContextRetainer) obj).setProviders(providerFactory);
      }
    }
  }
Пример #12
0
  public Object readFrom(
      Class<Object> type,
      Type genericType,
      Annotation[] annotations,
      MediaType mediaType,
      MultivaluedMap<String, String> httpHeaders,
      InputStream entityStream)
      throws IOException, WebApplicationException {
    JAXBContextFinder finder = getFinder(mediaType);
    if (finder == null) {
      throw new JAXBUnmarshalException("Unable to find JAXBContext for media type: " + mediaType);
    }
    Class baseType = Types.getCollectionBaseType(type, genericType);
    JaxbCollection col = null;
    try {
      JAXBElement<JaxbCollection> ele = null;

      if (suppressExpandEntityExpansion()) {
        SAXSource source = new SAXSource(new InputSource(entityStream));
        JAXBContext ctx = finder.findCachedContext(JaxbCollection.class, mediaType, annotations);
        Unmarshaller unmarshaller = ctx.createUnmarshaller();
        unmarshaller = new ExternalEntityUnmarshaller(unmarshaller);
        ele = unmarshaller.unmarshal(source, JaxbCollection.class);
      } else {
        StreamSource source = new StreamSource(entityStream);
        JAXBContext ctx = finder.findCachedContext(JaxbCollection.class, mediaType, annotations);
        ele = ctx.createUnmarshaller().unmarshal(source, JaxbCollection.class);
      }

      Wrapped wrapped = FindAnnotation.findAnnotation(annotations, Wrapped.class);
      if (wrapped != null) {
        if (!wrapped.element().equals(ele.getName().getLocalPart())) {
          throw new JAXBUnmarshalException(
              "Collection wrapping failed, expected root element name of "
                  + wrapped.element()
                  + " got "
                  + ele.getName().getLocalPart());
        }
        if (!wrapped.namespace().equals(ele.getName().getNamespaceURI())) {
          throw new JAXBUnmarshalException(
              "Collection wrapping failed, expect namespace of "
                  + wrapped.namespace()
                  + " got "
                  + ele.getName().getNamespaceURI());
        }
      }

      col = ele.getValue();
    } catch (JAXBException e) {
      throw new JAXBUnmarshalException(e);
    }

    try {
      JAXBContext ctx = finder.findCachedContext(baseType, mediaType, null);
      Unmarshaller unmarshaller = ctx.createUnmarshaller();
      unmarshaller =
          AbstractJAXBProvider.decorateUnmarshaller(baseType, annotations, mediaType, unmarshaller);
      if (type.isArray()) {
        Object array = Array.newInstance(baseType, col.getValue().size());
        for (int i = 0; i < col.getValue().size(); i++) {
          Element val = (Element) col.getValue().get(i);
          Array.set(array, i, unmarshaller.unmarshal(val));
        }
        return array;
      } else {
        Collection outCol = null;
        if (type.isInterface()) {
          if (List.class.isAssignableFrom(type)) outCol = new ArrayList();
          else if (SortedSet.class.isAssignableFrom(type)) outCol = new TreeSet();
          else if (Set.class.isAssignableFrom(type)) outCol = new HashSet();
          else outCol = new ArrayList();
        } else {
          try {
            outCol = (Collection) type.newInstance();
          } catch (Exception e) {
            throw new JAXBUnmarshalException(e);
          }
        }
        for (Object obj : col.getValue()) {
          Element val = (Element) obj;
          outCol.add(unmarshaller.unmarshal(val));
        }
        return outCol;
      }
    } catch (JAXBException e) {
      throw new JAXBUnmarshalException(e);
    }
  }