@Override
 protected ResourceConfig configure() {
   enable(TestProperties.LOG_TRAFFIC);
   ResourceConfig rc = new ResourceConfig(ResponseTest.class);
   rc.property(ServerProperties.LOCATION_HEADER_RELATIVE_URI_RESOLUTION_DISABLED, Boolean.TRUE);
   return rc;
 }
예제 #2
0
    @Override
    protected Application configure() {
      final ResourceConfig resourceConfig = new ResourceConfig(Resource.class);
      resourceConfig.property(ServerProperties.METAINF_SERVICES_LOOKUP_DISABLE, true);

      return resourceConfig;
    }
 @Override
 public Handler createHandler() throws ConfigurationException {
   // set up jersey servlet
   ResourceConfig config = new ResourceConfig();
   // we package everything into a runnable jar using OneJAR, which provides its own class loader.
   // as the result, Jersey classpath scanning won't work properly for now.
   // hopefully this can be fixed soon. right now we need to specify classes.
   config.register(Echo.class);
   config.register(LogService.class);
   config.register(PageService.class);
   config.register(TaskService.class);
   // binder for HK2 to inject the controller to Jersey resource instances
   config.register(
       new AbstractBinder() {
         @Override
         protected void configure() {
           bind(controller).to(Controller.class);
         }
       });
   ServletContainer container = new ServletContainer(config);
   ServletContextHandler handler = new ServletContextHandler();
   handler.setContextPath("/DownloaderPool");
   handler.addServlet(new ServletHolder(container), "/*");
   return handler;
 }
예제 #4
0
 @Override
 protected Application configure() {
   ResourceConfig resourceConfig = new ResourceConfig();
   ExampleApplicationConfiguration exampleApplicationConfiguration =
       new ExampleApplicationConfiguration();
   exampleApplicationConfiguration.setName("Ray");
   resourceConfig.registerInstances(new UrsusApplicationBinder(exampleApplicationConfiguration));
   resourceConfig.register(HelloWorldResource.class);
   return resourceConfig;
 }
예제 #5
0
 /**
  * Creates and starts a lightweight HTTP server. Uses the HTTP server bundled with Java SE.
  * Requires Java SE 6 or later.
  *
  * @return The HTTP server.
  * @throws IOException If any error occurs in the process.
  */
 private static HttpServer createHttpServer() throws IOException {
   // Configure resources that will be published in the HTTP server.
   ResourceConfig weatherForecastResourceConfig = new ResourceConfig();
   // All resources are RESTful web services located in the package
   // ie.tcd.dsg.surf.weatherforecast.service.
   weatherForecastResourceConfig.packages("ie.tcd.dsg.surf.weatherforecast.service");
   // Create the HTTP server with the previous configuration.
   // Note: The server is started automatically.
   return JdkHttpServerFactory.createHttpServer(
       getWeatherForecastURI(), weatherForecastResourceConfig);
 }
예제 #6
0
  @Override
  protected Application configure() {
    enable(TestProperties.LOG_TRAFFIC);
    enable(TestProperties.DUMP_ENTITY);

    ResourceConfig config = new ResourceConfig();
    // config.register(new FastJsonFeature()).register(FastJsonProvider.class);
    config.register(new FastJsonFeature()).register(new FastJsonProvider().setPretty(true));
    config.packages("com.alibaba.fastjson");
    return config;
  }
 @Test
 public void testEnableFor() {
   ResourceConfig rc = new ResourceConfig();
   HttpMethodOverrideFilter.enableFor(rc, HttpMethodOverrideFilter.Source.HEADER);
   assertTrue(rc.getClasses().contains(HttpMethodOverrideFilter.class));
   assertEquals(
       1,
       ((HttpMethodOverrideFilter.Source[]) rc.getProperty(ServerProperties.HTTP_METHOD_OVERRIDE))
           .length);
   assertEquals(
       HttpMethodOverrideFilter.Source.HEADER,
       ((HttpMethodOverrideFilter.Source[]) rc.getProperty(ServerProperties.HTTP_METHOD_OVERRIDE))
           [0]);
 }
