javax.ws.rs.core.Application源码实例Demo

类javax.ws.rs.core.Application源码实例Demo

下面列出了javax.ws.rs.core.Application 类实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: jitsi-videobridge   文件: DebugTest.java
@Override
protected Application configure()
{
    videobridgeProvider = mock(VideobridgeProvider.class);
    videobridge = mock(Videobridge.class);
    when(videobridgeProvider.get()).thenReturn(videobridge);

    Endpoint endpoint = mock(Endpoint.class);
    Conference conference = mock(Conference.class);
    when(videobridge.getConference("foo")).thenReturn(conference);
    when(conference.getEndpoint("bar")).thenReturn(endpoint);

    enable(TestProperties.LOG_TRAFFIC);
    enable(TestProperties.DUMP_ENTITY);
    return new ResourceConfig() {
        {
            register(new MockBinder<>(videobridgeProvider, VideobridgeProvider.class));
            register(Debug.class);
        }
    };
}
 
源代码2 项目: camunda-bpm-platform   文件: CXFServerBootstrap.java
private void separateProvidersAndResources(Application application, List<Class<?>> resourceClasses, List<Object> providerInstances) {
  Set<Class<?>> classes = application.getClasses();

  for (Class<?> clazz : classes) {
    Annotation[] annotations = clazz.getAnnotations();
    for (Annotation annotation : annotations) {
      if (annotation.annotationType().equals(Provider.class)) {
        // for providers we have to create an instance
        try {
          providerInstances.add(clazz.newInstance());
          break;
        } catch (Exception e) {
          throw new RuntimeException(e);
        }
      } else if (annotation.annotationType().equals(Path.class)) {
        resourceClasses.add(clazz);
        break;
      }
    }
  }
}
 
public CxfJaxrsServiceRegistrator(
    Bus bus, ServiceTuple<Application> applicationTuple,
    Map<String, ?> properties,
    AriesJaxrsServiceRuntime ariesJaxrsServiceRuntime) {

    _bus = bus;
    _applicationTuple = applicationTuple;
    _properties = Collections.unmodifiableMap(new HashMap<>(properties));
    _ariesJaxrsServiceRuntime = ariesJaxrsServiceRuntime;

    Comparator<ServiceTuple<?>> comparing = Comparator.comparing(
        ServiceTuple::getCachingServiceReference);

    _providers = new TreeSet<>(comparing);
    _erroredProviders = new ArrayList<>();
    _erroredServices = new ArrayList<>();
    _serviceReferenceRegistry = new ServiceReferenceRegistry();
}
 
@Test
public void jaxRsAsync() {
    expected.expect(IllegalArgumentException.class);
    expected.expectMessage(allOf(
            containsString("suspended("),
            containsString("sse("),
            containsString("managed()"),
            containsString("cf()")));

    new HttpJerseyRouterBuilder()
            .routeExecutionStrategyFactory(asFactory(
                    singletonMap("test", defaultStrategy(TEST_EXEC.executor()))))
            .buildStreaming(new Application() {
                @Override
                public Set<Class<?>> getClasses() {
                    return singleton(ResourceUnsupportedAsync.class);
                }
            });
}
 
源代码5 项目: sinavi-jfw   文件: LocaleContextFilterTest.java
@Override
protected Application configure() {
    enable(TestProperties.LOG_TRAFFIC);
    ResourceConfig config = new ResourceConfig();
    config.register(LocaleContextFilter.class, 1);
    config.register(new ContainerRequestFilter() {

        @Override
        public void filter(ContainerRequestContext requestContext) throws IOException {
            called.incrementAndGet();
            locale = LocaleContextKeeper.getLocale();
        }

    }, 2);
    config.register(TestResource.class);
    return config;
}
 
