org.apache.cxf.jaxrs.model.ClassResourceInfo Java Examples

The following examples show how to use org.apache.cxf.jaxrs.model.ClassResourceInfo. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: JAXRSUtilsTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testWrongType() throws Exception {
    Class<?>[] argType = {HashMap.class}; //NOPMD
    Method m = Customer.class.getMethod("testWrongType", argType);
    Message messageImpl = createMessage();
    messageImpl.put(Message.QUERY_STRING, "p1=1");
    try {
        JAXRSUtils.processParameters(new OperationResourceInfo(m,
                                         new ClassResourceInfo(Customer.class)),
                                     null,
                                     messageImpl);
        fail("HashMap can not be handled as parameter");
    } catch (WebApplicationException ex) {
        assertEquals(500, ex.getResponse().getStatus());
        assertEquals("Parameter Class java.util.HashMap has no constructor with "
                     + "single String parameter, static valueOf(String) or fromString(String) methods",
                     ex.getResponse().getEntity().toString());
    }

}
 
Example #2
Source File: DefaultApplicationFactory.java    From cxf with Apache License 2.0 6 votes vote down vote up
/**
 * Detects the application (if present) or creates the default application (in case the scan is disabled).
 */
public static ApplicationInfo createApplicationInfoOrDefault(final Server server, 
            final ServerProviderFactory factory, final JAXRSServiceFactoryBean sfb, final Bus bus, 
                final boolean scan) {
    
    ApplicationInfo appInfo = null;
    if (!scan) {
        appInfo = factory.getApplicationProvider();
        if (appInfo == null) {
            Set<Class<?>> serviceClasses = new HashSet<>();
            for (ClassResourceInfo cri : sfb.getClassResourceInfo()) {
                serviceClasses.add(cri.getServiceClass());
            }
            appInfo = createApplicationInfo(serviceClasses, bus);
            server.getEndpoint().put(Application.class.getName(), appInfo);
        }
    }
    
    return appInfo;
}
 
Example #3
Source File: UriInfoImplTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetMatchedURIsSubResourceLocator() throws Exception {
    System.out.println("testGetMatchedURIsSubResourceLocator");
    Message m = mockMessage("http://localhost:8080/app", "/foo/sub");
    OperationResourceInfoStack oriStack = new OperationResourceInfoStack();
    ClassResourceInfo rootCri = getCri(RootResource.class, true);
    OperationResourceInfo rootOri = getOri(rootCri, "getSubResourceLocator");

    MethodInvocationInfo miInfo = new MethodInvocationInfo(rootOri, RootResource.class, new ArrayList<String>());
    oriStack.push(miInfo);

    ClassResourceInfo subCri = getCri(SubResource.class, false);
    OperationResourceInfo subOri = getOri(subCri, "getFromSub");

    miInfo = new MethodInvocationInfo(subOri, SubResource.class, new ArrayList<String>());
    oriStack.push(miInfo);
    m.put(OperationResourceInfoStack.class, oriStack);

    UriInfoImpl u = new UriInfoImpl(m);
    List<String> matchedUris = getMatchedURIs(u);
    assertEquals(2, matchedUris.size());
    assertEquals("foo/sub", matchedUris.get(0));
    assertEquals("foo", matchedUris.get(1));
}
 
Example #4
Source File: JAXRSUtilsTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testQueryParametersIntegerArrayValueIsColection() throws Exception {
    Class<?>[] argType = {Integer[].class};
    Method m = Customer.class.getMethod("testQueryIntegerArray", argType);
    Message messageImpl = createMessage();
    messageImpl.put("parse.query.value.as.collection", true);
    messageImpl.put(Message.QUERY_STRING, "query=1&query=2,3");
    List<Object> params = JAXRSUtils.processParameters(new OperationResourceInfo(m,
                                                           new ClassResourceInfo(Customer.class)),
                                                       null,
                                                       messageImpl);
    assertEquals(1, params.size());
    Integer[] intValues = (Integer[])params.get(0);
    assertEquals(3, intValues.length);
    assertEquals(1, (int)intValues[0]);
    assertEquals(2, (int)intValues[1]);
    assertEquals(3, (int)intValues[2]);
}
 