예제 #8
0
    @Test
    public void testEmptyProduces() throws Exception {
      final ResourceConfig rc = new ResourceConfig(EmptyProducesTestResource.class);
      rc.property(ServerProperties.WADL_FEATURE_DISABLE, false);

      final ApplicationHandler applicationHandler = new ApplicationHandler(rc);

      final ContainerResponse containerResponse =
          applicationHandler
              .apply(
                  new ContainerRequest(
                      URI.create("/"),
                      URI.create("/application.wadl"),
                      "GET",
                      null,
                      new MapPropertiesDelegate()))
              .get();

      assertEquals(200, containerResponse.getStatus());

      ((ByteArrayInputStream) containerResponse.getEntity()).reset();

      final DocumentBuilderFactory bf = DocumentBuilderFactory.newInstance();
      bf.setNamespaceAware(true);
      bf.setValidating(false);
      if (!SaxHelper.isXdkDocumentBuilderFactory(bf)) {
        bf.setXIncludeAware(false);
      }
      final DocumentBuilder b = bf.newDocumentBuilder();
      final Document d = b.parse((InputStream) containerResponse.getEntity());
      printSource(new DOMSource(d));
      final XPath xp = XPathFactory.newInstance().newXPath();
      xp.setNamespaceContext(
          new SimpleNamespaceResolver("wadl", "http://wadl.dev.java.net/2009/02"));

      final NodeList responseElements =
          (NodeList)
              xp.evaluate(
                  "/wadl:application/wadl:resources[@path!='application.wadl']//wadl:method/wadl:response",
                  d,
                  XPathConstants.NODESET);

      for (int i = 0; i < responseElements.getLength(); i++) {
        final Node item = responseElements.item(i);

        assertEquals(0, item.getChildNodes().getLength());
        assertEquals(0, item.getAttributes().getLength());
      }
    }
