Java Code Examples for org.glassfish.jersey.server.ResourceConfig#register()

The following examples show how to use org.glassfish.jersey.server.ResourceConfig#register() . 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: JettyServerProvider.java    From browserup-proxy with Apache License 2.0 8 votes vote down vote up
@Inject
public JettyServerProvider(@Named("port") int port, @Named("address") String address, MitmProxyManager proxyManager) throws UnknownHostException {
    OpenApiResource openApiResource = new OpenApiResource();
    openApiResource.setConfigLocation(SWAGGER_CONFIG_NAME);

    ResourceConfig resourceConfig = new ResourceConfig();
    resourceConfig.packages(SWAGGER_PACKAGE);
    resourceConfig.register(openApiResource);
    resourceConfig.register(proxyManagerToHkBinder(proxyManager));
    resourceConfig.register(JacksonFeature.class);
    resourceConfig.register(ConstraintViolationExceptionMapper.class);
    resourceConfig.registerClasses(LoggingFilter.class);

    resourceConfig.property(ServerProperties.BV_SEND_ERROR_IN_RESPONSE, true);
    resourceConfig.property(ServerProperties.WADL_FEATURE_DISABLE, true);

    ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
    context.setContextPath("/");

    context.addFilter(GuiceFilter.class, "/*", EnumSet.of(DispatcherType.REQUEST));;
    context.addServlet(DefaultServlet.class, "/");
    context.addServlet(new ServletHolder(new ServletContainer(resourceConfig)), "/*");

    server = new Server(new InetSocketAddress(InetAddress.getByName(address), port));
    server.setHandler(context);
}
 
Example 2
Source File: CubeResourceGeneralTest.java    From cubedb with GNU General Public License v3.0 6 votes vote down vote up
@Before
public void setup() throws Exception {
  //create ResourceConfig from Resource class
  ResourceConfig rc = new ResourceConfig();
  cube = new MultiCubeImpl(null);
  rc.registerInstances(new CubeResource(cube));
  rc.register(JsonIteratorConverter.class);

  //create the Grizzly server instance
  httpServer = GrizzlyHttpServerFactory.createHttpServer(baseUri, rc);
  //start the server
  httpServer.start();

  //configure client with the base URI path
  Client client = ClientBuilder.newClient();
  client.register(JsonIteratorConverter.class);
  webTarget = client.target(baseUri);
}
 
Example 3
Source File: WebDAVNoBaseUrlTest.java    From trellis with Apache License 2.0 6 votes vote down vote up
@Override
public Application configure() {

    initMocks(this);

    final ResourceConfig config = new ResourceConfig();

    config.register(new DebugExceptionMapper());
    config.register(new TestAuthnFilter("testUser", ""));
    config.register(new TrellisWebDAVRequestFilter());
    config.register(new TrellisWebDAVResponseFilter());
    config.register(new TrellisWebDAV(mockBundler));
    config.register(new TrellisHttpResource(mockBundler));
    config.register(new AbstractBinder() {
        @Override
        protected void configure() {
            bind(mockBundler).to(ServiceBundler.class);
        }
    });
    return config;
}
 
Example 4
Source File: TileMapServiceResourceIntegrationTest.java    From mrgeo with Apache License 2.0 6 votes vote down vote up
@Override
protected Application configure()
{
  service = Mockito.mock(TmsService.class);
  request = Mockito.mock(HttpServletRequest.class);

  ResourceConfig config = new ResourceConfig();
  config.register(TileMapServiceResource.class);
  config.register(new AbstractBinder()
  {
    @Override
    protected void configure()
    {
      bind(service).to(TmsService.class);
    }
  });
  config.register(new AbstractBinder()
  {
    @Override
    protected void configure()
    {
      bind(request).to(HttpServletRequest.class);
    }
  });
  return config;
}
 
Example 5
Source File: TrellisHttpResourceNoAgentTest.java    From trellis with Apache License 2.0 6 votes vote down vote up
@Override
protected Application configure() {

    // Junit runner doesn't seem to work very well with JerseyTest
    initMocks(this);

    System.setProperty(WebSubHeaderFilter.CONFIG_HTTP_WEB_SUB_HUB, HUB);

    final String baseUri = getBaseUri().toString();

    final ResourceConfig config = new ResourceConfig();
    config.register(new TrellisHttpResource(mockBundler, singletonMap(ACL, PreferAccessControl), baseUri));
    config.register(new CacheControlFilter());
    config.register(new WebSubHeaderFilter());
    config.register(new TrellisHttpFilter());
    return config;
}
 