Example #5
Source File: JAXRSUtilsTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testConversion() throws Exception {
    ClassResourceInfo cri = new ClassResourceInfo(Customer.class, true);
    OperationResourceInfo ori =
        new OperationResourceInfo(
            Customer.class.getMethod("testConversion",
                                     new Class[]{PathSegmentImpl.class,
                                                 SimpleFactory.class}),
            cri);
    ori.setHttpMethod("GET");
    ori.setURITemplate(new URITemplate("{id1}/{id2}"));
    MultivaluedMap<String, String> values = new MetadataMap<>();
    values.putSingle("id1", "1");
    values.putSingle("id2", "2");

    Message m = createMessage();


    List<Object> params =
        JAXRSUtils.processParameters(ori, values, m);
    PathSegment ps = (PathSegment)params.get(0);
    assertEquals("1", ps.getPath());

    SimpleFactory sf = (SimpleFactory)params.get(1);
    assertEquals(2, sf.getId());
}
 
Example #6
Source File: CxfJaxrsServiceRegistrator.java    From aries-jax-rs-whiteboard with Apache License 2.0 6 votes vote down vote up
private ResourceContextProvider createResourceContextProvider(
    JAXRSServiceFactoryBean jaxrsServiceFactoryBean) {

    ComparableResourceComparator comparableResourceComparator =
        new ComparableResourceComparator();

    List<ClassResourceInfo> classResourceInfos =
        jaxrsServiceFactoryBean.getClassResourceInfo().stream().sorted(
            (cri1, cri2) -> comparableResourceComparator.compare(
                cri1, cri2, null)
        ).collect(
            Collectors.toList()
        );

    HashMap<Class, ResourceProvider> map = new HashMap<>();

    for (ClassResourceInfo classResourceInfo : classResourceInfos) {
        map.put(
            classResourceInfo.getResourceClass(),
            classResourceInfo.getResourceProvider());
    }

    return map::get;
}
 
Example #7
Source File: SelectMethodCandidatesTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testFindOverridesDifferentArguments() throws Exception {
    JAXRSServiceFactoryBean sf = new JAXRSServiceFactoryBean();
    sf.setResourceClasses(CustomizedApi.class);

    sf.create();
    List<ClassResourceInfo> resources = ((JAXRSServiceImpl)sf.getService()).getClassResourceInfos();
    Message m = createMessage();
    m.put(Message.CONTENT_TYPE, "application/json");

    MetadataMap<String, String> values = new MetadataMap<>();
    OperationResourceInfo ori = findTargetResourceClass(resources, m,
                                                        "/api",
                                                        "GET",
                                                        values, "application/json",
                                                        sortMediaTypes("*/*"));
    assertNotNull(ori);
    assertEquals("resourceMethod needs to be selected", "getApi",
                 ori.getMethodToInvoke().getName());
    
    final Method expected = CustomizedApi.class.getMethod("getApi", 
        new Class[]{ServletConfig.class, HttpHeaders.class, UriInfo.class, String.class});
    assertEquals(expected, ori.getMethodToInvoke());
}
 
Example #8
Source File: WadlGeneratorTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testCustomSchemaAndSchemaPrefixes() throws Exception {
    WadlGenerator wg = new WadlGenerator();
    wg.setSchemaLocations(Collections.singletonList("classpath:/book2.xsd"));
    wg.setUseJaxbContextForQnames(false);

    ClassResourceInfo cri =
        ResourceUtils.createClassResourceInfo(BookStore.class, BookStore.class, true, true);
    Message m = mockMessage("http://localhost:8080/baz", "/bookstore/1", WadlGenerator.WADL_QUERY, cri);
    Response r = handleRequest(wg, m);
    checkResponse(r);
    Document doc = StaxUtils.read(new StringReader(r.getEntity().toString()));
    checkGrammars(doc.getDocumentElement(), "book", "book2", "chapter");
    List<Element> els = getWadlResourcesInfo(doc, "http://localhost:8080/baz", 1);
    checkBookStoreInfo(els.get(0), "prefix1:book", "prefix1:book2", "prefix1:chapter");
}
 