예제 #9
0
 /**
  * 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 JerseyTest(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();
   }
 }
예제 #10
0
  @Override
  protected DeploymentContext configureDeployment() {
    final ResourceConfig resourceConfig = new ResourceConfig(new MyApplication().getClasses());
    resourceConfig.property(
        ServerProperties.WADL_GENERATOR_CONFIG,
        "org.glassfish.jersey.examples.extendedwadl" + ".SampleWadlGeneratorConfig");

    final Resource.Builder resourceBuilder = Resource.builder();
    resourceBuilder
        .name("resource-programmatic")
        .path("programmatic")
        .addMethod("GET")
        .handledBy(new ProgrammaticResource());
    resourceConfig.registerResources(resourceBuilder.build());
    return DeploymentContext.builder(resourceConfig).contextPath("extended-wadl-webapp").build();
  }
예제 #11
0
  @Override
  protected DeploymentContext configureDeployment() {
    reloader = new Reloader();

    return DeploymentContext.newInstance(
        ResourceConfig.forApplicationClass(MyApplication.class).register(reloader));
  }
  @Override
  protected Application configure() {
    final ResourceConfig resourceConfig = new ResourceConfig(new MyApplication().getClasses());
    resourceConfig.setProperty(
        ServerProperties.PROPERTY_WADL_GENERATOR_CONFIG,
        "org.glassfish.jersey.examples.extendedwadl" + ".SampleWadlGeneratorConfig");

    final Resource.Builder resourceBuilder = Resource.builder();
    resourceBuilder
        .name("resource-programmatic")
        .path("programmatic")
        .addMethod("GET")
        .handledBy(new ProgrammaticResource());
    resourceConfig.registerResources(resourceBuilder.build());
    return resourceConfig;
  }
예제 #13
0
 public static ResourceConfig registerHK2Services(final ResourceConfig rc) {
   rc.register(
           new AbstractBinder() {
             @Override
             protected void configure() {
               bind(BuilderHelper.link(HK2ServiceSingleton.class).in(Singleton.class).build());
             }
           })
       .register(
           new AbstractBinder() {
             @Override
             protected void configure() {
               bind(
                   BuilderHelper.link(HK2ServiceRequestScoped.class)
                       .in(RequestScoped.class)
                       .build());
             }
           })
       .register(
           new AbstractBinder() {
             @Override
             protected void configure() {
               bind(BuilderHelper.link(HK2ServicePerLookup.class).in(PerLookup.class).build());
             }
           });
   return rc;
 }
예제 #14
0
 @Test
 public void testFiltersAnnotated() throws ExecutionException, InterruptedException {
   final ResourceConfig resourceConfig =
       new ResourceConfig(
           MyServerFilter.class,
           MyClientFilter.class,
           MyServerWrongFilter.class,
           MyServerFilterWithoutConstraint.class,
           Resource.class);
   resourceConfig.registerInstances(new MyServerWrongFilter2(), new MyServerFilter2());
   ApplicationHandler handler = new ApplicationHandler(resourceConfig);
   final ContainerResponse response =
       handler.apply(RequestContextBuilder.from("/resource", "GET").build()).get();
   Assert.assertEquals("called", response.getHeaderString("MyServerFilter"));
   Assert.assertEquals("called", response.getHeaderString("MyServerFilter2"));
   Assert.assertEquals("called", response.getHeaderString("MyServerFilterWithoutConstraint"));
 }
  @Override
  public Map<String, Object> getAttributes() {
    final ResourceConfig resourceConfig;
    if (!applicationInstance.isUnsatisfied() && !applicationInstance.isAmbiguous()) {
      resourceConfig = ResourceConfig.forApplication(applicationInstance.get());
    } else {
      resourceConfig = new ResourceConfig();
    }

    if (resourceConfig.getClasses().isEmpty()) {
      resourceConfig
          .registerClasses(jerseyCdiExtension.getProviders())
          .registerClasses(jerseyCdiExtension.getResources());
    }

    final String attributeName = RESOURCE_CONFIG + SERVLET_NAME;
    return singletonMap(attributeName, resourceConfig);
  }
예제 #16
0
 @Override
 protected Application configure() {
   /* enable/disable Jersey logs to console */
   // enable(TestProperties.LOG_TRAFFIC);
   // enable(TestProperties.DUMP_ENTITY);
   // enable(TestProperties.RECORD_LOG_LEVEL);
   // set(TestProperties.RECORD_LOG_LEVEL, Level.ALL.intValue());
   ResourceConfig resourceConfig = new ResourceConfig();
   resourceConfig =
       resourceConfig.registerInstances(
           restconfImpl,
           StructuredDataToXmlProvider.INSTANCE,
           StructuredDataToJsonProvider.INSTANCE,
           XmlToCompositeNodeProvider.INSTANCE,
           JsonToCompositeNodeProvider.INSTANCE);
   resourceConfig.registerClasses(RestconfDocumentedExceptionMapper.class);
   return resourceConfig;
 }
예제 #17
0
    @Test
    public void testEnableWadl() throws ExecutionException, InterruptedException {
      final ResourceConfig rc = new ResourceConfig(WidgetsResource.class, ExtraResource.class);
      rc.property(ServerProperties.WADL_FEATURE_DISABLE, false);

      final ApplicationHandler applicationHandler = new ApplicationHandler(rc);

      final ContainerResponse containerResponse =
          applicationHandler
              .apply(
                  new ContainerRequest(
                      URI.create("/"),
                      URI.create("/application.wadl"),
                      "GET",
                      null,
                      new MapPropertiesDelegate()))
              .get();

      assertEquals(200, containerResponse.getStatus());
    }