Example 6
Source File: WmsGeneratorTestAbstract.java    From mrgeo with Apache License 2.0 5 votes vote down vote up
@Override
protected Application configure()
{
  ResourceConfig config = new ResourceConfig();
  config.register(WmsGenerator.class);
  return config;
}
 
Example 7
Source File: EmbeddedHttpServer.java    From cantor with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
Server createServer(final int port, final String basePath) {
    final ResourceConfig config = new SwaggerJaxrsConfig();

    // bind resources with required constructor parameters
    final Cantor cantor = getCantorOnMysql();
    config.register(new AbstractBinder() {
        @Override
        protected void configure() {
            bind(new EventsResource(cantor));
            bind(new ObjectsResource(cantor));
            bind(new SetsResource(cantor));
            bind(new FunctionsResource(cantor));
        }
    });

    final Server server = new Server(port);

    // load jersey servlets
    final ServletHolder jerseyServlet = new ServletHolder(new ServletContainer(config));
    final ServletContextHandler context = new ServletContextHandler(server, "/");
    context.addServlet(jerseyServlet, basePath);

    // serve static resources
    context.setResourceBase("cantor-http-server/src/main/resources/static");
    context.addServlet(DefaultServlet.class, "/");

    return server;
}
 
Example 8
Source File: ITTracingApplicationEventListener.java    From brave with Apache License 2.0 5 votes vote down vote up
@Override public void init(ServletContextHandler handler) {
  ResourceConfig config = new ResourceConfig();
  config.register(new TestResource(httpTracing));
  config.register(TracingApplicationEventListener.create(httpTracing));
  ServletHolder servlet = new ServletHolder(new ServletContainer(config));
  servlet.setAsyncSupported(true);
  handler.addServlet(servlet, "/*");
}
 
Example 9
Source File: SpringContextJerseyTest.java    From demo-restWS-spring-jersey-jpa2-hibernate with MIT License 5 votes vote down vote up
/**
 * 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();
    }
}
 
Example 10
Source File: ExecutionContainerModule.java    From flux with Apache License 2.0 5 votes vote down vote up
/**
 * Creates the Jetty server instance for the Flux Execution API endpoint.
 * @return Jetty Server instance
 */
@Named("ExecutionAPIJettyServer")
@Provides
@Singleton
Server getExecutionAPIJettyServer(@Named("Execution.Node.Api.service.port") int port,
                         @Named("ExecutionAPIResourceConfig")ResourceConfig resourceConfig,
                         @Named("Execution.Node.Api.service.acceptors") int acceptorThreads,
                         @Named("Execution.Node.Api.service.selectors") int selectorThreads,
                         @Named("Execution.Node.Api.service.workers") int maxWorkerThreads,
                         ObjectMapper objectMapper, MetricRegistry metricRegistry) throws URISyntaxException, UnknownHostException {
    JacksonJaxbJsonProvider provider = new JacksonJaxbJsonProvider();
    provider.setMapper(objectMapper);
    resourceConfig.register(provider);
    QueuedThreadPool threadPool = new QueuedThreadPool();
    threadPool.setMaxThreads(maxWorkerThreads);
    Server server = new Server(threadPool);
    ServerConnector http = new ServerConnector(server, acceptorThreads, selectorThreads);
    http.setPort(port);
    server.addConnector(http);
    ServletContextHandler context = new ServletContextHandler(server, "/*");
    ServletHolder servlet = new ServletHolder(new ServletContainer(resourceConfig));
    context.addServlet(servlet, "/*");

    final InstrumentedHandler handler = new InstrumentedHandler(metricRegistry);
    handler.setHandler(context);
    server.setHandler(handler);

    server.setStopAtShutdown(true);
    return server;
}
 