Example #9
Source File: JAXRSUtilsTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testFormParametersBeanWithMap() throws Exception {
    Class<?>[] argType = {Customer.CustomerBean.class};
    Method m = Customer.class.getMethod("testFormBean", argType);
    Message messageImpl = createMessage();
    messageImpl.put(Message.REQUEST_URI, "/bar");
    MultivaluedMap<String, String> headers = new MetadataMap<>();
    headers.putSingle("Content-Type", MediaType.APPLICATION_FORM_URLENCODED);
    messageImpl.put(Message.PROTOCOL_HEADERS, headers);
    String body = "g.b=1&g.b=2";
    messageImpl.setContent(InputStream.class, new ByteArrayInputStream(body.getBytes()));
    List<Object> params = JAXRSUtils.processParameters(new OperationResourceInfo(m,
                                                           new ClassResourceInfo(Customer.class)),
                                                       null,
                                                       messageImpl);
    assertEquals("Bean should be created", 1, params.size());
    Customer.CustomerBean cb = (Customer.CustomerBean)params.get(0);
    assertNotNull(cb);
    assertNotNull(cb.getG());
    List<String> values = cb.getG().get("b");
    assertEquals(2, values.size());
    assertEquals("1", values.get(0));
    assertEquals("2", values.get(1));

}
 
Example #10
Source File: JAXRSUtilsTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
private static OperationResourceInfo findTargetResourceClass(List<ClassResourceInfo> resources,
                                                            Message message,
                                                            String path,
                                                            String httpMethod,
                                                            MultivaluedMap<String, String> values,
                                                            String requestContentType,
                                                            List<MediaType> acceptContentTypes) {

    Map<ClassResourceInfo, MultivaluedMap<String, String>> mResources
        = JAXRSUtils.selectResourceClass(resources, path, new MessageImpl());

    if (mResources != null) {
        OperationResourceInfo ori = JAXRSUtils.findTargetMethod(mResources, message, httpMethod,
                                               values, requestContentType, acceptContentTypes);
        if (ori != null) {
            return ori;
        }
    }

    return null;
}
 
Example #11
Source File: JAXRSUtilsTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testFormParametersBeanWithBoolean() throws Exception {
    Class<?>[] argType = {Customer.CustomerBean.class};
    Method m = Customer.class.getMethod("testFormBean", argType);
    Message messageImpl = createMessage();
    messageImpl.put(Message.REQUEST_URI, "/bar");
    MultivaluedMap<String, String> headers = new MetadataMap<>();
    headers.putSingle("Content-Type", MediaType.APPLICATION_FORM_URLENCODED);
    messageImpl.put(Message.PROTOCOL_HEADERS, headers);
    String body = "a=aValue&b=123&cb=true";
    messageImpl.setContent(InputStream.class, new ByteArrayInputStream(body.getBytes()));

    List<Object> params = JAXRSUtils.processParameters(new OperationResourceInfo(m,
                                                           new ClassResourceInfo(Customer.class)),
                                                       null,
                                                       messageImpl);
    assertEquals("Bean should be created", 1, params.size());
    Customer.CustomerBean cb = (Customer.CustomerBean)params.get(0);
    assertNotNull(cb);

    assertEquals("aValue", cb.getA());
    assertEquals(Long.valueOf(123), cb.getB());
    assertTrue(cb.isCb());
}
 