예제 #18
0
 @POST
 public void reload(@Context Reloader r, @Context ResourceConfig rc, @Context ServerContext sc) {
   ClassLoader originalContextClassLoader = Thread.currentThread().getContextClassLoader();
   try {
     ClassLoader apiClassLoader = sc.getCommonClassLoader();
     Thread.currentThread().setContextClassLoader(apiClassLoader);
     rc.getClasses().add(org.glassfish.admin.rest.resources.StaticResource.class);
     r.reload();
   } finally {
     Thread.currentThread().setContextClassLoader(originalContextClassLoader);
   }
 }
  @Override
  protected Application configure() {
    faker = new Faker();

    final Configuration configuration;
    try {
      configuration = new Configuration(CONFIG);
    } catch (IOException | NumberFormatException e) {
      System.out.println("Properties error:");
      System.out.println(e.getMessage());
      System.exit(1);
      return null;
    }

    final AccountServiceImpl accountService;
    try {
      accountService =
          new AccountServiceImpl(
              configuration.getDbName(),
              configuration.getDbHost(),
              configuration.getDbPort(),
              configuration.getDbUsername(),
              configuration.getDbPassword());
    } catch (SQLException | IOException e) {
      e.printStackTrace();
      System.exit(1);
      return null;
    }

    final ResourceConfig config = new ResourceConfig(Session.class, Users.class);
    config.register(new AccountServiceAbstractBinder(accountService));
    final HttpServletRequest httpServletRequest = mock(HttpServletRequest.class);
    final HttpSession httpSession = mock(HttpSession.class);
    final String sessionId = faker.lorem().fixedString(15);
    Mockito.when(httpServletRequest.getSession()).thenReturn(httpSession);
    Mockito.when(httpSession.getId()).thenReturn(sessionId);

    config.register(new ServletAbstractBinder(httpServletRequest));
    return config;
  }
예제 #20
0
    /**
     * Test overriding WADL's /application/resources/@base attribute.
     *
     * @throws Exception in case of unexpected test failure.
     */
    @Test
    public void testCustomWadlResourcesBaseUri() throws Exception {
      final ResourceConfig rc = new ResourceConfig(WidgetsResource.class, ExtraResource.class);
      rc.property(ServerProperties.WADL_GENERATOR_CONFIG, MyWadlGeneratorConfig.class.getName());

      final ApplicationHandler applicationHandler = new ApplicationHandler(rc);

      final ContainerResponse containerResponse =
          applicationHandler
              .apply(
                  new ContainerRequest(
                      URI.create("/"),
                      URI.create("/application.wadl"),
                      "GET",
                      null,
                      new MapPropertiesDelegate()))
              .get();

      final DocumentBuilderFactory bf = DocumentBuilderFactory.newInstance();
      bf.setNamespaceAware(true);
      bf.setValidating(false);
      if (!SaxHelper.isXdkDocumentBuilderFactory(bf)) {
        bf.setXIncludeAware(false);
      }
      final DocumentBuilder b = bf.newDocumentBuilder();

      ((ByteArrayInputStream) containerResponse.getEntity()).reset();

      final Document d = b.parse((InputStream) containerResponse.getEntity());
      printSource(new DOMSource(d));
      final XPath xp = XPathFactory.newInstance().newXPath();
      xp.setNamespaceContext(
          new SimpleNamespaceResolver("wadl", "http://wadl.dev.java.net/2009/02"));
      // check base URI
      final String val =
          (String) xp.evaluate("/wadl:application/wadl:resources/@base", d, XPathConstants.STRING);
      assertEquals(val, MyWadlGeneratorConfig.MyWadlGenerator.CUSTOM_RESOURCES_BASE_URI);
    }
  private ServletContainer processBundle(Bundle bundle, String applicationName) {
    Application application = null;
    try {
      Class<?> applicationClass = bundle.loadClass(applicationName);
      application = (Application) applicationClass.newInstance();
    } catch (Exception e) {
      log.log(
          LogService.LOG_ERROR,
          "Error loading application class "
              + applicationName
              + " from bundle "
              + bundle.getLocation(),
          e);
    }

    return new ServletContainer(ResourceConfig.forApplication(application));
  }