Example 11
Source File: SpringContextJerseyTest.java    From demo-restWS-spring-jersey-tomcat-mybatis with MIT License 5 votes vote down vote up
/**
 * Construct a new instance with an {@link Application} class.
 *
 * @param jaxrsApplicationClass 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(Class<? extends Application> jaxrsApplicationClass) throws TestContainerException {
    ResourceConfig config = ResourceConfig.forApplicationClass(jaxrsApplicationClass);
    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();
    }
}
 
Example 12
Source File: RequestMetricsContainerFilterTest.java    From cf-java-logging-support with Apache License 2.0 5 votes vote down vote up
@Override
protected Application configure() {
    ResourceConfig config = new ResourceConfig();
    config.register(TestResource.class);
    RequestMetricsFilterRegistry.registerContainerFilters(config);
    return config;

}
 
Example 13
Source File: EchoServer.java    From reladomo with Apache License 2.0 5 votes vote down vote up
private ResourceConfig initResources()
{
    ResourceConfig rc = new ResourceConfig();
    rc.register(EchoResource.class);
    rc.register(JacksonFeature.class);
    rc.register(JacksonObjectMapperProvider.class);
    return rc;

    /*
    ObjectMapper ob = new ObjectMapper();
    JacksonJsonProvider jc = new JacksonJsonProvider();
    jc.setMapper(ob);
    rc.register(jc);
    */
}
 
Example 14
Source File: RequestMetricsClientFilterTest.java    From cf-java-logging-support with Apache License 2.0 5 votes vote down vote up
@Override
protected Application configure() {
    ResourceConfig config = new ResourceConfig();
    config.register(TestResource.class);
    config.register(TestChainedResource.class);
    return config;

}
 
Example 15
Source File: AbstractRecommenderRestTest.java    From TeaStore with Apache License 2.0 4 votes vote down vote up
/**
 * Sets up a registry, a persistance unit and a store.
 * 
 * @throws Throwable
 *             Throws uncaught throwables for test to fail.
 */
@Before
public void setup() throws Throwable {
	persistence = new MockPersistenceProvider(persistenceWireMockRule);

	otherrecommender = new MockOtherRecommenderProvider(otherRecommenderWireMockRule);

	setRegistry(new MockRegistry(registryWireMockRule, Arrays.asList(getPersistence().getPort()),
			Arrays.asList(RECOMMENDER_TEST_PORT, otherrecommender.getPort())));

	// debuggging response
	// Response response1 = ClientBuilder
	// .newBuilder().build().target("http://localhost:" + otherrecommender.getPort()
	// + "/"
	// + Service.RECOMMENDER.getServiceName() + "/rest/train/timestamp")
	// .request(MediaType.APPLICATION_JSON).get();
	// System.out.println(response1.getStatus() + ":" +
	// response1.readEntity(String.class));

	// debuggging response
	// Response response0 = ClientBuilder.newBuilder().build()
	// .target("http://localhost:" + MockRegistry.DEFAULT_MOCK_REGISTRY_PORT
	// + "/tools.descartes.teastore.registry/rest/services/"
	// + Service.PERSISTENCE.getServiceName() + "/")
	// .request(MediaType.APPLICATION_JSON).get();
	// System.out.println(response0.getStatus() + ":" +
	// response0.readEntity(String.class));
	//
	// Response response1 = ClientBuilder.newBuilder().build()
	// .target("http://localhost:" + persistence.getPort()
	// + "/tools.descartes.teastore.persistence/rest/orderitems")
	// .request(MediaType.APPLICATION_JSON).get();
	// System.out.println(response1.getStatus() + ":" +
	// response1.readEntity(String.class));

	// Setup recommend tomcat
	testTomcat = new Tomcat();
	testTomcat.setPort(RECOMMENDER_TEST_PORT);
	testTomcat.setBaseDir(testWorkingDir);
	testTomcat.enableNaming();
	Context context = testTomcat.addWebapp("/" + Service.RECOMMENDER.getServiceName(), testWorkingDir);
	ContextEnvironment registryURL3 = new ContextEnvironment();
	registryURL3.setDescription("");
	registryURL3.setOverride(false);
	registryURL3.setType("java.lang.String");
	registryURL3.setName("registryURL");
	registryURL3.setValue(
			"http://localhost:" + registry.getPort() + "/tools.descartes.teastore.registry/rest/services/");
	context.getNamingResources().addEnvironment(registryURL3);
	ContextEnvironment servicePort3 = new ContextEnvironment();
	servicePort3.setDescription("");
	servicePort3.setOverride(false);
	servicePort3.setType("java.lang.String");
	servicePort3.setName("servicePort");
	servicePort3.setValue("" + RECOMMENDER_TEST_PORT);
	context.getNamingResources().addEnvironment(servicePort3);
	ResourceConfig restServletConfig3 = new ResourceConfig();
	restServletConfig3.register(TrainEndpoint.class);
	restServletConfig3.register(RecommendEndpoint.class);
	restServletConfig3.register(RecommendSingleEndpoint.class);
	ServletContainer restServlet3 = new ServletContainer(restServletConfig3);
	testTomcat.addServlet("/" + Service.RECOMMENDER.getServiceName(), "restServlet", restServlet3);
	context.addServletMappingDecoded("/rest/*", "restServlet");
	context.addApplicationListener(RecommenderStartup.class.getName());

	ContextEnvironment recommender = new ContextEnvironment();
	recommender.setDescription("");
	recommender.setOverride(false);
	recommender.setType("java.lang.String");
	recommender.setName("recommenderAlgorithm");
	recommender.setValue("PreprocessedSlopeOne");
	context.getNamingResources().addEnvironment(recommender);

	ContextEnvironment retrainlooptime = new ContextEnvironment();
	retrainlooptime.setDescription("");
	retrainlooptime.setOverride(false);
	retrainlooptime.setType("java.lang.Long");
	retrainlooptime.setName("recommenderLoopTime");
	retrainlooptime.setValue("100");
	context.getNamingResources().addEnvironment(retrainlooptime);

	testTomcat.start();

	try {
		Thread.sleep(5000);
	} catch (InterruptedException e) {
	}
}
 
