org.apache.cxf.jaxrs.utils.ResourceUtils Java Examples

The following examples show how to use org.apache.cxf.jaxrs.utils.ResourceUtils. 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: OpenApiCustomizer.java    From cxf with Apache License 2.0 6 votes vote down vote up
public void setApplicationInfo(ApplicationInfo application) {
    if (application != null && application.getProvider() != null) {
        final Class<?> clazz = application.getProvider().getClass();
        final ApplicationPath path = ResourceUtils.locateApplicationPath(clazz);

        if (path != null) {
            applicationPath = path.value();

            if (!applicationPath.startsWith("/")) {
                applicationPath = "/" + applicationPath;
            }

            if (applicationPath.endsWith("/")) {
                applicationPath = applicationPath.substring(0, applicationPath.lastIndexOf('/'));
            }
        }
    }
}
 
Example #2
Source File: WadlGenerator.java    From cxf with Apache License 2.0 6 votes vote down vote up
private String transformLocally(Message m, UriInfo ui, Source source) throws Exception {
    InputStream is = ResourceUtils.getResourceStream(stylesheetReference, m.getExchange().getBus());
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    transformerFactory.setFeature(javax.xml.XMLConstants.FEATURE_SECURE_PROCESSING, true);
    try {
        transformerFactory.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, "");
        transformerFactory.setAttribute(XMLConstants.ACCESS_EXTERNAL_STYLESHEET, "");
    } catch (IllegalArgumentException ex) {
        // ignore
    }

    Transformer t = transformerFactory.newTemplates(new StreamSource(is)).newTransformer();
    t.setParameter("base.path", m.get("http.base.path"));
    StringWriter stringWriter = new StringWriter();
    t.transform(source, new StreamResult(stringWriter));
    return stringWriter.toString();
}
 
Example #3
Source File: WadlGeneratorTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testExternalRelativeSchemaJaxbContextPrefixes() throws Exception {
    WadlGenerator wg = new WadlGenerator();
    wg.setExternalLinks(Collections.singletonList("books.xsd"));

    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://localhost:8080/baz/books.xsd"));
    List<Element> els = getWadlResourcesInfo(doc, "http://localhost:8080/baz", 1);
    checkBookStoreInfo(els.get(0), "prefix1:thebook", "prefix1:thebook2", "prefix1:thechapter");
}
 
Example #4
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 #5
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 #6
Source File: WadlGeneratorTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testSingleRootResource() throws Exception {
    WadlGenerator wg = new WadlGenerator();
    wg.setApplicationTitle("My Application");
    wg.setNamespacePrefix("ns");
    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()));
    checkDocs(doc.getDocumentElement(), "My Application", "", "");
    checkGrammars(doc.getDocumentElement(), "thebook", "books", "thebook2s", "thebook2", "thechapter");
    List<Element> els = getWadlResourcesInfo(doc, "http://localhost:8080/baz", 1);
    checkBookStoreInfo(els.get(0),
                       "ns1:thebook",
                       "ns1:thebook2",
                       "ns1:thechapter",
                       "ns1:books");
}
 
Example #7
Source File: CXFNonSpringJaxrsServlet.java    From cxf with Apache License 2.0 6 votes vote down vote up
protected void createServerFromApplication(ServletConfig servletConfig)
    throws ServletException {

    Application app = getApplication();
    JAXRSServerFactoryBean bean = ResourceUtils.createApplication(
                                      app,
                                      isIgnoreApplicationPath(servletConfig),
                                      getStaticSubResolutionValue(servletConfig),
                                      isAppResourceLifecycleASingleton(app, servletConfig),
                                      getBus());
    String splitChar = getParameterSplitChar(servletConfig);
    setAllInterceptors(bean, servletConfig, splitChar);
    setInvoker(bean, servletConfig);
    setExtensions(bean, servletConfig);
    setDocLocation(bean, servletConfig);
    setSchemasLocations(bean, servletConfig);

    List<?> providers = getProviders(servletConfig, splitChar);
    bean.setProviders(providers);
    List<? extends Feature> features = getFeatures(servletConfig, splitChar);
    bean.getFeatures().addAll(features);

    bean.setBus(getBus());
    bean.setApplication(getApplication());
    bean.create();
}
 