Example #12
Source File: JAXRSInvoker.java    From cxf with Apache License 2.0 6 votes vote down vote up
private Object handleFault(Fault ex, Message inMessage,
                           ClassResourceInfo cri, Method methodToInvoke) {
    String errorMessage = ex.getMessage();
    if (errorMessage != null && cri != null
        && errorMessage.contains(PROXY_INVOCATION_ERROR_FRAGMENT)) {
        org.apache.cxf.common.i18n.Message errorM =
            new org.apache.cxf.common.i18n.Message("PROXY_INVOCATION_FAILURE",
                                                   BUNDLE,
                                                   methodToInvoke,
                                                   cri.getServiceClass().getName());
        LOG.severe(errorM.toString());
    }
    Response excResponse =
        JAXRSUtils.convertFaultToResponse(ex.getCause() == null ? ex : ex.getCause(), inMessage);
    if (excResponse == null) {
        inMessage.getExchange().put(Message.PROPOGATE_EXCEPTION,
                                    ExceptionUtils.propogateException(inMessage));
        throw ex;
    }
    return new MessageContentsList(excResponse);
}
 
Example #13
Source File: JAXRSUtilsTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testQueryParameter() throws Exception {
    Message messageImpl = createMessage();
    ProviderFactory.getInstance(messageImpl).registerUserProvider(
        new GenericObjectParameterHandler());
    Class<?>[] argType = {Query.class};
    Method m = Customer.class.getMethod("testGenericObjectParam", argType);

    messageImpl.put(Message.QUERY_STRING, "p1=thequery");
    List<Object> params = JAXRSUtils.processParameters(new OperationResourceInfo(m,
                                                           new ClassResourceInfo(Customer.class)),
                                                       null,
                                                       messageImpl);
    assertEquals(1, params.size());
    @SuppressWarnings("unchecked")
    Query<String> query = (Query<String>)params.get(0);
    assertEquals("thequery", query.getEntity());
}
 
Example #14
Source File: ResourceUtils.java    From cxf with Apache License 2.0 6 votes vote down vote up
public static ClassResourceInfo createClassResourceInfo(final Class<?> rClass,
                                                        final Class<?> sClass,
                                                        ClassResourceInfo parent,
                                                        boolean root,
                                                        boolean enableStatic,
                                                        Bus bus,
                                                        List<MediaType> defaultConsumes,
                                                        List<MediaType> defaultProduces) {
//CHECKSTYLE:ON
    ClassResourceInfo cri = new ClassResourceInfo(rClass, sClass, root, enableStatic, bus,
                                                  defaultConsumes, defaultProduces);
    cri.setParent(parent);

    if (root) {
        URITemplate t = URITemplate.createTemplate(cri.getPath());
        cri.setURITemplate(t);
    }

    evaluateResourceClass(cri, enableStatic);
    return checkMethodDispatcher(cri) ? cri : null;
}
 
Example #15
Source File: JAXRSUtilsTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testPerRequestContextFields() throws Exception {

    ClassResourceInfo cri = new ClassResourceInfo(Customer.class, true);
    cri.setResourceProvider(new PerRequestResourceProvider(Customer.class));
    OperationResourceInfo ori = new OperationResourceInfo(Customer.class.getMethod("postConstruct",
                                                                                   new Class[]{}), cri);

    Customer c = new Customer();

    Message m = createMessage();
    m.put(Message.PROTOCOL_HEADERS, new HashMap<String, List<String>>());
    HttpServletResponse response = EasyMock.createMock(HttpServletResponse.class);
    m.put(AbstractHTTPDestination.HTTP_RESPONSE, response);

    InjectionUtils.injectContextFields(c, ori.getClassResourceInfo(), m);
    assertSame(UriInfoImpl.class, c.getUriInfo2().getClass());
    assertSame(HttpHeadersImpl.class, c.getHeaders().getClass());
    assertSame(RequestImpl.class, c.getRequest().getClass());
    assertSame(SecurityContextImpl.class, c.getSecurityContext().getClass());
    assertSame(ProvidersImpl.class, c.getBodyWorkers().getClass());

}
 