Example 16
Source File: DremioServer.java    From dremio-oss with Apache License 2.0 4 votes vote down vote up
public void startDremioServer(
  SingletonRegistry registry,
  DACConfig config,
  Provider<ServerHealthMonitor> serverHealthMonitor,
  Provider<NodeEndpoint> endpointProvider,
  Provider<SabotContext> contextProvider,
  Provider<RestServerV2> restServerProvider,
  Provider<APIServer> apiServerProvider,
  DremioBinder dremioBinder,
  Tracer tracer,
  String uiType,
  boolean isInternalUS
) throws Exception {
  try {
    if (!embeddedJetty.isRunning()) {
      createConnector(config);
      addHandlers();
    }

    // security header filters
    servletContextHandler.addFilter(SecurityHeadersFilter.class.getName(), "/*", EnumSet.of(DispatcherType.REQUEST));

    // server tracing filter.
    servletContextHandler.addFilter(SpanFinishingFilter.class.getName(), "/*", EnumSet.of(DispatcherType.REQUEST));

    // add the font mime type.
    final MimeTypes mimeTypes = servletContextHandler.getMimeTypes();
    mimeTypes.addMimeMapping("woff2", "application/font-woff2; charset=utf-8");
    servletContextHandler.setMimeTypes(mimeTypes);

    // WebSocket API
    final SocketServlet servlet = new SocketServlet(registry.lookup(JobsService.class), registry.lookup(TokenManager.class));
    final ServletHolder wsHolder = new ServletHolder(servlet);
    wsHolder.setInitOrder(3);
    servletContextHandler.addServlet(wsHolder, "/apiv2/socket");

    // Rest API
    ResourceConfig restServer = restServerProvider.get();

    restServer.property(RestServerV2.ERROR_STACKTRACE_ENABLE, config.sendStackTraceToClient);
    restServer.property(RestServerV2.TEST_API_ENABLE, config.allowTestApis);
    restServer.property(RestServerV2.FIRST_TIME_API_ENABLE, isInternalUS);

    restServer.register(dremioBinder);
    restServer.register(new ServerTracingDynamicFeature(tracer));

    final ServletHolder restHolder = new ServletHolder(new ServletContainer(restServer));
    restHolder.setInitOrder(2);
    servletContextHandler.addServlet(restHolder, "/apiv2/*");

    // Public API
    ResourceConfig apiServer = apiServerProvider.get();
    apiServer.register(dremioBinder);
    apiServer.register(new ServerTracingDynamicFeature(tracer));

    final ServletHolder apiHolder = new ServletHolder(new ServletContainer(apiServer));
    apiHolder.setInitOrder(3);
    servletContextHandler.addServlet(apiHolder, "/api/v3/*");

    if (config.verboseAccessLog) {
      accessLogFilter = new AccessLogFilter();
      servletContextHandler.addFilter(
        new FilterHolder(accessLogFilter),
        "/*",
        EnumSet.of(DispatcherType.REQUEST));
    }

    if (config.serveUI) {
      final String basePath = "rest/dremio_static/";
      final String markerPath = String.format("META-INF/%s.properties", uiType);

      final ServletHolder fallbackServletHolder = new ServletHolder("fallback-servlet", registry.lookup(DremioServlet.class));
      addStaticPath(fallbackServletHolder, basePath, markerPath);
      servletContextHandler.addServlet(fallbackServletHolder, "/*");

      // TODO DX-1556 - temporary static asset serving for showing Profiles
      final String baseStaticPath = "rest/static/";
      final String arrowDownResourceRelativePath = "rest/static/img/arrow-down-small.svg";
      ServletHolder restStaticHolder = new ServletHolder("static", DefaultServlet.class);
      // Get resource URL for legacy static assets, based on where some image is located
      addStaticPath(restStaticHolder, baseStaticPath, arrowDownResourceRelativePath);
      servletContextHandler.addServlet(restStaticHolder, "/static/*");
    }

    if (!embeddedJetty.isRunning()) {
      embeddedJetty.start();
    }

    setPortFromConnector();
    logger.info("Started on {}://localhost:" + port, config.webSSLEnabled() ? "https" : "http");

    serviceStarted = true;
  } catch (Exception ex) {
    throw new ServerErrorException(ex);
  }
}
 