Example #8
Source File: WadlGeneratorTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testSingleRootResourceNoPrefixIncrement() throws Exception {
    WadlGenerator wg = new WadlGenerator();
    wg.setApplicationTitle("My Application");
    wg.setNamespacePrefix("ns");
    wg.setIncrementNamespacePrefix(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()));
    checkDocs(doc.getDocumentElement(), "My Application", "", "");
    checkGrammars(doc.getDocumentElement(), "thebook", "books", "thebook2s", "thebook2", "thechapter");
    List<Element> els = getWadlResourcesInfo(doc, "http://localhost:8080/baz", 1);
    checkBookStoreInfo(els.get(0),
                       "ns:thebook",
                       "ns:thebook2",
                       "ns:thechapter",
                       "ns:books");
}
 
Example #9
Source File: BlueprintResourceFactory.java    From cxf with Apache License 2.0 6 votes vote down vote up
private void init() {
    Class<?> type = ClassHelper.getRealClassFromClass(blueprintContainer.getComponentInstance(beanId)
                                                      .getClass());
    if (Proxy.isProxyClass(type)) {
        type = ClassHelper.getRealClass(blueprintContainer.getComponentInstance(beanId));
    }
    c = ResourceUtils.findResourceConstructor(type, !isSingleton());
    if (c == null) {
        throw new RuntimeException("Resource class " + type + " has no valid constructor");
    }
    postConstructMethod = ResourceUtils.findPostConstructMethod(type);
    preDestroyMethod = ResourceUtils.findPreDestroyMethod(type);

    Object component = blueprintContainer.getComponentMetadata(beanId);
    if (component instanceof BeanMetadata) {
        BeanMetadata local = (BeanMetadata) component;
        isSingleton = BeanMetadata.SCOPE_SINGLETON.equals(local.getScope())
            || (local.getScope() == null && local.getId() != null);
    }
}
 
Example #10
Source File: WadlGeneratorTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testRootResourceWithSingleSlash() throws Exception {
    WadlGenerator wg = new WadlGenerator();
    ClassResourceInfo cri =
        ResourceUtils.createClassResourceInfo(BookStoreWithSingleSlash.class,
                                              BookStoreWithSingleSlash.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()));
    List<Element> rootEls = getWadlResourcesInfo(doc, "http://localhost:8080/baz", 1);
    assertEquals(1, rootEls.size());
    Element resource = rootEls.get(0);
    assertEquals("/", resource.getAttribute("path"));
    List<Element> resourceEls = DOMUtils.getChildrenWithName(resource,
                                                             WadlGenerator.WADL_NS, "resource");
    assertEquals(1, resourceEls.size());
    assertEquals("book", resourceEls.get(0).getAttribute("path"));

    verifyParameters(resourceEls.get(0), 1, new Param("id", "template", "xs:int"));

    checkGrammars(doc.getDocumentElement(), "thebook", null, "thechapter");
}
 
Example #11
Source File: WadlGeneratorTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testMultipleRootResources() throws Exception {
    WadlGenerator wg = new WadlGenerator();
    wg.setDefaultMediaType(WadlGenerator.WADL_TYPE.toString());
    ClassResourceInfo cri1 =
        ResourceUtils.createClassResourceInfo(BookStore.class, BookStore.class, true, true);
    ClassResourceInfo cri2 =
        ResourceUtils.createClassResourceInfo(Orders.class, Orders.class, true, true);
    List<ClassResourceInfo> cris = new ArrayList<>();
    cris.add(cri1);
    cris.add(cri2);
    Message m = mockMessage("http://localhost:8080/baz", "", WadlGenerator.WADL_QUERY, cris);
    Response r = handleRequest(wg, m);
    assertEquals(WadlGenerator.WADL_TYPE.toString(),
                 r.getMetadata().getFirst(HttpHeaders.CONTENT_TYPE).toString());
    String wadl = r.getEntity().toString();
    Document doc = StaxUtils.read(new StringReader(wadl));
    checkGrammars(doc.getDocumentElement(), "thebook", "books", "thebook2s", "thebook2", "thechapter");
    List<Element> els = getWadlResourcesInfo(doc, "http://localhost:8080/baz", 2);
    checkBookStoreInfo(els.get(0), "prefix1:thebook", "prefix1:thebook2", "prefix1:thechapter");
    Element orderResource = els.get(1);
    assertEquals("/orders", orderResource.getAttribute("path"));
}
 
