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

The following examples show how to use org.apache.cxf.jaxrs.model.ClassResourceInfo. These examples are extracted from open source projects. 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 Project: cxf   Source File: WadlGeneratorTest.java    License: 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 2
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 3
Source Project: cxf   Source File: DefaultApplicationFactory.java    License: 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 4
Source Project: cxf   Source File: UriInfoImplTest.java    License: 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 5
Source Project: cxf   Source File: JAXRSUtilsTest.java    License: 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 6
Source Project: cxf   Source File: JAXRSUtilsTest.java    License: 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 7
Source Project: cxf   Source File: SelectMethodCandidatesTest.java    License: 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 Project: cxf   Source File: JAXRSUtilsTest.java    License: 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 9
Source Project: cxf   Source File: JAXRSUtilsTest.java    License: 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 10
Source Project: cxf   Source File: JAXRSUtilsTest.java    License: 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 11
Source Project: cxf   Source File: JAXRSUtilsTest.java    License: 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 Project: cxf   Source File: JAXRSInvoker.java    License: 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 Project: cxf   Source File: JAXRSUtilsTest.java    License: 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 Project: cxf   Source File: ResourceUtils.java    License: 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 Project: cxf   Source File: JAXRSUtilsTest.java    License: 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 Project: product-private-paas   Source File: OAuthHandler.java    License: 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 Project: tomee   Source File: Contexts.java    License: 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 Project: cxf   Source File: WadlGeneratorTest.java    License: 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 Project: cxf   Source File: ResourceUtilsTest.java    License: 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 Project: cxf   Source File: JAXRSUtilsTest.java    License: 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 Project: cxf   Source File: JAXRSServerFactoryBean.java    License: 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 Project: aries-jax-rs-whiteboard   Source File: ClassIntrospector.java    License: Apache License 2.0 5 votes vote down vote up
private static String getPathSafe(ClassResourceInfo classResourceInfo) {
    Path path = classResourceInfo.getPath();
    if (path == null) {
        return "/";
    }

    return path.value();
}
 
Example 23
Source Project: carbon-device-mgt   Source File: ValidationInterceptor.java    License: 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 24
Source Project: carbon-device-mgt   Source File: ValidationInterceptor.java    License: 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 25
Source Project: carbon-identity   Source File: SCIMAuthenticatorRegistry.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Given the RESTful message and other info, returns the authenticator which can handle the request.
 *
 * @param message
 * @param classResourceInfo
 * @return
 */
public SCIMAuthenticationHandler getAuthenticator(Message message,
                                                  ClassResourceInfo classResourceInfo) {
    //since we use a tree map to store authenticators, they are ordered based on the priority.
    //therefore, we iterate over the authenticators and check the can handle method
    for (SCIMAuthenticationHandler scimAuthenticationHandler : SCIMAuthHandlers.values()) {
        if (scimAuthenticationHandler.canHandle(message, classResourceInfo)) {
            return scimAuthenticationHandler;
        }
    }
    return null;
}
 
Example 26
Source Project: syncope   Source File: BatchClientProxyImpl.java    License: Apache License 2.0 5 votes vote down vote up
public BatchClientProxyImpl(
        final BatchClientFactoryBean factory,
        final URI baseURI,
        final ClassLoader loader,
        final ClassResourceInfo cri,
        final boolean isRoot,
        final boolean inheritHeaders,
        final Object... varValues) {

    super(baseURI, loader, cri, isRoot, inheritHeaders, varValues);
    this.factory = factory;
}
 
Example 27
Source Project: syncope   Source File: BatchClientProxyImpl.java    License: Apache License 2.0 5 votes vote down vote up
public BatchClientProxyImpl(
        final BatchClientFactoryBean factory,
        final ClientState initialState,
        final ClassLoader loader,
        final ClassResourceInfo cri,
        final boolean isRoot,
        final boolean inheritHeaders,
        final Object... varValues) {

    super(initialState, loader, cri, isRoot, inheritHeaders, varValues);
    this.factory = factory;
}
 
Example 28
Source Project: cxf   Source File: SelectMethodCandidatesTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testFindFromAbstractGenericImpl4() throws Exception {
    JAXRSServiceFactoryBean sf = new JAXRSServiceFactoryBean();
    sf.setResourceClasses(GenericEntityImpl4.class);
    sf.create();
    List<ClassResourceInfo> resources = ((JAXRSServiceImpl)sf.getService()).getClassResourceInfos();
    String contentTypes = "text/xml";
    String acceptContentTypes = "text/xml";

    Message m = new MessageImpl();
    m.put(Message.CONTENT_TYPE, "text/xml");
    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,
                                                        "/books",
                                                        "POST",
                                                        values, contentTypes,
                                                        sortMediaTypes(acceptContentTypes));
    assertNotNull(ori);
    assertEquals("resourceMethod needs to be selected", "postEntity",
                 ori.getMethodToInvoke().getName());

    String value = "<Books><Book><name>The Book</name><id>2</id></Book></Books>";
    m.setContent(InputStream.class, new ByteArrayInputStream(value.getBytes()));
    List<Object> params = JAXRSUtils.processParameters(ori, values, m);
    assertEquals(1, params.size());
    List<?> books = (List<?>)params.get(0);
    assertEquals(1, books.size());
    Book book = (Book)books.get(0);
    assertNotNull(book);
    assertEquals(2L, book.getId());
    assertEquals("The Book", book.getName());
}
 
Example 29
Source Project: cxf   Source File: WadlGeneratorTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testGenericImplementation() throws Exception {
    setUpGenericImplementationTest();

    WadlGenerator wg = new WadlGenerator();
    wg.setApplicationTitle("My Application");
    wg.setNamespacePrefix("ns");
    ClassResourceInfo cri =
        ResourceUtils.createClassResourceInfo(ActualResource.class, ActualResource.class, true, true);
    Message m = mockMessage("http://example.com", "/", 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());
    
    List<Element> importEls = DOMUtils.getChildrenWithName(schemasEls.get(0),
                                                           Constants.URI_2001_SCHEMA_XSD,
                                                           "import");
    int schemaElementsIndex = !importEls.isEmpty() ? 0 : 1;
    int schemaTypesIndex = schemaElementsIndex == 0 ? 1 : 0;
    
    checkGenericImplSchemaWithTypes(schemasEls.get(schemaTypesIndex));
    checkGenericImplSchemaWithElements(schemasEls.get(schemaElementsIndex));

    List<Element> reps = DOMUtils.findAllElementsByTagNameNS(doc.getDocumentElement(),
                                   WadlGenerator.WADL_NS, "representation");
    assertEquals(2, reps.size());
    assertEquals("ns1:actual", reps.get(0).getAttribute("element"));
    assertEquals("ns1:actual", reps.get(1).getAttribute("element"));

}
 
Example 30
Source Project: carbon-apimgt   Source File: ValidationInInterceptor.java    License: Apache License 2.0 5 votes vote down vote up
public void handleMessage(Message message) {

        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);
            }
        }
    }