javax.ws.rs.core.Application Java Examples

The following examples show how to use javax.ws.rs.core.Application. 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: CXFServerBootstrap.java    From camunda-bpm-platform with Apache License 2.0 6 votes vote down vote up
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();
}
 
Example #2
Source File: CXFServerBootstrap.java    From camunda-bpm-platform with Apache License 2.0 6 votes vote down vote up
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;
      }
    }
  }
}
 
Example #3
Source File: DebugTest.java    From jitsi-videobridge with Apache License 2.0 6 votes vote down vote up
@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);
        }
    };
}
 
Example #4
Source File: CxfJaxrsServiceRegistrator.java    From aries-jax-rs-whiteboard with Apache License 2.0 6 votes vote down vote up
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();
}
 
Example #5
Source File: ExecutionStrategyConfigurationFailuresTest.java    From servicetalk with Apache License 2.0 6 votes vote down vote up
@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);
                }
            });
}
 
Example #6
Source File: LocaleContextFilterTest.java    From sinavi-jfw with Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example #7
Source File: AsynchronousRequestTest.java    From everrest with Eclipse Public License 2.0 6 votes vote down vote up
@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());
}
 
Example #8
Source File: AbstractResourceInfo.java    From cxf with Apache License 2.0 6 votes vote down vote up
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);
}
 
Example #9
Source File: JAXRSServerFactoryBean.java    From cxf with Apache License 2.0 6 votes vote down vote up
protected void injectContexts(ServerProviderFactory factory, ApplicationInfo fallback) {
    // Sometimes the application provider (ApplicationInfo) is injected through
    // the endpoint, not JAXRSServerFactoryBean (like for example OpenApiFeature
    // or Swagger2Feature do). As such, without consulting the endpoint, the injection
    // may not work properly.
    final ApplicationInfo appInfoProvider = (appProvider == null) ? fallback : appProvider;
    final Application application = appInfoProvider == null ? null : appInfoProvider.getProvider();

    for (ClassResourceInfo cri : serviceFactory.getClassResourceInfo()) {
        if (cri.isSingleton()) {
            InjectionUtils.injectContextProxiesAndApplication(cri,
                                                cri.getResourceProvider().getInstance(null),
                                                application,
                                                factory);
        }
    }
    if (application != null) {
        InjectionUtils.injectContextProxiesAndApplication(appInfoProvider,
                                                          application, null, null);
    }
}
 
Example #10
Source File: DOM4JProviderTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #11
Source File: MucClientTest.java    From jitsi-videobridge with Apache License 2.0 6 votes vote down vote up
@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);
        }
    };
}
 
Example #12
Source File: ColorScaleResourceTest.java    From mrgeo with Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example #13
Source File: AsynchronousRequestTest.java    From everrest with Eclipse Public License 2.0 6 votes vote down vote up
@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());
}
 
Example #14
Source File: TestHelper.java    From aries-jax-rs-whiteboard with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #15
Source File: ClientAndServerWithoutBodyTest.java    From logbook with MIT License 6 votes vote down vote up
@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);
}
 
Example #16
Source File: TestPipelineStoreResourceForSlaveMode.java    From datacollector with Apache License 2.0 5 votes vote down vote up
@Override
protected Application configure() {
  return new ResourceConfig() {
    {
      register(new PipelineStoreResourceConfig());
      register(PipelineStoreResource.class);
      register(MultiPartFeature.class);
    }
  };
}
 
Example #17
Source File: ApplicationPathFilterIntTest.java    From jrestless with Apache License 2.0 5 votes vote down vote up
@Override
protected Application configure() {
	ResourceConfig application = new ApiResourceConfig();
	application.register(TestResource.class);
	application.register(ApplicationPathFilter.class);
	return application;
}
 
Example #18
Source File: CXFNonSpringJaxrsServlet.java    From JaxRSProviders with Apache License 2.0 5 votes vote down vote up
protected boolean isAppResourceLifecycleASingleton(Application app, ServletConfig servletConfig) {
    String scope = servletConfig.getInitParameter(SERVICE_SCOPE_PARAM);
    if (scope == null) {
        scope = (String)app.getProperties().get(SERVICE_SCOPE_PARAM);
    }
    return SERVICE_SCOPE_SINGLETON.equals(scope);
}
 
Example #19
Source File: JAXRSCdiResourceExtension.java    From cxf with 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 #20
Source File: CxfRsHttpListener.java    From tomee with Apache License 2.0 5 votes vote down vote up
private boolean applicationProvidesResources(final Application application) {
    try {
        if (application == null) {
            return false;
        }
        if (InternalApplication.class.isInstance(application) && (InternalApplication.class.cast(application).getOriginal() == null)) {
            return false;
        }
        return !application.getClasses().isEmpty() || !application.getSingletons().isEmpty();
    } catch (final Exception e) {
        return false;
    }
}
 
