javax.ws.rs.ext.RuntimeDelegate Java Examples

The following examples show how to use javax.ws.rs.ext.RuntimeDelegate. 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: UriUtil.java    From container with Apache License 2.0 6 votes vote down vote up
public static URI generateSubResourceURI(final UriInfo uriInfo, final String subResource,
                                         final boolean encodeSubResourcePathSegment) {
    logger.debug("Generating sub resource URI for sub resource: {} with encoding flag: {}", subResource, encodeSubResourcePathSegment);
    final UriBuilder uriBuilder = RuntimeDelegate.getInstance().createUriBuilder();
    uriBuilder.path(uriInfo.getAbsolutePath().toString());
    uriBuilder.path("{resourceId}");
    URI finalUri;

    if (encodeSubResourcePathSegment) {
        finalUri = uriBuilder.build(subResource);
    } else {
        finalUri = uriBuilder.buildFromEncoded(subResource);
    }
    logger.debug("Final URI: {}", finalUri);

    return finalUri;
}
 
Example #2
Source File: Main.java    From http-server-benchmarks with MIT License 6 votes vote down vote up
public static HttpServer startServer() {
    HttpServer server = new HttpServer();
    server.addListener(new NetworkListener("grizzly", "0.0.0.0", 8080));

    final TCPNIOTransportBuilder transportBuilder = TCPNIOTransportBuilder.newInstance();
    //transportBuilder.setIOStrategy(WorkerThreadIOStrategy.getInstance());
    transportBuilder.setIOStrategy(SameThreadIOStrategy.getInstance());
    server.getListener("grizzly").setTransport(transportBuilder.build());
    final ResourceConfig rc = new ResourceConfig().packages("xyz.muetsch.jersey");
    rc.register(JacksonFeature.class);
    final ServerConfiguration config = server.getServerConfiguration();
    config.addHttpHandler(RuntimeDelegate.getInstance().createEndpoint(rc, GrizzlyHttpContainer.class), "/rest/todo/");

    try {
        server.start();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return server;
}
 
Example #3
Source File: EverrestGuiceContextListener.java    From everrest with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void contextInitialized(ServletContextEvent sce) {
    super.contextInitialized(sce);
    ServletContext servletContext = sce.getServletContext();
    ResourceBinderImpl resources = new ResourceBinderImpl();
    ApplicationProviderBinder providers = new ApplicationProviderBinder();
    Injector injector = getInjector(servletContext);
    DependencySupplier dependencySupplier = new GuiceDependencySupplier(injector);
    EverrestConfiguration config = injector.getInstance(EverrestConfiguration.class);
    EverrestServletContextInitializer everrestInitializer = new EverrestServletContextInitializer(servletContext);
    Application application = everrestInitializer.getApplication();
    EverrestApplication everrest = new EverrestApplication();
    if (config.isAsynchronousSupported()) {
        everrest.addResource(config.getAsynchronousServicePath(), AsynchronousJobService.class);
        everrest.addSingleton(new AsynchronousJobPool(config));
        everrest.addSingleton(new AsynchronousProcessListWriter());
    }
    if (config.isCheckSecurity()) {
        everrest.addSingleton(new SecurityConstraint());
    }
    everrest.addApplication(application);

    processBindings(injector, everrest);
    RequestDispatcher requestDispatcher = new RequestDispatcher(resources);
    RequestHandlerImpl requestHandler = new RequestHandlerImpl(requestDispatcher, providers);
    EverrestProcessor processor = new EverrestProcessor(config, dependencySupplier, requestHandler, everrest);
    processor.start();

    servletContext.setAttribute(EverrestConfiguration.class.getName(), config);
    servletContext.setAttribute(Application.class.getName(), everrest);
    servletContext.setAttribute(DependencySupplier.class.getName(), dependencySupplier);
    servletContext.setAttribute(ResourceBinder.class.getName(), resources);
    servletContext.setAttribute(ApplicationProviderBinder.class.getName(), providers);
    servletContext.setAttribute(EverrestProcessor.class.getName(), processor);
    // use specific RuntimeDelegate instance which is able to work with guice rest service proxies.
    // (need for interceptors functionality)
    RuntimeDelegate.setInstance(new GuiceRuntimeDelegateImpl());
}
 
Example #4
Source File: CoffeeConfig.java    From product-ei with Apache License 2.0 5 votes vote down vote up
@Bean
 public org.apache.cxf.endpoint.Server jaxRsServer() {
     JAXRSServerFactoryBean factory = RuntimeDelegate.getInstance().createEndpoint( jaxRsApiApplication(), JAXRSServerFactoryBean.class );
     factory.setServiceBeans( Arrays.< Object >asList(starbucksOutletService()) );
     factory.setAddress( "/" + factory.getAddress() );
List<Object> providers = new ArrayList<Object>();
     providers.add(jsonProvider());
     providers.add(new OrderReader());
     factory.setProviders(providers);
     //factory.setProviders( Arrays.< Object >asList( jsonProvider() ) );
     return factory.create();
 }
 
Example #5
Source File: CustomerConfig.java    From product-ei with Apache License 2.0 5 votes vote down vote up
@Bean
public org.apache.cxf.endpoint.Server jaxRsServer() {
    JAXRSServerFactoryBean factory = RuntimeDelegate.getInstance().createEndpoint( jaxRsApiApplication(), JAXRSServerFactoryBean.class );
    factory.setServiceBeans( Arrays.< Object >asList(customerService()) );
    factory.setAddress( "/" + factory.getAddress() );
    factory.setProviders( Arrays.< Object >asList( jsonProvider() ) );
    return factory.create();
}
 
Example #6
Source File: MusicConfig.java    From product-ei with Apache License 2.0 5 votes vote down vote up
@Bean
public Server jaxRsServer() {
    JAXRSServerFactoryBean factory = RuntimeDelegate.getInstance().createEndpoint( jaxRsApiApplication(), JAXRSServerFactoryBean.class );
    factory.setServiceBeans( Arrays.< Object >asList(musicRestService()) );
    factory.setAddress( "/" + factory.getAddress() );
    factory.setProviders( Arrays.< Object >asList( jsonProvider() ) );
    return factory.create();
}
 
Example #7
Source File: AppConfig.java    From product-ei with Apache License 2.0 5 votes vote down vote up
@Bean
public Server jaxRsServer() {
    JAXRSServerFactoryBean factory = RuntimeDelegate.getInstance().createEndpoint( jaxRsApiApplication(), JAXRSServerFactoryBean.class );
    factory.setServiceBeans( Arrays.< Object >asList( peopleRestService() ) );
    factory.setAddress( "/" + factory.getAddress() );
    factory.setProviders( Arrays.< Object >asList( jsonProvider() ) );
    return factory.create();
}
 
Example #8
Source File: CxfJaxrsServiceRegistrator.java    From aries-jax-rs-whiteboard with Apache License 2.0 5 votes vote down vote up
public <T> T createEndpoint(Application app, Class<T> endpointType) {
    JAXRSServerFactoryBean bean =
        RuntimeDelegate.getInstance().createEndpoint(
            app, JAXRSServerFactoryBean.class);

    if (JAXRSServerFactoryBean.class.isAssignableFrom(endpointType)) {
        return endpointType.cast(bean);
    }
    bean.setApplication(app);
    bean.setStart(false);
    Server server = bean.create();
    return endpointType.cast(server);
}
 
Example #9
Source File: Activator.java    From XPagesExtensionLibrary with Apache License 2.0 5 votes vote down vote up
@Override
public void start(BundleContext context) throws Exception {
	// Ensure that the service loader uses the right class
	// See: http://www.mail-archive.com/[email protected]/msg07539.html
	ClassLoader oldcl = Thread.currentThread().getContextClassLoader();
	ClassLoader newcl = RuntimeDelegate.class.getClassLoader();
	
	Thread.currentThread().setContextClassLoader(newcl);
	try {
		RuntimeDelegate.setInstance(new RuntimeDelegateImpl());
	} finally {
		Thread.currentThread().setContextClassLoader(oldcl);
	}
	super.start(context);
}
 
Example #10
Source File: UriUtil.java    From container with Apache License 2.0 5 votes vote down vote up
public static URI encode(final URI uri) {
    final List<PathSegment> pathSegments = UriComponent.decodePath(uri, false);
    final UriBuilder uriBuilder = RuntimeDelegate.getInstance().createUriBuilder();
    // Build base URL
    uriBuilder.scheme(uri.getScheme()).host(uri.getHost()).port(uri.getPort());
    // Iterate over path segments and encode it if necessary
    for (final PathSegment ps : pathSegments) {
        uriBuilder.path(UriComponent.encode(ps.toString(), UriComponent.Type.PATH_SEGMENT));
    }
    logger.debug("URL before encoding: {}", uri.toString());
    URI result = uriBuilder.build();
    logger.debug("URL after encoding:  {}", result.toString());
    return result;
}
 
Example #11
Source File: StatsConfig.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Bean @DependsOn("cxf")
Server jaxRsServer() {
    final JAXRSServerFactoryBean factory = RuntimeDelegate
        .getInstance()
        .createEndpoint(new StatsApplication(), JAXRSServerFactoryBean.class);
    factory.setServiceBean(statsRestService);
    factory.setProvider(new JacksonJsonProvider());
    return factory.create();
}
 
Example #12
Source File: OpenApiCustomizerTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Override
protected void run() {
    final JAXRSServerFactoryBean sf = RuntimeDelegate
        .getInstance()
        .createEndpoint(new BookStoreApplication(), JAXRSServerFactoryBean.class);
    sf.setResourceClasses(BookStoreOpenApi.class);
    sf.setResourceClasses(BookStoreStylesheetsOpenApi.class);
    sf.setResourceProvider(BookStoreOpenApi.class,
        new SingletonResourceProvider(new BookStoreOpenApi()));
    sf.setProvider(new JacksonJsonProvider());
    final OpenApiFeature feature = createOpenApiFeature();
    sf.setFeatures(Arrays.asList(feature));
    sf.setAddress("http://localhost:" + port + "/api");
    sf.create();
}
 
Example #13
Source File: HttpUtils.java    From cxf with Apache License 2.0 5 votes vote down vote up
public static RuntimeDelegate getOtherRuntimeDelegate() {
    try {
        RuntimeDelegate rd = RuntimeDelegate.getInstance();
        return rd instanceof RuntimeDelegateImpl ? null : rd;
    } catch (Throwable t) {
        return null;
    }
}
 
Example #14
Source File: HttpUtils.java    From cxf with Apache License 2.0 5 votes vote down vote up
public static void convertHeaderValuesToString(Map<String, List<Object>> headers, boolean delegateOnly) {
    if (headers == null) {
        return;
    }
    RuntimeDelegate rd = getOtherRuntimeDelegate();
    if (rd == null && delegateOnly) {
        return;
    }
    for (Map.Entry<String, List<Object>> entry : headers.entrySet()) {
        List<Object> values = entry.getValue();
        for (int i = 0; i < values.size(); i++) {
            Object value = values.get(i);

            if (value != null && !(value instanceof String)) {

                HeaderDelegate<Object> hd = getHeaderDelegate(rd, value);

                if (hd != null) {
                    value = hd.toString(value);
                } else if (!delegateOnly) {
                    value = value.toString();
                }

                try {
                    values.set(i, value);
                } catch (UnsupportedOperationException ex) {
                    // this may happen if an unmodifiable List was set via Map put
                    List<Object> newList = new ArrayList<>(values);
                    newList.set(i, value);
                    // Won't help if the map is unmodifiable in which case it is a bug anyway
                    headers.put(entry.getKey(), newList);
                }

            }

        }
    }

}
 
Example #15
Source File: ResponseImplTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
public static final void assertNotStringBeanRuntimeDelegate(RuntimeDelegate delegate) {
    if (delegate instanceof StringBeanRuntimeDelegate) {
        StringBeanRuntimeDelegate sbrd = (StringBeanRuntimeDelegate) delegate;
        if (sbrd.getOriginal() != null) {
            RuntimeDelegate.setInstance(sbrd.getOriginal());
            throw new RuntimeException(
                "RuntimeDelegate.getInstance() is StringBeanRuntimeDelegate");
        }
    }
}
 
Example #16
Source File: InvocationBuilderImpl.java    From cxf with Apache License 2.0 5 votes vote down vote up
private void doSetHeader(RuntimeDelegate rd, String name, Object value) {
    HeaderDelegate<Object> hd = HttpUtils.getHeaderDelegate(rd, value);
    if (hd != null) {
        value = hd.toString(value);
    }
    
    // If value is null then all current headers of the same name should be removed
    if (value == null) {
        webClient.replaceHeader(name, value);
    } else {
        webClient.header(name, value);
    }
}
 
Example #17
Source File: AppConfig.java    From micro-integrator with Apache License 2.0 5 votes vote down vote up
@Bean
public Server jaxRsServer() {
    JAXRSServerFactoryBean factory = RuntimeDelegate.getInstance()
            .createEndpoint(jaxRsApiApplication(), JAXRSServerFactoryBean.class);
    factory.setServiceBeans(Arrays.<Object>asList(peopleRestService()));
    factory.setAddress("/" + factory.getAddress());
    factory.setProviders(Arrays.<Object>asList(jsonProvider()));
    return factory.create();
}
 
Example #18
Source File: ResponseImpl.java    From everrest with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public Locale getLanguage() {
    Object value = getMetadata().getFirst(CONTENT_LANGUAGE);
    if (value == null) {
        return null;
    }
    if (value instanceof Locale) {
        return (Locale)value;
    }
    return RuntimeDelegate.getInstance().createHeaderDelegate(Locale.class)
                          .fromString(value instanceof String ? (String)value : getHeaderAsString(value));
}
 
Example #19
Source File: ContainerRequest.java    From everrest with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public Locale getLanguage() {
    if (contentLanguage == null && httpHeaders.getFirst(CONTENT_LANGUAGE) != null) {
        contentLanguage = RuntimeDelegate.getInstance().createHeaderDelegate(Locale.class).fromString(httpHeaders.getFirst(CONTENT_LANGUAGE));
    }

    return contentLanguage;
}
 
Example #20
Source File: AcceptMediaTypeTest.java    From everrest with Eclipse Public License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Before
public void setUp() throws Exception {
    headerDelegate = mock(HeaderDelegate.class);

    RuntimeDelegate runtimeDelegate = mock(RuntimeDelegate.class);
    when(runtimeDelegate.createHeaderDelegate(AcceptMediaType.class)).thenReturn(headerDelegate);

    RuntimeDelegate.setInstance(runtimeDelegate);
}
 
Example #21
Source File: HeaderHelperTest.java    From everrest with Eclipse Public License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void transformsObjectToStringWithHeaderDelegate() throws Exception {
    RuntimeDelegate runtimeDelegate = mock(RuntimeDelegate.class);
    RuntimeDelegate.setInstance(runtimeDelegate);

    HeaderDelegate<String> headerDelegate = mock(HeaderDelegate.class);
    when(runtimeDelegate.createHeaderDelegate(String.class)).thenReturn(headerDelegate);
    when(headerDelegate.toString("foo")).thenReturn("<foo>");

    assertEquals("<foo>", HeaderHelper.getHeaderAsString("foo"));
}
 
Example #22
Source File: HeaderHelperTest.java    From everrest with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void transformsObjectToStringWithToStringMethodWhenHeaderDelegateDoesNotPresent() throws Exception {
    RuntimeDelegate runtimeDelegate = mock(RuntimeDelegate.class);
    RuntimeDelegate.setInstance(runtimeDelegate);

    Object someObject = mock(Object.class);
    when(someObject.toString()).thenReturn("<foo>");

    assertEquals("<foo>", HeaderHelper.getHeaderAsString(someObject));
}
 
Example #23
Source File: AcceptLanguageTest.java    From everrest with Eclipse Public License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Before
public void setUp() throws Exception {
    headerDelegate = mock(RuntimeDelegate.HeaderDelegate.class);

    RuntimeDelegate runtimeDelegate = mock(RuntimeDelegate.class);
    when(runtimeDelegate.createHeaderDelegate(AcceptLanguage.class)).thenReturn(headerDelegate);

    RuntimeDelegate.setInstance(runtimeDelegate);
}
 
Example #24
Source File: RangesTest.java    From everrest with Eclipse Public License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Before
public void setUp() throws Exception {
    headerDelegate = mock(HeaderDelegate.class);

    RuntimeDelegate runtimeDelegate = mock(RuntimeDelegate.class);
    when(runtimeDelegate.createHeaderDelegate(Ranges.class)).thenReturn(headerDelegate);

    RuntimeDelegate.setInstance(runtimeDelegate);
}
 
Example #25
Source File: ResponseImplTest.java    From everrest with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void getsHeadersAsStringToStringMapAndUsesRuntimeDelegateForConvertValuesToString() throws Exception {
    HeaderDelegate<HeaderValue> headerDelegate = mock(HeaderDelegate.class);
    when(headerDelegate.toString(isA(HeaderValue.class))).thenReturn("bar");
    RuntimeDelegate runtimeDelegate = mock(RuntimeDelegate.class);
    when(runtimeDelegate.createHeaderDelegate(HeaderValue.class)).thenReturn(headerDelegate);
    RuntimeDelegate.setInstance(runtimeDelegate);

    MultivaluedMap<String, Object> headers = new MultivaluedHashMap<>();
    headers.put("foo", newArrayList(new HeaderValue()));
    ResponseImpl response = new ResponseImpl(200, "foo", null, headers);

    assertEquals(ImmutableMap.of("foo", newArrayList("bar")), response.getStringHeaders());
}
 
Example #26
Source File: ResponseImplTest.java    From everrest with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void getsHeadersAsStringToStringMapAndUsesToStringMethodOfValueToConvertIt() throws Exception {
    RuntimeDelegate runtimeDelegate = mock(RuntimeDelegate.class);
    RuntimeDelegate.setInstance(runtimeDelegate);

    MultivaluedMap<String, Object> headers = new MultivaluedHashMap<>();
    HeaderValue headerValue = mock(HeaderValue.class);
    when(headerValue.toString()).thenReturn("bar");
    headers.put("foo", newArrayList(headerValue));
    ResponseImpl response = new ResponseImpl(200, "foo", null, headers);

    assertEquals(ImmutableMap.of("foo", newArrayList("bar")), response.getStringHeaders());
}
 
Example #27
Source File: ResponseImplTest.java    From everrest with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void getSingleHeaderAsStringAndUsesRuntimeDelegateForConvertValueToString() throws Exception {
    HeaderDelegate<HeaderValue> headerDelegate = mock(HeaderDelegate.class);
    when(headerDelegate.toString(isA(HeaderValue.class))).thenReturn("bar");
    RuntimeDelegate runtimeDelegate = mock(RuntimeDelegate.class);
    when(runtimeDelegate.createHeaderDelegate(HeaderValue.class)).thenReturn(headerDelegate);
    RuntimeDelegate.setInstance(runtimeDelegate);

    MultivaluedMap<String, Object> headers = new MultivaluedHashMap<>();
    headers.put("foo", newArrayList(new HeaderValue()));
    ResponseImpl response = new ResponseImpl(200, "foo", null, headers);

    assertEquals("bar", response.getHeaderString("foo"));
}
 
Example #28
Source File: ResponseImplTest.java    From everrest with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void getMultipleHeaderAsStringAndUsesRuntimeDelegateForConvertValuesToString() throws Exception {
    HeaderDelegate<HeaderValue> headerDelegate = mock(HeaderDelegate.class);
    when(headerDelegate.toString(isA(HeaderValue.class))).thenReturn("bar1", "bar2");
    RuntimeDelegate runtimeDelegate = mock(RuntimeDelegate.class);
    when(runtimeDelegate.createHeaderDelegate(HeaderValue.class)).thenReturn(headerDelegate);
    RuntimeDelegate.setInstance(runtimeDelegate);

    MultivaluedMap<String, Object> headers = new MultivaluedHashMap<>();
    headers.put("foo", newArrayList(new HeaderValue(), new HeaderValue()));
    ResponseImpl response = new ResponseImpl(200, "foo", null, headers);

    assertEquals("bar1,bar2", response.getHeaderString("foo"));
}
 
Example #29
Source File: AppConfig.java    From service-autodiscovery with Apache License 2.0 5 votes vote down vote up
@Bean @DependsOn( "cxf" )
public Server jaxRsServer() {
	JAXRSServerFactoryBean factory = RuntimeDelegate.getInstance().createEndpoint( jaxRsApiApplication(), JAXRSServerFactoryBean.class );
	factory.setServiceBeans( Arrays.< Object >asList( peopleRestService() ) );
	factory.setAddress( factory.getAddress() );
	factory.setProviders( Arrays.< Object >asList( jsonProvider() ) );
	return factory.create();
}
 
Example #30
Source File: ClientTestBase.java    From incubator-batchee with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public static void startServer() throws IOException {
    mockServer = new FeaturedHttpServerBuilder().port(-1).observer(new RequestObserver() {
        @Override
        public void onRequest(final FullHttpRequest request) {
            if (request.getUri().endsWith("start/simple")) {
                final String actual = new String(request.content().array());
                assertEquals(actual, "{\"entries\":[{\"key\":\"a\",\"value\":\"b\"}]}");
            }
        }
    }).build().start();
    port = mockServer.getPort();
    RuntimeDelegate.setInstance(null); // reset
}