源代码6 项目: everrest   文件: AsynchronousRequestTest.java
@Test
public void startsAsynchronousJob() throws Exception {
    processor.addApplication(new Application() {
        @Override
        public Set<Class<?>> getClasses() {
            return newHashSet(Resource1.class);
        }
    });
    String jobUrl = startAsynchronousJobAndGetItsUrl("/a", "GET", null, null, null);

    ByteArrayContainerResponseWriter writer = new ByteArrayContainerResponseWriter();
    ContainerResponse response = getAsynchronousResponse(jobUrl, writer);
    assertEquals(200, response.getStatus());
    assertEquals("asynchronous response", new String(writer.getBody()));

    // Try one more time. Job must be removed from pool so expected result is 404.
    response = launcher.service("GET", jobUrl, "", null, null, null);
    assertEquals(404, response.getStatus());
}
 
源代码7 项目: cxf   文件: AbstractResourceInfo.java
private void findContextFields(Class<?> cls, Object provider) {
    if (cls == Object.class || cls == null) {
        return;
    }
    for (Field f : ReflectionUtil.getDeclaredFields(cls)) {
        for (Annotation a : f.getAnnotations()) {
            if (a.annotationType() == Context.class
                && (f.getType().isInterface() || f.getType() == Application.class)) {
                contextFields = addContextField(contextFields, f);
                checkContextClass(f.getType());
                if (!InjectionUtils.VALUE_CONTEXTS.contains(f.getType().getName())) {
                    addToMap(getFieldProxyMap(true), f, getFieldThreadLocalProxy(f, provider));
                }
            }
        }
    }
    findContextFields(cls.getSuperclass(), provider);
}
 
源代码8 项目: cxf   文件: JAXRSServerFactoryBean.java
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);
    }
}
 
源代码9 项目: cxf   文件: DOM4JProviderTest.java
private Message createMessage(ProviderFactory factory) {
    Message m = new MessageImpl();
    m.put("org.apache.cxf.http.case_insensitive_queries", false);
    Exchange e = new ExchangeImpl();
    m.setExchange(e);
    e.setInMessage(m);
    Endpoint endpoint = EasyMock.createMock(Endpoint.class);
    endpoint.getEndpointInfo();
    EasyMock.expectLastCall().andReturn(null).anyTimes();
    endpoint.get(Application.class.getName());
    EasyMock.expectLastCall().andReturn(null);
    endpoint.size();
    EasyMock.expectLastCall().andReturn(0).anyTimes();
    endpoint.isEmpty();
    EasyMock.expectLastCall().andReturn(true).anyTimes();
    endpoint.get(ServerProviderFactory.class.getName());
    EasyMock.expectLastCall().andReturn(factory).anyTimes();
    EasyMock.replay(endpoint);
    e.put(Endpoint.class, endpoint);
    return m;
}
 
源代码10 项目: jitsi-videobridge   文件: MucClientTest.java
@Override
protected Application configure()
{
    clientConnectionProvider = mock(ClientConnectionProvider.class);
    clientConnection = mock(ClientConnectionImpl.class);
    when(clientConnectionProvider.get()).thenReturn(clientConnection);

    enable(TestProperties.LOG_TRAFFIC);
    enable(TestProperties.DUMP_ENTITY);
    return new ResourceConfig() {
        {
            register(new MockBinder<>(clientConnectionProvider, ClientConnectionProvider.class));
            register(MucClient.class);
        }
    };
}
 
源代码11 项目: mrgeo   文件: ColorScaleResourceTest.java
@Override
protected Application configure()
{
  service = Mockito.mock(MrsPyramidService.class);

  ResourceConfig config = new ResourceConfig();
  config.register(ColorScaleResource.class);
  config.register(new AbstractBinder()
  {
    @Override
    protected void configure()
    {
      bind(service).to(MrsPyramidService.class);
    }
  });
  return config;
}
 
源代码12 项目: everrest   文件: AsynchronousRequestTest.java
@Test
public void providesListOfAsynchronousJobsAsJson() throws Exception {
    processor.addApplication(new Application() {
        @Override
        public Set<Class<?>> getClasses() {
            return newHashSet(Resource1.class);
        }
    });
    startAsynchronousJobAndGetItsUrl("/a", "GET", null, null, null);

    MultivaluedMap<String, String> headers = new MultivaluedMapImpl();
    headers.putSingle("accept", "application/json");
    ContainerResponse response = launcher.service("GET", "/async", "", headers, null, null, null);

    assertEquals(200, response.getStatus());
    assertEquals("application/json", response.getContentType().toString());

    Collection<AsynchronousProcess> processes = (Collection<AsynchronousProcess>)response.getEntity();

    assertEquals(1, processes.size());
    AsynchronousProcess process = processes.iterator().next();
    assertNull(process.getOwner());
    assertEquals("running", process.getStatus());
    assertEquals("/a", process.getPath());
}
 