예제 #22
0
  public static void main(String[] args)
      throws IOException, URISyntaxException, InterruptedException {
    final int port = System.getenv("PORT") != null ? Integer.valueOf(System.getenv("PORT")) : 8080;
    final URI baseUri = UriBuilder.fromUri("http://0.0.0.0/").port(port).build();
    final Application application =
        Application.builder(
                ResourceConfig.builder().packages(BarServer.class.getPackage().getName()).build())
            .build();
    application.addModules(new JsonJacksonModule());
    final HttpServer httpServer = GrizzlyHttpServerFactory.createHttpServer(baseUri, application);
    httpServer
        .getServerConfiguration()
        .addHttpHandler(new StaticHttpHandler("src/main/webapp"), CONTENT_PATH);

    for (NetworkListener networkListener : httpServer.getListeners()) {
      if (System.getenv("FILE_CACHE_ENABLED") == null) {
        networkListener.getFileCache().setEnabled(false);
      }
    }

    Runtime.getRuntime()
        .addShutdownHook(
            new Thread() {
              @Override
              public void run() {
                httpServer.stop();
              }
            });

    MongoURI mongolabUri =
        new MongoURI(
            System.getenv("MONGOLAB_URI") != null
                ? System.getenv("MONGOLAB_URI")
                : "mongodb://127.0.0.1:27017/hello");
    Mongo m = new Mongo(mongolabUri);
    mongoDB = m.getDB(mongolabUri.getDatabase());
    if ((mongolabUri.getUsername() != null) && (mongolabUri.getPassword() != null)) {
      mongoDB.authenticate(mongolabUri.getUsername(), mongolabUri.getPassword());
    }

    contentUrl = System.getenv("CONTENT_URL") != null ? System.getenv("CONTENT_URL") : CONTENT_PATH;

    Thread.currentThread().join();
  }
예제 #23
0
 private ResourceConfig getResourceConfig(Application app) {
   return ResourceConfig.forApplication(app);
 }
예제 #24
0
  @SuppressWarnings({"unchecked", "rawtypes"})
  public Task<Void> start() {

    // Ensuring that jersey will use singletons from the orbit container.
    ServiceLocator locator = Injections.createLocator();
    DynamicConfigurationService dcs = locator.getService(DynamicConfigurationService.class);
    DynamicConfiguration dc = dcs.createDynamicConfiguration();

    final List<Class<?>> classes = new ArrayList<>(providers);
    if (container != null) {
      classes.addAll(container.getClasses());
      for (final Class<?> c : container.getClasses()) {
        if (c.isAnnotationPresent(Singleton.class)) {
          Injections.addBinding(
              Injections.newFactoryBinder(
                      new Factory() {
                        @Override
                        public Object provide() {
                          return container.get(c);
                        }

                        @Override
                        public void dispose(final Object instance) {}
                      })
                  .to(c),
              dc);
        }
      }
    }
    dc.commit();

    final ResourceConfig resourceConfig = new ResourceConfig();

    // installing jax-rs classes known by the orbit container.
    for (final Class c : classes) {
      if (c.isAnnotationPresent(javax.ws.rs.Path.class)
          || c.isAnnotationPresent(javax.ws.rs.ext.Provider.class)) {
        resourceConfig.register(c);
      }
    }

    final WebAppContext webAppContext = new WebAppContext();
    final ProtectionDomain protectionDomain = EmbeddedHttpServer.class.getProtectionDomain();
    final URL location = protectionDomain.getCodeSource().getLocation();
    logger.info(location.toExternalForm());
    webAppContext.setInitParameter("useFileMappedBuffer", "false");
    webAppContext.setWar(location.toExternalForm());
    // this sets the default service locator to one that bridges to the orbit container.
    webAppContext.getServletContext().setAttribute(ServletProperties.SERVICE_LOCATOR, locator);
    webAppContext.setContextPath("/*");
    webAppContext.addServlet(new ServletHolder(new ServletContainer(resourceConfig)), "/*");

    final ContextHandler resourceContext = new ContextHandler();
    ResourceHandler resourceHandler = new ResourceHandler();
    resourceHandler.setDirectoriesListed(true);
    resourceHandler.setWelcomeFiles(new String[] {"index.html"});
    resourceHandler.setBaseResource(Resource.newClassPathResource("/web"));

    resourceContext.setHandler(resourceHandler);
    resourceContext.setInitParameter("useFileMappedBuffer", "false");
    final ContextHandlerCollection contexts = new ContextHandlerCollection();

    contexts.setHandlers(
        new Handler[] {
          wrapHandlerWithMetrics(resourceContext, "resourceContext"),
          wrapHandlerWithMetrics(webAppContext, "webAppContext")
        });

    server = new Server(port);
    server.setHandler(contexts);
    try {
      /// Initialize javax.websocket layer
      final ServerContainer serverContainer =
          WebSocketServerContainerInitializer.configureContext(webAppContext);

      for (Class c : classes) {
        if (c.isAnnotationPresent(ServerEndpoint.class)) {
          final ServerEndpoint annotation = (ServerEndpoint) c.getAnnotation(ServerEndpoint.class);

          final ServerEndpointConfig serverEndpointConfig =
              ServerEndpointConfig.Builder.create(c, annotation.value())
                  .configurator(
                      new ServerEndpointConfig.Configurator() {
                        @Override
                        public <T> T getEndpointInstance(final Class<T> endpointClass)
                            throws InstantiationException {
                          return container.get(endpointClass);
                        }
                      })
                  .build();

          serverContainer.addEndpoint(serverEndpointConfig);
        }
      }
    } catch (Exception e) {
      logger.error("Error starting jetty", e);
      throw new UncheckedException(e);
    }

    try {
      server.start();
    } catch (Exception e) {
      logger.error("Error starting jetty", e);
      throw new UncheckedException(e);
    }
    return Task.done();
  }
 @Override
 protected ResourceConfig configureApplication() {
   final ResourceConfig application = new ResourceConfig();
   application.register(DefaultWishlistsResource.class);
   return application;
 }