Example 17
Source File: ApiResourceNotAuthenticatedTest.java    From gravitee-management-rest-api with Apache License 2.0 4 votes vote down vote up
@Override
protected void decorate(ResourceConfig resourceConfig) {
    resourceConfig.register(AuthenticationFilter.class);
}
 
Example 18
Source File: RestServer.java    From DataLink with Apache License 2.0 4 votes vote down vote up
public void start(Keeper keeper) {
    log.info("Starting REST server");

    ResourceConfig resourceConfig = new ResourceConfig();
    resourceConfig.packages("com.ucar.datalink.worker.core.runtime.rest.resources");
    resourceConfig.register(new FastJsonProvider());
    resourceConfig.register(RootResource.class);
    resourceConfig.register(new TasksResource(keeper));
    resourceConfig.register(RestExceptionMapper.class);
    resourceConfig.register(FlushResource.class);
    resourceConfig.register(HBaseMetaResource.class);
    resourceConfig.register(WorkerResource.class);

    ServletContainer servletContainer = new ServletContainer(resourceConfig);
    ServletHolder servletHolder = new ServletHolder(servletContainer);

    ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
    context.setContextPath("/");
    context.addServlet(servletHolder, "/*");

    String allowedOrigins = config.getString(WorkerConfig.ACCESS_CONTROL_ALLOW_ORIGIN_CONFIG);
    if (allowedOrigins != null && !allowedOrigins.trim().isEmpty()) {
        FilterHolder filterHolder = new FilterHolder(new CrossOriginFilter());
        filterHolder.setName("cross-origin");
        filterHolder.setInitParameter(CrossOriginFilter.ALLOWED_ORIGINS_PARAM, allowedOrigins);
        String allowedMethods = config.getString(WorkerConfig.ACCESS_CONTROL_ALLOW_METHODS_CONFIG);
        if (allowedMethods != null && !allowedOrigins.trim().isEmpty()) {
            filterHolder.setInitParameter(CrossOriginFilter.ALLOWED_METHODS_PARAM, allowedMethods);
        }
        context.addFilter(filterHolder, "/*", EnumSet.of(DispatcherType.REQUEST));
    }

    RequestLogHandler requestLogHandler = new RequestLogHandler();
    Slf4jRequestLog requestLog = new Slf4jRequestLog();
    requestLog.setLoggerName(RestServer.class.getCanonicalName());
    requestLog.setLogLatency(true);
    requestLogHandler.setRequestLog(requestLog);

    HandlerCollection handlers = new HandlerCollection();
    handlers.setHandlers(new Handler[]{context, new DefaultHandler(), requestLogHandler});

    /* Needed for graceful shutdown as per `setStopTimeout` documentation */
    StatisticsHandler statsHandler = new StatisticsHandler();
    statsHandler.setHandler(handlers);
    jettyServer.setHandler(statsHandler);
    jettyServer.setStopTimeout(GRACEFUL_SHUTDOWN_TIMEOUT_MS);
    jettyServer.setStopAtShutdown(true);

    try {
        jettyServer.start();
    } catch (Exception e) {
        throw new DatalinkException("Unable to start REST server", e);
    }

    log.info("REST server listening at " + jettyServer.getURI() + ", advertising URL " + advertisedUrl());
}
 
Example 19
Source File: AbstractStoreRestTest.java    From TeaStore with Apache License 2.0 4 votes vote down vote up
/**
 * Sets up a store.
 * 
 * @throws Throwable
 *           Throws uncaught throwables for test to fail.
 */