Example #12
Source File: JAXRSParameterNameProvider.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Override
public List<String> getParameterNames(final Method method) {
    final List< Parameter > parameters = ResourceUtils.getParameters(method);
    final List< String > parameterNames = new ArrayList<>();

    for (int i = 0; i < parameters.size(); ++i) {
        final StringBuilder sb = new StringBuilder();
        sb.append("arg").append(i);
        sb.append('(');

        Parameter parameter = parameters.get(i);
        if (parameter.getName() != null) {
            sb.append(parameter.getType().toString());
            sb.append("(\"").append(parameter.getName()).append("\")");
            sb.append(' ');
        }
        sb.append(method.getParameterTypes()[i].getSimpleName());

        sb.append(')');
        parameterNames.add(sb.toString());
    }

    return parameterNames;
}
 
Example #13
Source File: WadlGenerator.java    From cxf with Apache License 2.0 6 votes vote down vote up
private void loadSchemasIntoCache(String loc) throws Exception {
    InputStream is = ResourceUtils.getResourceStream(loc,
        bus == null ? BusFactory.getDefaultBus() : bus);
    if (is == null) {
        return;
    }
    try (ByteArrayInputStream bis = IOUtils.loadIntoBAIS(is)) {
        XMLSource source = new XMLSource(bis);
        source.setBuffering();
        String targetNs = source.getValue("/*/@targetNamespace");

        Map<String, String> nsMap = Collections.singletonMap("xs", Constants.URI_2001_SCHEMA_XSD);
        String[] elementNames = source.getValues("/*/xs:element/@name", nsMap);
        externalQnamesMap.put(targetNs, Arrays.asList(elementNames));
        String schemaValue = source.getNode("/xs:schema", nsMap, String.class);
        externalSchemasCache.add(schemaValue);
    }
}
 
Example #14
Source File: SingletonResourceProvider.java    From cxf with Apache License 2.0 6 votes vote down vote up
public void init(Endpoint ep) {
    if (resourceInstance instanceof Constructor) {
        Constructor<?> c = (Constructor<?>)resourceInstance;
        Message m = new MessageImpl();
        ExchangeImpl exchange = new ExchangeImpl();
        exchange.put(Endpoint.class, ep);
        m.setExchange(exchange);
        Object[] values = 
            ResourceUtils.createConstructorArguments(c, m, false, Collections.emptyMap());
        try {
            resourceInstance = values.length > 0 ? c.newInstance(values) : c.newInstance(new Object[]{});
        } catch (Exception ex) {
            throw new ServiceConstructionException(ex);
        }
    }
    if (callPostConstruct) {
        InjectionUtils.invokeLifeCycleMethod(resourceInstance,
            ResourceUtils.findPostConstructMethod(ClassHelper.getRealClass(resourceInstance)));
    }    
}
 