예제 #26
0
 @Override
 protected Application configure() {
   ResourceConfig config = new ResourceConfig(HttpMethodResource.class);
   config.register(new LoggingFilter(LOGGER, true));
   return config;
 }
예제 #27
0
  private void run() throws Exception {
    InetSocketAddress address;

    if (this.host != null) {
      address = new InetSocketAddress(this.host, this.port);
    } else {
      address = new InetSocketAddress(this.port);
    }

    Server server = new Server(address);

    ContextHandlerCollection handlerCollection = new ContextHandlerCollection();

    final ModelRegistry modelRegistry = new ModelRegistry();

    final MetricRegistry metricRegistry = new MetricRegistry();

    Binder binder =
        new AbstractBinder() {

          @Override
          protected void configure() {
            bind(modelRegistry).to(ModelRegistry.class);
            bind(metricRegistry).to(MetricRegistry.class);
          }
        };

    ResourceConfig config = new ResourceConfig(ModelResource.class);
    config.register(binder);
    config.register(JacksonFeature.class);
    config.register(MultiPartFeature.class);
    config.register(ObjectMapperProvider.class);
    config.register(RolesAllowedDynamicFeature.class);

    // Naive implementation that grants the "admin" role to all local network users
    config.register(NetworkSecurityContextFilter.class);

    ServletContextHandler servletHandler = new ServletContextHandler();
    servletHandler.setContextPath(this.contextPath);

    ServletContainer jerseyServlet = new ServletContainer(config);

    servletHandler.addServlet(new ServletHolder(jerseyServlet), "/*");

    InstrumentedHandler instrumentedHandler = new InstrumentedHandler(metricRegistry);
    instrumentedHandler.setHandler(servletHandler);

    handlerCollection.addHandler(instrumentedHandler);

    if (this.consoleWar != null) {
      WebAppContext consoleHandler = new WebAppContext();
      consoleHandler.setContextPath(this.contextPath + "/console"); // XXX
      consoleHandler.setWar(this.consoleWar.getAbsolutePath());

      handlerCollection.addHandler(consoleHandler);
    }

    server.setHandler(handlerCollection);

    DirectoryDeployer deployer = null;

    if (this.modelDir != null) {

      if (!this.modelDir.isDirectory()) {
        throw new IOException(this.modelDir.getAbsolutePath() + " is not a directory");
      }

      deployer = new DirectoryDeployer(modelRegistry, this.modelDir.toPath());
    }

    server.start();

    if (deployer != null) {
      deployer.start();
    }

    server.join();

    if (deployer != null) {
      deployer.interrupt();

      deployer.join();
    }
  }
예제 #28
0
 @Override
 protected Application configure() {
   ResourceConfig rc = new ResourceConfig();
   rc.addClasses(MyTypeResource.class, MyTypeWriter.class, ResourceGetByteNoHead.class);
   return rc;
 }