源代码13 项目: aries-jax-rs-whiteboard   文件: TestHelper.java
protected ServiceRegistration<Application> registerApplication(
    Application application, Object... keyValues) {

    Dictionary<String, Object> properties = new Hashtable<>();

    for (int i = 0; i < keyValues.length; i = i + 2) {
        properties.put(keyValues[i].toString(), keyValues[i + 1]);
    }

    if (properties.get(JAX_RS_APPLICATION_BASE) == null) {
        properties.put(JAX_RS_APPLICATION_BASE, "/test-application");
    }

    ServiceRegistration<Application> serviceRegistration =
        bundleContext.registerService(
            Application.class, application, properties);

    _registrations.add(serviceRegistration);

    return serviceRegistration;
}
 
源代码14 项目: logbook   文件: ClientAndServerWithoutBodyTest.java
@Override
protected Application configure() {
    // jersey calls this method within the constructor before our fields are initialized... WTF
    this.client = mock(Sink.class);
    this.server = mock(Sink.class);

    return new ResourceConfig(TestWebService.class)
            .register(new LogbookServerFilter(
                    Logbook.builder()
                            // do not replace multi-part form bodies, which is the default
                            .requestFilter(replaceBody(stream()))
                            .strategy(new WithoutBodyStrategy())
                            .sink(server)
                            .build()))
            .register(MultiPartFeature.class);
}
 
源代码15 项目: camunda-bpm-platform   文件: CXFServerBootstrap.java
private void setupServer(Application application) {
  jaxrsServerFactoryBean = new JAXRSServerFactoryBean();
  List<Class<?>> resourceClasses = new ArrayList<Class<?>>();
  List<Object> providerInstances = new ArrayList<Object>();

  // separate the providers and resources from the application returned classes
  separateProvidersAndResources(application, resourceClasses, providerInstances);
  jaxrsServerFactoryBean.setResourceClasses(resourceClasses);
  jaxrsServerFactoryBean.setProviders(providerInstances);

  // set up address
  Properties serverProperties = readProperties();
  propertyPort = serverProperties.getProperty(PORT_PROPERTY);
  jaxrsServerFactoryBean.setAddress("http://localhost:" + propertyPort + ROOT_RESOURCE_PATH);

  // set start to false so create call does not start server
  jaxrsServerFactoryBean.setStart(false);
  server = jaxrsServerFactoryBean.create();
}
 
源代码16 项目: everrest   文件: OPTIONSMethodTest.java
@Test
public void whenOPTIONSMethodIsNotAvailableThenWADLResponseIsProvided() throws Exception {
    processor.addApplication(new Application() {
        @Override
        public Set<Object> getSingletons() {
            return newHashSet(new Resource_without_OPTIONS_method());
        }
    });

    ContainerResponse response = launcher.service("OPTIONS", "/b", "", null, null, null);

    assertEquals(200, response.getStatus());
    assertEquals(new MediaType("application", "vnd.sun.wadl+xml"), response.getContentType());
    assertNotNull(response.getResponse().getEntity());
}
 
@Override
protected Application configure() {
  return new ResourceConfig() {
    {
      register(new PipelineStoreResourceConfig());
      register(PipelineStoreResource.class);
      register(MultiPartFeature.class);
    }
  };
}
 
源代码18 项目: everrest   文件: MethodReturnTypeTest.java
@Before
@Override
public void setUp() throws Exception {
    super.setUp();
    processor.addApplication(new Application() {
        @Override
        public Set<Object> getSingletons() {
            return newHashSet(new Resource());
        }
    });
}
 