Example #15
Source File: EHCacheTokenReplayCache.java    From cxf with Apache License 2.0 6 votes vote down vote up
public EHCacheTokenReplayCache(String configFile, Bus bus)
        throws IllegalAccessException, ClassNotFoundException, InstantiationException {
    if (bus == null) {
        bus = BusFactory.getThreadDefaultBus(true);
    }
    URL configFileURL = null;
    try {
        configFileURL =
                ResourceUtils.getClasspathResourceURL(configFile, EHCacheTokenReplayCache.class, bus);
    } catch (Exception ex) {
        // ignore
    }

    XmlConfiguration xmlConfig = new XmlConfiguration(getConfigFileURL(configFileURL));
    CacheConfigurationBuilder<String, EHCacheValue> configurationBuilder =
            xmlConfig.newCacheConfigurationBuilderFromTemplate(CACHE_KEY,
                    String.class, EHCacheValue.class);
    // Note, we don't require strong random values here
    String diskKey = CACHE_KEY + "-" + Math.abs(new Random().nextInt());
    cacheManager = CacheManagerBuilder.newCacheManagerBuilder().withCache(CACHE_KEY, configurationBuilder)
            .with(CacheManagerBuilder.persistence(new File(System.getProperty("java.io.tmpdir"), diskKey))).build();

    cacheManager.init();
    cache = cacheManager.getCache(CACHE_KEY, String.class, EHCacheValue.class);

}
 
Example #16
Source File: SourceGenerator.java    From cxf with Apache License 2.0 6 votes vote down vote up
private Element readDocument(String href) {
    try {
        InputStream is = null;
        if (!href.startsWith("http")) {
            is = ResourceUtils.getResourceStream(href, bus);
        }
        if (is == null) {
            URL url = new URL(href);
            if (href.startsWith("https") && authentication != null) {
                is = SecureConnectionHelper.getStreamFromSecureConnection(url, authentication);
            } else {
                is = url.openStream();
            }
        }
        try (Reader reader = new InputStreamReader(is, StandardCharsets.UTF_8)) {
            return StaxUtils.read(new InputSource(reader)).getDocumentElement();
        }
    } catch (Exception ex) {
        throw new RuntimeException("Resource " + href + " can not be read");
    }
}
 
Example #17
Source File: ClassResourceInfoProxyHelper.java    From HotswapAgent with GNU General Public License v2.0 6 votes vote down vote up
public static void reloadClassResourceInfo(ClassResourceInfo classResourceInfoProxy) {
    try {
        DISABLE_PROXY_GENERATION.set(true);
        CriProxyMethodHandler criMethodHandler = (CriProxyMethodHandler) ((ProxyObject)classResourceInfoProxy).getHandler();
        ClassResourceInfo newClassResourceInfo = (ClassResourceInfo) ReflectionHelper.invoke(null, ResourceUtils.class, "createClassResourceInfo",
                criMethodHandler.generatorTypes, criMethodHandler.generatorParams);
        ClassResourceInfo oldClassResourceInfo = criMethodHandler.delegate;
        ResourceProvider resourceProvider = oldClassResourceInfo.getResourceProvider();
        updateResourceProvider(resourceProvider);
        newClassResourceInfo.setResourceProvider(resourceProvider);
        criMethodHandler.delegate = newClassResourceInfo;
    } catch (Exception e) {
        LOGGER.error("reloadClassResourceInfo() exception {}", e.getMessage());
    } finally {
        DISABLE_PROXY_GENERATION.remove();
    }
}
 
Example #18
Source File: BrooklynRestResourceTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
protected synchronized void startServer() throws Exception {
    if (server == null) {
        setUpResources();
        
        // needed to enable session support
        serverEngine = new JettyHTTPServerEngineFactory().createJettyHTTPServerEngine(
            ENDPOINT_ADDRESS_HOST, ENDPOINT_ADDRESS_PORT, "http"); 
        serverEngine.setSessionSupport(true);
        JAXRSServerFactoryBean sf = ResourceUtils.createApplication(createRestApp(), true,false,false, BusFactory.getDefaultBus());
        if (clientProviders == null) {
            clientProviders = sf.getProviders();
        }
        configureCXF(sf);
        
        sf.setAddress(getEndpointAddress());
        sf.setFeatures(ImmutableList.of(new org.apache.cxf.feature.LoggingFeature()));
        server = sf.create();
    }
}
 