Example #16
Source File: OAuthHandler.java    From product-private-paas with Apache License 2.0 6 votes vote down vote up
public Response handle(Message message, ClassResourceInfo classResourceInfo) {
    try {
        OAuth2TokenValidationResponseDTO respDTO;
        ValidationServiceClient validationServiceClient = new ValidationServiceClient(oauthValidationEndpoint,
                username, password);
        HttpHeaders httpHeaders = new HttpHeadersImpl(message);
        String header = httpHeaders.getRequestHeaders().getFirst("Authorization");
        // if the authorization token has Bearer..
        if (header.startsWith("Bearer ")) {
            String accessToken = header.substring(7).trim();
            respDTO = validationServiceClient.validateAuthenticationRequest(accessToken); //TODO : send scope params
            boolean valid = respDTO.getValid();
            if (!valid) {
                // authorization failure..
                return Response.status(Response.Status.FORBIDDEN).build();
            }
        }
    } catch (Exception e) {
        log.error("Error while validating access token", e);
        return Response.status(Response.Status.FORBIDDEN).build();
    }
    AuthenticationContext.setAuthenticated(true);
    return null;
}
 
Example #17
Source File: Contexts.java    From tomee with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("UnusedDeclaration")
public static void bind(final Exchange exchange) {
    if (exchange == null) {
        return;
    }

    final ClassResourceInfo cri = exchange.get(OperationResourceInfo.class).getClassResourceInfo();

    // binding context fields
    final Set<Class<?>> types = new HashSet<>();
    for (final Field field : cri.getContextFields()) {
        types.add(field.getType());
    }

    bind(exchange, types);
}
 
Example #18
Source File: WadlGeneratorTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testExternalSchemaCustomPrefix() throws Exception {
    WadlGenerator wg = new WadlGenerator();
    wg.setExternalLinks(Collections.singletonList("http://books"));
    wg.setUseJaxbContextForQnames(false);

    ClassResourceInfo cri =
        ResourceUtils.createClassResourceInfo(BookStore.class, BookStore.class, true, true);
    Message m = mockMessage("http://localhost:8080/baz", "/bookstore/1", WadlGenerator.WADL_QUERY, cri);
    Response r = handleRequest(wg, m);
    checkResponse(r);
    Document doc = StaxUtils.read(new StringReader(r.getEntity().toString()));
    checkGrammarsWithLinks(doc.getDocumentElement(),
                           Collections.singletonList("http://books"));
    List<Element> els = getWadlResourcesInfo(doc, "http://localhost:8080/baz", 1);
    checkBookStoreInfo(els.get(0), "p1:thesuperbook", "p1:thesuperbook2", "p1:thesuperchapter");
}
 
Example #19
Source File: ResourceUtilsTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testClassResourceInfoWithSyntheticMethod() throws Exception {
    ClassResourceInfo cri =
            ResourceUtils.createClassResourceInfo(
                    SyntheticHelloInterfaceImpl.class,
                    SyntheticHelloInterfaceImpl.class,
                    true,
                    true);

    Method synthetic = SyntheticHelloInterfaceImpl.class.getMethod("getById", new Class[]{Object.class});
    assertTrue(synthetic.isSynthetic());

    assertNotNull(cri);
    Method notSynthetic = SyntheticHelloInterfaceImpl.class.getMethod("getById", new Class[]{String.class});
    assertFalse(notSynthetic.isSynthetic());

    cri.hasSubResources();
    assertEquals("there must be only one method, which is the getById(String)",
            1,
            cri.getMethodDispatcher().getOperationResourceInfos().size());
}
 