源代码19 项目: everrest   文件: AcceptResourceTest.java
@Override
@Before
public void setUp() throws Exception {
    super.setUp();
    processor.addApplication(new Application() {
        @Override
        public Set<Object> getSingletons() {
            return newHashSet(new Resource2());
        }
    });
}
 
/**
 * Private constructor for a LambdaContainer. Sets the application object, sets the ApplicationHandler,
 * and initializes the application using the <code>onStartup</code> method.
 * @param requestTypeClass The class for the expected event type
 * @param responseTypeClass The class for the output type
 * @param requestReader A request reader instance
 * @param responseWriter A response writer instance
 * @param securityContextWriter A security context writer object
 * @param exceptionHandler An exception handler
 * @param jaxRsApplication The JaxRs application
 */
public JerseyLambdaContainerHandler(Class<RequestType> requestTypeClass,
                                    Class<ResponseType> responseTypeClass,
                                    RequestReader<RequestType, HttpServletRequest> requestReader,
                                    ResponseWriter<AwsHttpServletResponse, ResponseType> responseWriter,
                                    SecurityContextWriter<RequestType> securityContextWriter,
                                    ExceptionHandler<ResponseType> exceptionHandler,
                                    Application jaxRsApplication) {

    super(requestTypeClass, responseTypeClass, requestReader, responseWriter, securityContextWriter, exceptionHandler);
    Timer.start("JERSEY_CONTAINER_CONSTRUCTOR");
    initialized = false;
    if (jaxRsApplication instanceof ResourceConfig) {
        ((ResourceConfig)jaxRsApplication).register(new AbstractBinder() {
            @Override
            protected void configure() {
                bindFactory(AwsProxyServletContextSupplier.class)
                        .proxy(true)
                        .proxyForSameScope(true)
                        .to(ServletContext.class)
                        .in(RequestScoped.class);
                bindFactory(AwsProxyServletRequestSupplier.class)
                        .proxy(true)
                        .proxyForSameScope(true)
                        .to(HttpServletRequest.class)
                        .in(RequestScoped.class);
                bindFactory(AwsProxyServletResponseSupplier.class)
                        .proxy(true)
                        .proxyForSameScope(true)
                        .to(HttpServletResponse.class)
                        .in(RequestScoped.class);
            }
        });
    }

    this.jerseyFilter = new JerseyHandlerFilter(jaxRsApplication);
    Timer.stop("JERSEY_CONTAINER_CONSTRUCTOR");
}
 
源代码21 项目: everrest   文件: ApplicationPublisherTest.java
@Test
public void publishesSingletonMessageBodyReader() {
    MessageBodyReader<String> messageBodyReader = new StringEntityProvider();
    Application application = mock(Application.class);
    when(application.getSingletons()).thenReturn(newHashSet(messageBodyReader));

    publisher.publish(application);

    verify(providers).addMessageBodyReader(messageBodyReader);
}
 
@Override
protected Application application(@Nullable final Key<BasicUserInfo> userInfoKey) {
    return new ResourceConfig(RoleProtectedResource.class)
            .register(RolesAllowedDynamicFeature.class)
            .registerInstances(userInfoKey != null ?
                    BasicAuthSecurityContextFilters.forGlobalBinding(userInfoKey)
                            .securityContextFunction((__, userInfo) ->
                                    new BasicAuthSecurityContext(new BasicAuthPrincipal<>(userInfo), false,
                                            role -> userInfo.roles().contains(role)))
                            .build() :
                    BasicAuthSecurityContextFilters.forGlobalBinding()
                            .securityContextFunction(__ ->
                                    new BasicAuthSecurityContext(() -> "N/A", false, "USER"::equals))
                            .build());
}
 
源代码23 项目: Graphene   文件: GrapheneRESTServerTest.java
@Override
protected Application configure() {

	Config config = ConfigFactory
               .load("application-server.local")
               .resolveWith(ConfigFactory.load())
               .withFallback(ConfigFactory.load("reference"));
       Graphene graphene = new Graphene(config);

	return GrapheneRESTServer.generateResourceConfig(config, graphene);
}
 