@Before
public void setup() throws Throwable {
  BasicConfigurator.configure();

  storeTomcat = new Tomcat();
  storeTomcat.setPort(3000);
  storeTomcat.setBaseDir(testWorkingDir);
  storeTomcat.enableNaming();
  ContextEnvironment registryUrl3 = new ContextEnvironment();
  registryUrl3.setDescription("");
  registryUrl3.setOverride(false);
  registryUrl3.setType("java.lang.String");
  registryUrl3.setName("registryURL");
  registryUrl3
      .setValue("http://localhost:18080/tools.descartes.teastore.registry/rest/services/");
  Context context3 = storeTomcat.addWebapp("/tools.descartes.teastore.auth", testWorkingDir);
  context3.getNamingResources().addEnvironment(registryUrl3);
  ContextEnvironment servicePort3 = new ContextEnvironment();
  servicePort3.setDescription("");
  servicePort3.setOverride(false);
  servicePort3.setType("java.lang.String");
  servicePort3.setName("servicePort");
  servicePort3.setValue("3000");
  context3.getNamingResources().addEnvironment(servicePort3);
  ResourceConfig restServletConfig3 = new ResourceConfig();
  restServletConfig3.register(AuthCartRest.class);
  restServletConfig3.register(AuthUserActionsRest.class);
  ServletContainer restServlet3 = new ServletContainer(restServletConfig3);
  storeTomcat.addServlet("/tools.descartes.teastore.auth", "restServlet", restServlet3);
  context3.addServletMappingDecoded("/rest/*", "restServlet");
  context3.addApplicationListener(EmptyAuthStartup.class.getName());

  // Mock registry
  List<String> strings = new LinkedList<String>();
  strings.add("localhost:18080");
  String json = new ObjectMapper().writeValueAsString(strings);
  List<String> strings2 = new LinkedList<String>();
  strings2.add("localhost:3000");
  String json2 = new ObjectMapper().writeValueAsString(strings2);
  wireMockRule.stubFor(get(urlEqualTo(
      "/tools.descartes.teastore.registry/rest/services/" + Service.IMAGE.getServiceName() + "/"))
          .willReturn(okJson(json)));
  wireMockRule.stubFor(get(urlEqualTo(
      "/tools.descartes.teastore.registry/rest/services/" + Service.AUTH.getServiceName() + "/"))
          .willReturn(okJson(json2)));
  wireMockRule.stubFor(
      WireMock.put(WireMock.urlMatching("/tools.descartes.teastore.registry/rest/services/"
          + Service.AUTH.getServiceName() + "/.*")).willReturn(okJson(json2)));
  wireMockRule.stubFor(
      WireMock.delete(WireMock.urlMatching("/tools.descartes.teastore.registry/rest/services/"
          + Service.AUTH.getServiceName() + "/.*")).willReturn(okJson(json2)));
  wireMockRule.stubFor(get(urlEqualTo("/tools.descartes.teastore.registry/rest/services/"
      + Service.PERSISTENCE.getServiceName() + "/")).willReturn(okJson(json)));
  wireMockRule.stubFor(get(urlEqualTo("/tools.descartes.teastore.registry/rest/services/"
      + Service.RECOMMENDER.getServiceName() + "/")).willReturn(okJson(json)));

  // Mock images
  HashMap<String, String> img = new HashMap<>();
  img.put("andreBauer", "andreBauer");
  img.put("johannesGrohmann", "johannesGrohmann");
  img.put("joakimKistowski", "joakimKistowski");
  img.put("simonEismann", "simonEismann");
  img.put("norbertSchmitt", "norbertSchmitt");
  img.put("descartesLogo", "descartesLogo");
  img.put("icon", "icon");
  mockValidPostRestCall(img, "/tools.descartes.teastore.image/rest/image/getWebImages");

  storeTomcat.start();
}
 
Example 20
Source File: MCRJerseyDefaultConfiguration.java    From mycore with GNU General Public License v3.0 2 votes vote down vote up
/**
 * Adds the binding between guice and hk2. This binding is one directional.
 * You can add guice services into hk2 (jersey) resources. You cannot add
 * a hk2 service into guice.
 * <p>
 * <a href="https://hk2.java.net/guice-bridge/">about the bridge</a>
 * </p>
 *
 * @param resourceConfig the jersey resource configuration
 */
public static void setupGuiceBridge(ResourceConfig resourceConfig) {
    LogManager.getLogger().info("Initialize hk2 - guice bridge...");
    resourceConfig.register(MCRGuiceBridgeFeature.class);
}