Example #19
Source File: CXFNonSpringJaxrsServlet.java    From JaxRSProviders with Apache License 2.0 6 votes vote down vote up
protected void createServerFromApplication(ServletConfig servletConfig)
    throws ServletException {

    Application app = getApplication();
    JAXRSServerFactoryBean bean = ResourceUtils.createApplication(
                                      app,
                                      isIgnoreApplicationPath(servletConfig),
                                      getStaticSubResolutionValue(servletConfig),
                                      isAppResourceLifecycleASingleton(app, servletConfig),
                                      getBus());
    String splitChar = getParameterSplitChar(servletConfig);
    setAllInterceptors(bean, servletConfig, splitChar);
    setInvoker(bean, servletConfig);
    setExtensions(bean, servletConfig);
    setDocLocation(bean, servletConfig);
    setSchemasLocations(bean, servletConfig);

    List<?> providers = getProviders(servletConfig, splitChar);
    bean.setProviders(providers);
    List<? extends Feature> features = getFeatures(servletConfig, splitChar);
    bean.setFeatures(features);

    bean.setBus(getBus());
    bean.setApplication(getApplication());
    bean.create();
}
 
Example #20
Source File: OpenApiParseUtils.java    From cxf with Apache License 2.0 5 votes vote down vote up
public static UserApplication getUserApplication(String loc, Bus bus, ParseConfiguration cfg) {    
    try {
        InputStream is = ResourceUtils.getResourceStream(loc, bus);
        if (is == null) {
            return null;
        }
        return getUserApplicationFromStream(is, cfg);
    } catch (Exception ex) {
        LOG.warning("Problem with processing a user model at " + loc);
    }
    return null;
}
 
Example #21
Source File: SwaggerParseUtils.java    From cxf with Apache License 2.0 5 votes vote down vote up
public static UserApplication getUserApplication(String loc, Bus bus, ParseConfiguration cfg) {    
    try {
        InputStream is = ResourceUtils.getResourceStream(loc, bus);
        if (is == null) {
            return null;
        }
        return getUserApplicationFromStream(is, cfg);
    } catch (Exception ex) {
        LOG.warning("Problem with processing a user model at " + loc);
    }
    return null;
}
 
Example #22
Source File: WadlGeneratorJsonTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testWadlInJsonFormat() throws Exception {
    ClassResourceInfo cri =
        ResourceUtils.createClassResourceInfo(BookChapters.class, BookChapters.class, true, true);
    final Message m = mockMessage("http://localhost:8080/baz", "/bookstore/1", WadlGenerator.WADL_QUERY, cri);
    Map<String, List<String>> headers = new HashMap<>();
    headers.put("Accept", Collections.singletonList("application/json"));
    m.put(Message.PROTOCOL_HEADERS, headers);

    WadlGenerator wg = new WadlGenerator() {
        @Override public void filter(ContainerRequestContext context) {
            super.doFilter(context, m);
        }
    };
    wg.setUseJaxbContextForQnames(false);
    wg.setIgnoreMessageWriters(false);
    wg.setExternalLinks(Collections.singletonList("json.schema"));

    Response r = handleRequest(wg, m);
    assertEquals("application/json",
            r.getMetadata().getFirst("Content-Type").toString());

    ByteArrayOutputStream os = new ByteArrayOutputStream();

    new JSONProvider<Document>().writeTo(
            (Document)r.getEntity(), Document.class, Document.class,
              new Annotation[]{}, MediaType.APPLICATION_JSON_TYPE,
              new MetadataMap<String, Object>(), os);
    String s = os.toString();
    String expected1 =
        "{\"application\":{\"grammars\":{\"include\":{\"@href\":\"http://localhost:8080/baz"
        + "/json.schema\"}},\"resources\":{\"@base\":\"http://localhost:8080/baz\","
        + "\"resource\":{\"@path\":\"/bookstore/{id}\"";
    assertTrue(s.startsWith(expected1));
    String expected2 =
        "\"response\":{\"representation\":[{\"@mediaType\":\"application/xml\"},"
        + "{\"@element\":\"Chapter\",\"@mediaType\":\"application/json\"}]}";
    assertTrue(s.contains(expected2));
}
 
