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

The following examples show how to use org.apache.cxf.jaxrs.utils.ResourceUtils. 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: JaxRSProviders   Source File: CXFNonSpringJaxrsServlet.java    License: 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 2
Source Project: brooklyn-server   Source File: BrooklynRestResourceTest.java    License: 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 3
Source Project: cxf   Source File: SourceGenerator.java    License: 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 4
Source Project: cxf   Source File: SingletonResourceProvider.java    License: 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 5
Source Project: cxf   Source File: JAXRSParameterNameProvider.java    License: 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 6
Source Project: cxf   Source File: CXFNonSpringJaxrsServlet.java    License: 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 7
Source Project: cxf   Source File: BlueprintResourceFactory.java    License: 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 8
Source Project: cxf   Source File: EHCacheTokenReplayCache.java    License: 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 9
Source Project: cxf   Source File: OpenApiCustomizer.java    License: 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 10
Source Project: cxf   Source File: WadlGenerator.java    License: 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 11
Source Project: cxf   Source File: WadlGenerator.java    License: 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 12
Source Project: cxf   Source File: WadlGeneratorTest.java    License: 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 13
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 14
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 15
Source Project: cxf   Source File: WadlGeneratorTest.java    License: 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 16
Source Project: cxf   Source File: WadlGeneratorTest.java    License: 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 17
Source Project: cxf   Source File: WadlGeneratorTest.java    License: 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 18
Source Project: cxf   Source File: WadlGeneratorTest.java    License: 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 19
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 20
Source Project: aries-jax-rs-whiteboard   Source File: ClassIntrospector.java    License: Apache License 2.0 5 votes vote down vote up
public static Collection<ResourceMethodInfoDTO> getResourceMethodInfos(
    Class<?> clazz, Bus bus) {

    ClassResourceInfo classResourceInfo =
        ResourceUtils.createClassResourceInfo(
            clazz, clazz, true, true, bus);

    Stream<ResourceMethodInfoDTO> convert = convert(
        new HashSet<>(), "/", null, null, null, null,
        true, classResourceInfo);

    return convert.collect(Collectors.toList());
}
 
Example 21
Source Project: JaxRSProviders   Source File: CXFNonSpringJaxrsServlet.java    License: 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();
    }
}
 
Example 22
Source Project: cxf   Source File: JAXRSCdiResourceExtension.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Create the JAXRSServerFactoryBean from the application and all discovered service and provider instances.
 * @param application application instance
 * @param services all discovered services
 * @param providers all discovered providers
 * @return JAXRSServerFactoryBean instance
 */
private JAXRSServerFactoryBean createFactoryInstance(final Application application, final List< ? > services,
        final List< ? > providers, final List< ? extends Feature > features) {

    final JAXRSServerFactoryBean instance = 
        ResourceUtils.createApplication(application, false, false, false, bus);
    instance.setServiceBeans(new ArrayList<>(services));
    instance.setProviders(providers);
    instance.setProviders(loadExternalProviders());
    instance.setFeatures(features);

    return instance;
}
 
Example 23
Source Project: cxf   Source File: JAXRSCdiResourceExtension.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Create the JAXRSServerFactoryBean from the objects declared by application itself.
 * @param application application instance
 * @return JAXRSServerFactoryBean instance
 */
private JAXRSServerFactoryBean createFactoryInstance(final Application application, final BeanManager beanManager) {
    final JAXRSServerFactoryBean instance =
        ResourceUtils.createApplication(application, false, false, false, bus);
    final ClassifiedClasses classified = classes2singletons(application, beanManager);

    instance.setProviders(classified.getProviders());
    instance.getFeatures().addAll(classified.getFeatures());

    for (final ResourceProvider resourceProvider: classified.getResourceProviders()) {
        instance.setResourceProvider(resourceProvider.getResourceClass(), resourceProvider);
    }

    return instance;
}
 
Example 24
Source Project: cxf   Source File: SourceGenerator.java    License: Apache License 2.0 5 votes vote down vote up
private void addSchemas(List<SchemaInfo> schemas, SchemaCompiler compiler) {
    // handle package customizations first
    for (int i = 0; i < schemaPackageFiles.size(); i++) {
        compiler.parseSchema(schemaPackageFiles.get(i));
    }

    for (int i = 0; i < schemas.size(); i++) {
        SchemaInfo schema = schemas.get(i);

        String key = schema.getSystemId();
        if (key != null) {
            // TODO: CXF code should have a better solution somewhere, we'll get back to it
            // when addressing the issue of retrieving WADLs with included schemas
            if (key.startsWith("classpath:")) {
                String resource = key.substring(10);
                URL url = ResourceUtils.getClasspathResourceURL(resource,
                                                                SourceGenerator.class,
                                                                bus);
                if (url != null) {
                    try {
                        key = url.toURI().toString();
                    } catch (Exception ex) {
                        // won't happen
                    }
                }
            }
        } else {
            key = Integer.toString(i);
        }
        InputSource is = new InputSource((InputStream)null);
        is.setSystemId(key);
        is.setPublicId(key);
        compiler.getOptions().addGrammar(is);
        compiler.parseSchema(key, schema.getElement());
    }
}
 