Example #20
Source File: JAXRSUtilsTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testAcceptTypesMatch() throws Exception {

    Method m = Customer.class.getMethod("test", new Class[]{});
    ClassResourceInfo cr = new ClassResourceInfo(Customer.class);

    assertTrue("text/xml can not be matched",
               JAXRSUtils.matchMimeTypes(JAXRSUtils.ALL_TYPES,
                                         new MediaType("text", "xml"),
                                         new OperationResourceInfo(m, cr)));
    assertTrue("text/xml can not be matched",
               JAXRSUtils.matchMimeTypes(JAXRSUtils.ALL_TYPES,
                                         new MediaType("text", "*"),
                                         new OperationResourceInfo(m, cr)));
    assertTrue("text/xml can not be matched",
               JAXRSUtils.matchMimeTypes(JAXRSUtils.ALL_TYPES,
                                         new MediaType("*", "*"),
                                         new OperationResourceInfo(m, cr)));
    assertFalse("text/plain was matched",
               JAXRSUtils.matchMimeTypes(JAXRSUtils.ALL_TYPES,
                                         new MediaType("text", "plain"),
                                         new OperationResourceInfo(m, cr)));
}
 
Example #21
Source File: JAXRSServerFactoryBean.java    From cxf with Apache License 2.0 6 votes vote down vote up
protected void injectContexts(ServerProviderFactory factory, ApplicationInfo fallback) {
    // Sometimes the application provider (ApplicationInfo) is injected through
    // the endpoint, not JAXRSServerFactoryBean (like for example OpenApiFeature
    // or Swagger2Feature do). As such, without consulting the endpoint, the injection
    // may not work properly.
    final ApplicationInfo appInfoProvider = (appProvider == null) ? fallback : appProvider;
    final Application application = appInfoProvider == null ? null : appInfoProvider.getProvider();

    for (ClassResourceInfo cri : serviceFactory.getClassResourceInfo()) {
        if (cri.isSingleton()) {
            InjectionUtils.injectContextProxiesAndApplication(cri,
                                                cri.getResourceProvider().getInstance(null),
                                                application,
                                                factory);
        }
    }
    if (application != null) {
        InjectionUtils.injectContextProxiesAndApplication(appInfoProvider,
                                                          application, null, null);
    }
}
 
Example #22
Source File: Java2WADLMojo.java    From cxf with Apache License 2.0 5 votes vote down vote up
private ClassResourceInfo getCreatedFromModel(Class<?> realClass) {

        for (ClassResourceInfo cri : classResourceInfos) {
            if (cri.isCreatedFromModel()
                && cri.isRoot() && cri.getServiceClass().isAssignableFrom(realClass)) {
                return cri;
            }
        }
        return null;
    }
 
Example #23
Source File: JAXRSServiceFactoryBean.java    From cxf with Apache License 2.0 5 votes vote down vote up
public void setUserResourcesWithServiceClass(List<UserResource> resources, Class<?> ...sClasses) {
    Map<String, UserResource> map = userResourcesAsMap(resources);
    for (Class<?> sClass : sClasses) {
        ClassResourceInfo cri = ResourceUtils.createServiceClassResourceInfo(
            map, map.get(sClass.getName()), sClass, true, enableStatic, getBus());
        if (cri != null) {
            classResourceInfos.add(cri);
        }
    }
}
 
Example #24
Source File: JAXRSUtilsTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testDefaultValueOnField() throws Exception {

    ClassResourceInfo cri = new ClassResourceInfo(Customer.class, true);
    Customer c = new Customer();
    OperationResourceInfo ori = new OperationResourceInfo(Customer.class.getMethods()[0],
                                                          cri);
    Message m = createMessage();

    m.put(Message.QUERY_STRING, "");
    JAXRSUtils.injectParameters(ori, c, m);
    assertEquals("bQuery", c.getB());
}
 