Example #23
Source File: SwaggerToOpenApiConversionUtils.java    From cxf with Apache License 2.0 5 votes vote down vote up
public static String getOpenApiFromSwaggerLoc(String loc, OpenApiConfiguration cfg, Bus bus) {
    try {
        InputStream is = ResourceUtils.getResourceStream(loc, bus);
        if (is == null) {
            return null;
        }
        return getOpenApiFromSwaggerStream(is, cfg);
    } catch (Exception ex) {
        LOG.warning("Problem with processing a user model at " + loc + ", exception: "
            + ExceptionUtils.getStackTrace(ex));
    }
    return null;
}
 
Example #24
Source File: WadlGenerator.java    From cxf with Apache License 2.0 5 votes vote down vote up
private Map<Parameter, Object> getClassParameters(ClassResourceInfo cri) {
    Map<Parameter, Object> classParams = new LinkedHashMap<>();
    List<Method> paramMethods = cri.getParameterMethods();
    for (Method m : paramMethods) {
        classParams.put(ResourceUtils.getParameter(0, m.getAnnotations(), m.getParameterTypes()[0]), m);
    }
    List<Field> fieldParams = cri.getParameterFields();
    for (Field f : fieldParams) {
        classParams.put(ResourceUtils.getParameter(0, f.getAnnotations(), f.getType()), f);
    }
    return classParams;
}
 
Example #25
Source File: JAXRSClientFactoryBeanDefinitionParser.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Override
protected void mapElement(ParserContext ctx, MutableBeanMetadata bean, Element el, String name) {
    if ("properties".equals(name) || "headers".equals(name)) {
        bean.addProperty(name, this.parseMapData(ctx, bean, el));
    } else if ("executor".equals(name)) {
        setFirstChildAsProperty(el, ctx, bean, "serviceFactory.executor");
    } else if ("binding".equals(name)) {
        setFirstChildAsProperty(el, ctx, bean, "bindingConfig");
    } else if ("inInterceptors".equals(name) || "inFaultInterceptors".equals(name)
        || "outInterceptors".equals(name) || "outFaultInterceptors".equals(name)) {
        bean.addProperty(name, parseListData(ctx, bean, el));
    } else if ("features".equals(name) || "providers".equals(name)
               || "schemaLocations".equals(name) || "modelBeans".equals(name)) {
        bean.addProperty(name, parseListData(ctx, bean, el));
    } else if ("model".equals(name)) {
        List<UserResource> resources = ResourceUtils.getResourcesFromElement(el);
        MutableCollectionMetadata list = ctx.createMetadata(MutableCollectionMetadata.class);
        list.setCollectionClass(List.class);
        for (UserResource res : resources) {
            MutablePassThroughMetadata factory = ctx.createMetadata(MutablePassThroughMetadata.class);
            factory.setObject(new PassThroughCallable<Object>(res));

            MutableBeanMetadata resourceBean = ctx.createMetadata(MutableBeanMetadata.class);
            resourceBean.setFactoryComponent(factory);
            resourceBean.setFactoryMethod("call");
            list.addValue(resourceBean);
        }
        bean.addProperty("modelBeans", list);
    } else {
        setFirstChildAsProperty(el, ctx, bean, name);
    }
}
 
Example #26
Source File: JAXBElementProviderTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testGenericsAndSingleContext() throws Exception {
    ClassResourceInfo cri =
        ResourceUtils.createClassResourceInfo(XmlListResource.class, XmlListResource.class, true, true);
    JAXBElementProvider<?> provider = new JAXBElementProvider<>();
    provider.setSingleJaxbContext(true);
    provider.init(Collections.singletonList(cri));
    testXmlList(provider);
}
 
Example #27
Source File: MicroProfileServiceFactoryBean.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Override
protected ClassResourceInfo createResourceInfo(Class<?> cls, boolean isRoot) {
    return addClassResourceInfo(
        ResourceUtils.createClassResourceInfo(cls, cls, null, isRoot, true, getBus(),
                                              Collections.singletonList(MediaType.APPLICATION_JSON_TYPE),
                                              Collections.singletonList(MediaType.APPLICATION_JSON_TYPE)));
}
 