DefaultJerseyStreamingHttpRouter(final Application application,
                                 final int publisherInputStreamQueueCapacity,
                                 final BiFunction<ConnectionContext, HttpRequestMetaData, String> baseUriFunction,
                                 final RouteExecutionStrategyFactory<HttpExecutionStrategy> strategyFactory) {
    this(new ApplicationHandler(application), publisherInputStreamQueueCapacity, baseUriFunction,
            strategyFactory);
}
 
DefaultJerseyStreamingHttpRouter(final Class<? extends Application> applicationClass,
                                 final int publisherInputStreamQueueCapacity,
                                 final BiFunction<ConnectionContext, HttpRequestMetaData, String> baseUriFunction,
                                 final RouteExecutionStrategyFactory<HttpExecutionStrategy> strategyFactory) {
    this(new ApplicationHandler(applicationClass), publisherInputStreamQueueCapacity, baseUriFunction,
            strategyFactory);
}
 
源代码26 项目: aries-jax-rs-whiteboard   文件: Whiteboard.java
private OSGi<ServiceRegistration<Application>>
    registerDefaultApplication() {

    return OSGi.register(
        Application.class, DefaultApplication::new,
        () -> {
            Object defaultApplicationBase = _configurationMap.get(
                "default.application.base");

            if (defaultApplicationBase == null ||
                !(defaultApplicationBase instanceof String)) {

                defaultApplicationBase = "/";
            }

            Map<String, Object> properties = new HashMap<>();

            mergePropertyMaps(properties, _configurationMap);

            properties.put(JAX_RS_NAME, DEFAULT_NAME);
            properties.put(JAX_RS_APPLICATION_BASE, defaultApplicationBase);
            properties.put("service.ranking", Integer.MIN_VALUE);
            properties.put(
                JAX_RS_WHITEBOARD_TARGET,
                "(" + SERVICE_PID + "=" + _configurationMap.get(SERVICE_PID)
                    + ")");

            return properties;
        });
}
 
源代码27 项目: tomee   文件: CdiInterceptorContextTest.java
@Module
@Classes(value = {Endpoint.class, AnswerPerfect.class}, cdiInterceptors = AnswerPerfect.class)
public WebApp war() {
    return new WebApp()
        .contextRoot("app")
        .addServlet("REST Application", Application.class.getName())
        .addInitParam("REST Application", "javax.ws.rs.Application", PerfectApplication.class.getName());
}
 
源代码28 项目: everrest   文件: MethodParametersInjectionTest.java
@Test
public void injectsUriInfo() throws Exception {
    processor.addApplication(new Application() {
        @Override
        public Set<Object> getSingletons() {
            return newHashSet(new ContextParamResource());
        }
    });
    ContainerResponse response = launcher.service("POST", "/g/1", "", null, null, null);

    assertTrue(String.format("Expected %s injected", UriInfo.class), response.getEntity() instanceof UriInfo);
}
 
/**
 * Construct a new instance with an application descriptor that defines
 * how the test container is configured.
 *
 * @param jaxrsApplication an application describing how to configure the
 *                         test container.
 * @throws TestContainerException if the default test container factory
 *                                cannot be obtained, or the application descriptor is not
 *                                supported by the test container factory.
 */
public SpringContextJerseyTest(Application jaxrsApplication) throws TestContainerException {
    ResourceConfig config = getResourceConfig(jaxrsApplication);
    config.register(new ServiceFinderBinder<TestContainerFactory>(TestContainerFactory.class, null, RuntimeType.SERVER));
    if (isLogRecordingEnabled()) {
        registerLogHandler();
    }
    this.application = new ApplicationHandler(config);
    this.tc = getContainer(application, getTestContainerFactory());
    if (isLogRecordingEnabled()) {
        loggedStartupRecords.addAll(loggedRuntimeRecords);
        loggedRuntimeRecords.clear();
        unregisterLogHandler();
    }
}
 
源代码30 项目: servicetalk   文件: MixedModeResourceTest.java
@Override
protected Application application() {
    return new Application() {
        @Override
        public Set<Class<?>> getClasses() {
            return singleton(MixedModeResources.class);
        }
    };
}