Example 25
Source Project: cxf   Source File: PerRequestResourceProvider.java    License: Apache License 2.0 5 votes vote down vote up
public PerRequestResourceProvider(Class<?> clazz) {
    c = ResourceUtils.findResourceConstructor(clazz, true);
    if (c == null) {
        throw new RuntimeException("Resource class " + clazz
                                   + " has no valid constructor");
    }
    params = c.getParameterTypes();
    anns = c.getParameterAnnotations();
    genericTypes = c.getGenericParameterTypes();
    postConstructMethod = ResourceUtils.findPostConstructMethod(clazz);
    preDestroyMethod = ResourceUtils.findPreDestroyMethod(clazz);
}
 
Example 26
Source Project: cxf   Source File: AbstractJAXRSFactoryBean.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Sets a reference to the external user model,
 * Example: "classpath:/model/resources.xml"
 *
 * @param modelRef the reference to the external model resource.
 */
public void setModelRef(String modelRef) {
    List<UserResource> resources = ResourceUtils.getUserResources(modelRef, getBus());
    if (resources != null) {
        serviceFactory.setUserResources(resources);
    }
}
 
Example 27
Source Project: cxf   Source File: SpringResourceFactory.java    License: Apache License 2.0 5 votes vote down vote up
private void init() {
    type = ClassHelper.getRealClassFromClass(ac.getType(beanId));
    if (Proxy.isProxyClass(type)) {
        type = ClassHelper.getRealClass(ac.getBean(beanId));
    }
    isSingleton = ac.isSingleton(beanId);
    postConstructMethod = ResourceUtils.findPostConstructMethod(type, postConstructMethodName);
    preDestroyMethod = ResourceUtils.findPreDestroyMethod(type, preDestroyMethodName);

    if (isSingleton()) {
        try {
            singletonInstance = ac.getBean(beanId);
        } catch (BeansException ex) {
            // ignore for now, try resolving resource constructor later
        }
        if (singletonInstance != null) {
            return;
        }
    } else {
        isPrototype = ac.isPrototype(beanId);
    }
    c = ResourceUtils.findResourceConstructor(type, !isSingleton());
    if (c == null) {
        throw new RuntimeException("Resource class " + type
                                   + " has no valid constructor");
    }

}
 
Example 28
Source Project: cxf   Source File: SpringResourceFactory.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public Object getInstance(Message m) {
    if (singletonInstance != null) {
        return singletonInstance;
    }
    ProviderInfo<?> application = m == null ? null
        : (ProviderInfo<?>)m.getExchange().getEndpoint().get(Application.class.getName());
    Map<Class<?>, Object> mapValues = CastUtils.cast(application == null ? null
        : Collections.singletonMap(Application.class, application.getProvider()));
    Object[] values = ResourceUtils.createConstructorArguments(c, m, !isSingleton(), mapValues);
    Object instance = values.length > 0 ? ac.getBean(beanId, values) : ac.getBean(beanId);
    initInstance(m, instance);
    return instance;
}
 
Example 29
Source Project: cxf   Source File: CXFNonSpringJaxrsServlet.java    License: 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.getFeatures().addAll(features);

        bean.setBus(getBus());
        bean.setApplicationInfo(providerApp);
        bean.create();
    }
}
 
Example 30
Source Project: cxf   Source File: OperationResourceInfo.java    License: Apache License 2.0 5 votes vote down vote up
public OperationResourceInfo(Method mInvoke, Method mAnnotated, ClassResourceInfo cri) {
    methodToInvoke = mInvoke;
    annotatedMethod = mAnnotated;
    if (mAnnotated != null) {
        parameters = ResourceUtils.getParameters(mAnnotated);
        nameBindings = AnnotationUtils.getNameBindings(mAnnotated.getAnnotations());
    }
    classResourceInfo = cri;
    checkMediaTypes(null, null);
    checkEncoded();
    checkDefaultParameterValue();
    checkOneway();
    checkSuspended();
    initActualMethodProperties();
}