Example #28
Source File: JAXBElementProviderTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testSetSchemasFromAnnotation() {
    JAXBElementProvider<?> provider = new JAXBElementProvider<>();
    ClassResourceInfo cri =
        ResourceUtils.createClassResourceInfo(JAXBResource.class, JAXBResource.class, true, true);
    provider.init(Collections.singletonList(cri));
    Schema s = provider.getSchema();
    assertNotNull("schema can not be read from classpath", s);
}
 
Example #29
Source File: JAXBElementProviderTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testGenericsAndSingleContext2() throws Exception {
    ClassResourceInfo cri =
        ResourceUtils.createClassResourceInfo(XmlListResource.class, XmlListResource.class, true, true);
    JAXBElementProvider<?> provider = new JAXBElementProvider<>();
    provider.setSingleJaxbContext(true);
    provider.init(Collections.singletonList(cri));

    List<org.apache.cxf.jaxrs.fortest.jaxb.SuperBook> list = new ArrayList<>();
    for (int i = 0; i < 10; i++) {
        org.apache.cxf.jaxrs.fortest.jaxb.SuperBook o =
            new org.apache.cxf.jaxrs.fortest.jaxb.SuperBook();
        o.setName("name #" + i);
        list.add(o);
    }
    XmlList<org.apache.cxf.jaxrs.fortest.jaxb.SuperBook> xmlList = new XmlList<>(list);

    Method m = XmlListResource.class.getMethod("testJaxb2", new Class[]{});
    JAXBContext context = provider.getJAXBContext(m.getReturnType(), m.getGenericReturnType());

    ByteArrayOutputStream os = new ByteArrayOutputStream();
    context.createMarshaller().marshal(xmlList, os);
    @SuppressWarnings("unchecked")
    XmlList<org.apache.cxf.jaxrs.fortest.jaxb.SuperBook> list2 =
        (XmlList<org.apache.cxf.jaxrs.fortest.jaxb.SuperBook>)context.createUnmarshaller()
            .unmarshal(new ByteArrayInputStream(os.toByteArray()));

    List<org.apache.cxf.jaxrs.fortest.jaxb.SuperBook> actualList = list2.getList();
    assertEquals(10, actualList.size());
    for (int i = 0; i < 10; i++) {
        org.apache.cxf.jaxrs.fortest.jaxb.SuperBook object = actualList.get(i);
        assertEquals("name #" + i, object.getName());
    }
}
 
Example #30
Source File: CXFNonSpringJaxrsServlet.java    From JaxRSProviders with Apache License 2.0 5 votes vote down vote up
protected void createServerFromApplication(String applicationNames, ServletConfig servletConfig)
    throws ServletException {

    boolean ignoreApplicationPath = isIgnoreApplicationPath(servletConfig);

    String[] classNames = applicationNames.split(getParameterSplitChar(servletConfig));

    if (classNames.length > 1 && ignoreApplicationPath) {
        throw new ServletException("\"" + IGNORE_APP_PATH_PARAM
            + "\" parameter must be set to false for multiple Applications be supported");
    }

    for (String cName : classNames) {
        ApplicationInfo providerApp = createApplicationInfo(cName, servletConfig);

        Application app = providerApp.getProvider();
        JAXRSServerFactoryBean bean = ResourceUtils.createApplication(
                                            app,
                                            ignoreApplicationPath,
                                            getStaticSubResolutionValue(servletConfig),
                                            isAppResourceLifecycleASingleton(app, servletConfig),
                                            getBus());
        String splitChar = getParameterSplitChar(servletConfig);
        setAllInterceptors(bean, servletConfig, splitChar);
        setInvoker(bean, servletConfig);
        setExtensions(bean, servletConfig);
        setDocLocation(bean, servletConfig);
        setSchemasLocations(bean, servletConfig);

        List<?> providers = getProviders(servletConfig, splitChar);
        bean.setProviders(providers);
        List<? extends Feature> features = getFeatures(servletConfig, splitChar);
        bean.setFeatures(features);

        bean.setBus(getBus());
        bean.setApplicationInfo(providerApp);
        bean.create();
    }
}