Example #25
Source File: JAXRSServiceImpl.java    From cxf with Apache License 2.0 5 votes vote down vote up
public List<ServiceInfo> getServiceInfos() {
    if (!createServiceModel) {
        return Collections.emptyList();
    }
    // try to convert to WSDL-centric model so that CXF DataBindings can get initialized
    // might become useful too if we support wsdl2

    // make databindings to use databinding-specific information
    // like @XmlRootElement for ex to select a namespace
    this.put("org.apache.cxf.databinding.namespace", "true");

    List<ServiceInfo> infos = new ArrayList<>();
    for (ClassResourceInfo cri : classResourceInfos) {
        ServiceInfo si = new ServiceInfo();
        infos.add(si);
        QName qname = JAXRSUtils.getClassQName(cri.getServiceClass());
        si.setName(qname);
        InterfaceInfo inf = new InterfaceInfo(si, qname);
        si.setInterface(inf);
        for (OperationResourceInfo ori : cri.getMethodDispatcher().getOperationResourceInfos()) {
            Method m = ori.getMethodToInvoke();
            QName oname = new QName(qname.getNamespaceURI(), m.getName());
            OperationInfo oi = inf.addOperation(oname);
            createMessagePartInfo(oi, m.getReturnType(), qname, m, false);
            for (Parameter pm : ori.getParameters()) {

                if (pm.getType() == ParameterType.REQUEST_BODY) {
                    createMessagePartInfo(oi,
                                          ori.getMethodToInvoke().getParameterTypes()[pm.getIndex()],
                                          qname, m, true);
                }
            }
        }

    }
    return infos;
}
 
Example #26
Source File: WadlGeneratorTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testTwoSchemasSameNs() throws Exception {
    WadlGenerator wg = new WadlGenerator();
    wg.setApplicationTitle("My Application");
    wg.setNamespacePrefix("ns");
    ClassResourceInfo cri =
        ResourceUtils.createClassResourceInfo(TestResource.class, TestResource.class, true, true);
    Message m = mockMessage("http://localhost:8080/baz", "/", WadlGenerator.WADL_QUERY, cri);
    Response r = handleRequest(wg, m);
    checkResponse(r);
    Document doc = StaxUtils.read(new StringReader(r.getEntity().toString()));
    checkDocs(doc.getDocumentElement(), "My Application", "", "");
    List<Element> grammarEls = DOMUtils.getChildrenWithName(doc.getDocumentElement(),
                                                            WadlGenerator.WADL_NS,
                                                            "grammars");
    assertEquals(1, grammarEls.size());
    List<Element> schemasEls = DOMUtils.getChildrenWithName(grammarEls.get(0),
                                                            Constants.URI_2001_SCHEMA_XSD,
                                                            "schema");
    assertEquals(2, schemasEls.size());
    assertEquals("http://example.com/test", schemasEls.get(0).getAttribute("targetNamespace"));
    assertEquals("http://example.com/test", schemasEls.get(1).getAttribute("targetNamespace"));
    List<Element> reps = DOMUtils.findAllElementsByTagNameNS(doc.getDocumentElement(),
                                   WadlGenerator.WADL_NS, "representation");
    assertEquals(2, reps.size());
    assertEquals("ns1:testCompositeObject", reps.get(0).getAttribute("element"));
    assertEquals("ns1:testCompositeObject", reps.get(1).getAttribute("element"));
}
 