Example #21
Source File: AcceptResourceTest.java    From everrest with Eclipse Public License 2.0 5 votes vote down vote up
@Override
@Before
public void setUp() throws Exception {
    super.setUp();
    processor.addApplication(new Application() {
        @Override
        public Set<Object> getSingletons() {
            return newHashSet(new Resource2());
        }
    });
}
 
Example #22
Source File: JerseyLambdaContainerHandler.java    From aws-serverless-java-container with Apache License 2.0 5 votes vote down vote up
/**
 * 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");
}
 
Example #23
Source File: GrapheneRESTServerTest.java    From Graphene with GNU General Public License v3.0 5 votes vote down vote up
@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);
}
 
Example #24
Source File: MCRRestAPIObjectsHelper.java    From mycore with GNU General Public License v3.0 5 votes vote down vote up
public static Response showMCRDerivate(String pathParamMcrID, String pathParamDerID, UriInfo info, Application app,
    boolean withDetails) throws MCRRestAPIException {

    MCRObjectID mcrObj = MCRObjectID.getInstance(pathParamMcrID);
    MCRDerivate derObj = retrieveMCRDerivate(mcrObj, pathParamDerID);

    try {
        Document doc = derObj.createXML();
        if (withDetails) {
            Document docContent = listDerivateContentAsXML(derObj, "/", -1, info, app);
            if (docContent != null && docContent.hasRootElement()) {
                doc.getRootElement().addContent(docContent.getRootElement().detach());
            }
        }

        StringWriter sw = new StringWriter();
        XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat());
        outputter.output(doc, sw);

        return Response.ok(sw.toString())
            .type("application/xml")
            .build();
    } catch (IOException e) {
        throw new MCRRestAPIException(Response.Status.INTERNAL_SERVER_ERROR,
            new MCRRestAPIError(MCRRestAPIError.CODE_INTERNAL_ERROR, GENERAL_ERROR_MSG, e.getMessage()));
    }

    // return MCRRestAPIError.create(Response.Status.INTERNAL_SERVER_ERROR, "Unexepected program flow termination.",
    //       "Please contact a developer!").createHttpResponse();
}
 
Example #25
Source File: ConstructorParametersInjectionTest.java    From everrest with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void injectsRequest() throws Exception {
    processor.addApplication(new Application() {
        @Override
        public Set<Class<?>> getClasses() {
            return newHashSet(RequestResource.class);
        }
    });
    ContainerResponse response = launcher.service("POST", "/g/1", "", null, null, null);

    assertTrue(String.format("Expected %s injected", Request.class), response.getEntity() instanceof Request);
}
 
Example #26
Source File: EndpointTestBase.java    From emissary with Apache License 2.0 5 votes vote down vote up
@Override
protected Application configure() {
    new UnitTest().setupSystemProperties();
    // Tells Jersey to use first available port, fixes address already in use exception
    forceSet(TestProperties.CONTAINER_PORT, "0");
    final ResourceConfig application = new ResourceConfig();
    application.register(MultiPartFeature.class);
    application.property(MustacheMvcFeature.TEMPLATE_BASE_PATH, "/templates");
    application.register(MustacheMvcFeature.class).packages("emissary.server.mvc");
    application.register(MustacheMvcFeature.class).packages("emissary.server.api");

    return application;
}
 
Example #27
Source File: FruitResourceIntegrationTest.java    From tutorials with MIT License 5 votes vote down vote up
@Override
protected Application configure() {
    enable(TestProperties.LOG_TRAFFIC);
    enable(TestProperties.DUMP_ENTITY);
    forceSet(TestProperties.CONTAINER_PORT, "0");

    ViewApplicationConfig config = new ViewApplicationConfig();
    config.register(FruitExceptionMapper.class);
    return config;
}
 
Example #28
Source File: ApplicationPublisherTest.java    From everrest with Eclipse Public License 2.0 5 votes vote down vote up
@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);
}
 
Example #29
Source File: SwaggerJsonBareService.java    From SciGraph with Apache License 2.0 5 votes vote down vote up
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("/swagger")
@ApiOperation(value = "The swagger definition in JSON", hidden = true)
public Response getListingJsonBare(
        @Context Application app,
        @Context ServletConfig sc,
        @Context HttpHeaders headers,
        @Context UriInfo uriInfo,
        @Context ResourceContext rc) {
    ApiListingResource apiListingResource = rc.getResource(ApiListingResource.class);
    return apiListingResource.getListingJson(app, sc, headers, uriInfo);
}
 
Example #30
Source File: MultipartTest.java    From everrest with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testInputMultipartFormMap() throws Exception {
    Map<String, InputItem> expected =
            ImmutableMap.of("xml-file", createInputItem("xml-file", "foo.xml", TEXT_XML_TYPE, XML_DATA),
                            "json-file", createInputItem("json-file", "foo.json", APPLICATION_JSON_TYPE, JSON_DATA),
                            "field", createInputItem("field", null, null, TEXT_DATA));

    processor.addApplication(new Application() {
        @Override
        public Set<Object> getSingletons() {
            return Collections.<Object>singleton(new Resource3(expected));
        }
    });
    doPost("/3");
}