Example #27
Source File: JAXRSUtilsTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void testHttpContextParameters() throws Exception {

    ClassResourceInfo cri = new ClassResourceInfo(Customer.class, true);
    OperationResourceInfo ori =
        new OperationResourceInfo(
            Customer.class.getMethod("testParams",
                                     new Class[]{UriInfo.class,
                                                 HttpHeaders.class,
                                                 Request.class,
                                                 SecurityContext.class,
                                                 Providers.class,
                                                 String.class,
                                                 List.class}),
            cri);
    ori.setHttpMethod("GET");
    MultivaluedMap<String, String> headers = new MetadataMap<>();
    headers.add("Foo", "bar, baz");

    Message m = createMessage();
    m.put("org.apache.cxf.http.header.split", "true");
    m.put(Message.PROTOCOL_HEADERS, headers);

    List<Object> params =
        JAXRSUtils.processParameters(ori, new MetadataMap<String, String>(), m);
    assertEquals("7 parameters expected", 7, params.size());
    assertSame(UriInfoImpl.class, params.get(0).getClass());
    assertSame(HttpHeadersImpl.class, params.get(1).getClass());
    assertSame(RequestImpl.class, params.get(2).getClass());
    assertSame(SecurityContextImpl.class, params.get(3).getClass());
    assertSame(ProvidersImpl.class, params.get(4).getClass());
    assertSame(String.class, params.get(5).getClass());
    assertEquals("Wrong header param", "bar", params.get(5));
    List<String> values = (List<String>)params.get(6);
    assertEquals("Wrong headers size", 2, values.size());
    assertEquals("Wrong 1st header param", "bar", values.get(0));
    assertEquals("Wrong 2nd header param", "baz", values.get(1));
}
 
Example #28
Source File: ValidationInterceptor.java    From carbon-device-mgt with Apache License 2.0 5 votes vote down vote up
@Override
public void handleMessage(Message message) throws Fault {
    final OperationResourceInfo operationResource = message.getExchange().get(OperationResourceInfo.class);
    if (operationResource == null) {
        log.info("OperationResourceInfo is not available, skipping validation");
        return;
    }

    final ClassResourceInfo classResource = operationResource.getClassResourceInfo();
    if (classResource == null) {
        log.info("ClassResourceInfo is not available, skipping validation");
        return;
    }

    final ResourceProvider resourceProvider = classResource.getResourceProvider();
    if (resourceProvider == null) {
        log.info("ResourceProvider is not available, skipping validation");
        return;
    }

    final List<Object> arguments = MessageContentsList.getContentsList(message);
    final Method method = operationResource.getAnnotatedMethod();
    final Object instance = resourceProvider.getInstance(message);
    if (method != null && arguments != null) {
        //validate the parameters(arguments) over the invoked method
        validate(method, arguments.toArray(), instance);

        //validate the fields of each argument
        for (Object arg : arguments) {
            if (arg != null)
                validate(arg);
        }
    }

}
 
Example #29
Source File: SelectMethodCandidatesTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
private void doTestConsumesResource(Class<?> resourceClass, String ct,
                                    String expectedMethodName) throws Exception {
    JAXRSServiceFactoryBean sf = new JAXRSServiceFactoryBean();
    sf.setResourceClasses(resourceClass);
    sf.create();
    List<ClassResourceInfo> resources = ((JAXRSServiceImpl)sf.getService()).getClassResourceInfos();
    String contentType = ct == null ? "application/xml" : ct;
    String acceptContentTypes = "*/*";

    Message m = new MessageImpl();
    m.put(Message.CONTENT_TYPE, contentType);
    Exchange ex = new ExchangeImpl();
    ex.setInMessage(m);
    m.setExchange(ex);
    Endpoint e = mockEndpoint();
    ex.put(Endpoint.class, e);

    MetadataMap<String, String> values = new MetadataMap<>();
    OperationResourceInfo ori = findTargetResourceClass(resources,
                                                        m,
                                                        "/",
                                                        "POST",
                                                        values,
                                                        contentType,
                                                        sortMediaTypes(acceptContentTypes));
    assertNotNull(ori);
    assertEquals(expectedMethodName,  ori.getMethodToInvoke().getName());
}
 
Example #30
Source File: ResourceUtils.java    From cxf with Apache License 2.0 5 votes vote down vote up
private static ClassResourceInfo getAncestorWithSameServiceClass(ClassResourceInfo parent, Class<?> subClass) {
    if (parent == null) {
        return null;
    }
    if (parent.getServiceClass() == subClass) {
        return parent;
    }
    return getAncestorWithSameServiceClass(parent.getParent(), subClass);
}