org.jboss.resteasy.plugins.server.vertx.VertxResteasyDeployment Java Examples

The following examples show how to use org.jboss.resteasy.plugins.server.vertx.VertxResteasyDeployment. 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: FCSPlugin.java    From redpipe with Apache License 2.0 6 votes vote down vote up
@Override
public Completable deployToResteasy(VertxResteasyDeployment deployment) {
	return Completable.defer(() -> {
		JsonArray packages = AppGlobals.get().getConfig().getJsonArray("scan");
		if(packages == null) {
			System.err.println("Not scanning any packages, please specify the 'scan' array of packages in configuration");
		}else {
			String[] packagesToScan = (String[]) packages.getList().toArray(new String[packages.size()]);
			new FastClasspathScanner(packagesToScan)
			.matchClassesWithAnnotation(Path.class, klass -> {
				if(!Modifier.isAbstract(klass.getModifiers()))
					deployment.getActualResourceClasses().add(klass);
			})
			.matchClassesWithAnnotation(Provider.class, klass -> {
				if(!Modifier.isAbstract(klass.getModifiers()))
					deployment.getActualProviderClasses().add(klass);
			})
			.scan();
		}
		return super.deployToResteasy(deployment);
	});
}
 
Example #2
Source File: Server.java    From redpipe with Apache License 2.0 6 votes vote down vote up
private Completable setupVertx(VertxResteasyDeployment deployment) {
   	return Completable.defer(() -> {
   		// Get a DB
   		SQLClient dbClient = createDbClient(AppGlobals.get().getConfig());

   		Class<?> mainClass = null;
   		for (Class<?> resourceClass : deployment.getActualResourceClasses()) {
   			if(resourceClass.getAnnotation(MainResource.class) != null){
   				mainClass = resourceClass;
   				break;
   			}
   		}

   		// Save our injected globals
   		AppGlobals globals = AppGlobals.get();
   		globals.setDbClient(dbClient);
   		globals.setMainClass(mainClass);
   		globals.setDeployment(deployment);

   		return doOnPlugins(plugin -> plugin.init())
   				.concatWith(startVertx(deployment));
   	});
}
 
Example #3
Source File: Server.java    From redpipe with Apache License 2.0 6 votes vote down vote up
protected Single<VertxResteasyDeployment> setupResteasy(Class<?>... resourceOrProviderClasses) {
	return Single.defer(() -> {
		// Build the Jax-RS hello world deployment
		VertxResteasyDeployment deployment = new VertxResteasyDeployment();
		deployment.getDefaultContextObjects().put(Vertx.class, AppGlobals.get().getVertx());
		deployment.getDefaultContextObjects().put(AppGlobals.class, AppGlobals.get());

		return doOnPlugins(plugin -> plugin.deployToResteasy(deployment)).toSingle(() -> {
			for(Class<?> klass : resourceOrProviderClasses) {
				if(klass.isAnnotationPresent(Path.class))
					deployment.getActualResourceClasses().add(klass);
				if(klass.isAnnotationPresent(Provider.class))
					deployment.getActualProviderClasses().add(klass);
			}
			try {
				deployment.start();
			}catch(ExceptionInInitializerError err) {
				// rxjava behaves badly on LinkageError
				RedpipeUtil.rethrow(err.getCause());
			}
			return deployment;
		}).doOnError(t -> t.printStackTrace());
	});
}
 
Example #4
Source File: MainModule.java    From cassandra-sidecar with Apache License 2.0 5 votes vote down vote up
@Provides
@Singleton
private VertxRequestHandler configureServices(Vertx vertx, HealthService healthService)
{
    VertxResteasyDeployment deployment = new VertxResteasyDeployment();
    deployment.start();
    VertxRegistry r = deployment.getRegistry();

    r.addPerInstanceResource(SwaggerOpenApiResource.class);
    r.addSingletonResource(healthService);

    return new VertxRequestHandler(vertx, deployment);
}
 
Example #5
Source File: CdiPlugin.java    From redpipe with Apache License 2.0 5 votes vote down vote up
@Override
public Completable deployToResteasy(VertxResteasyDeployment deployment) {
	ResteasyCdiExtension cdiExtension = CDI.current().select(ResteasyCdiExtension.class).get();
	deployment.setActualResourceClasses(cdiExtension.getResources());
	deployment.setInjectorFactoryClass(CdiInjectorFactory.class.getName());
	deployment.getActualProviderClasses().addAll(cdiExtension.getProviders());
	return Completable.complete();
}
 
Example #6
Source File: Server.java    From redpipe with Apache License 2.0 5 votes vote down vote up
private Completable startVertx(VertxResteasyDeployment deployment)
{
	return Completable.defer(() -> {
		Router router = Router.router(vertx);
		AppGlobals globals = AppGlobals.get();
		globals.setRouter(router);

		VertxPluginRequestHandler resteasyHandler = new VertxPluginRequestHandler(vertx, deployment, plugins);

		return doOnPlugins(plugin -> plugin.preRoute())
				.doOnComplete(() -> {
					setupRoutes(router);
					router.route().handler(routingContext -> {
						ResteasyProviderFactory.pushContext(RoutingContext.class, routingContext);
						ResteasyProviderFactory.pushContext(io.vertx.rxjava.ext.web.RoutingContext.class, 
								io.vertx.rxjava.ext.web.RoutingContext.newInstance(routingContext.getDelegate()));
						resteasyHandler.handle(routingContext.request());
					});
				}).concatWith(doOnPlugins(plugin -> plugin.postRoute()))
				.concatWith(Completable.defer(() -> {
					// Start the front end server using the Jax-RS controller
					int port = globals.getConfig().getInteger("http_port", 9000);
					String host = globals.getConfig().getString("http_host", NetServerOptions.DEFAULT_HOST);
					return vertx.createHttpServer()
							.requestHandler(router::accept)
							.rxListen(port, host)
							.doOnSuccess(server -> System.out.println("Server started on port " + server.actualPort()))
							.doOnError(t -> t.printStackTrace())
							.ignoreElement();
				}));
	});
}
 
Example #7
Source File: Server.java    From redpipe with Apache License 2.0 4 votes vote down vote up
protected void setupSwagger(VertxResteasyDeployment deployment) {
	ModelConverters.getInstance().addConverter(new RxModelConverter());
	
	// Swagger
	ServletContext servletContext = new RedpipeServletContext();
	AppGlobals.get().setGlobal(ServletContext.class, servletContext);

	ServletConfig servletConfig = new ServletConfig(){

		@Override
		public String getServletName() {
			return "pretend-servlet";
		}

		@Override
		public ServletContext getServletContext() {
			return servletContext;
		}

		@Override
		public String getInitParameter(String name) {
			return getServletContext().getInitParameter(name);
		}

		@Override
		public Enumeration<String> getInitParameterNames() {
			return getServletContext().getInitParameterNames();
		}
	};
	AppGlobals.get().setGlobal(ServletConfig.class, servletConfig);

	ReaderConfigUtils.initReaderConfig(servletConfig);

	BeanConfig swaggerConfig = new MyBeanConfig();
	swaggerConfig.setVersion("1.0");
	swaggerConfig.setSchemes(new String[]{"http"});
	swaggerConfig.setHost("localhost:"+AppGlobals.get().getConfig().getInteger("http_port", 9000));
	swaggerConfig.setBasePath("/");
	Set<String> resourcePackages = new HashSet<>();
	for (Class<?> klass : deployment.getActualResourceClasses()) {
		resourcePackages.add(klass.getPackage().getName());
	}
	swaggerConfig.setResourcePackage(String.join(",", resourcePackages));
	swaggerConfig.setServletConfig(servletConfig);
	swaggerConfig.setPrettyPrint(true);
	swaggerConfig.setScan(true);
	
	deployment.getRegistry().addPerInstanceResource(ApiListingResource.class);
	deployment.getProviderFactory().register(SwaggerSerializers.class);
}
 
Example #8
Source File: AppGlobals.java    From redpipe with Apache License 2.0 4 votes vote down vote up
public void setDeployment(VertxResteasyDeployment deployment) {
	this.deployment = deployment;
}
 
Example #9
Source File: AppGlobals.java    From redpipe with Apache License 2.0 4 votes vote down vote up
public VertxResteasyDeployment getDeployment() {
	return deployment;
}
 
Example #10
Source File: VertxRestService.java    From atomix with Apache License 2.0 4 votes vote down vote up
@Override
public CompletableFuture<RestService> start() {
  server = vertx.createHttpServer();
  deployment = new VertxResteasyDeployment();
  deployment.start();

  deployment.getDispatcher().getDefaultContextObjects()
      .put(ClusterMembershipService.class, atomix.getMembershipService());
  deployment.getDispatcher().getDefaultContextObjects()
      .put(ClusterCommunicationService.class, atomix.getCommunicationService());
  deployment.getDispatcher().getDefaultContextObjects()
      .put(ClusterEventService.class, atomix.getEventService());
  deployment.getDispatcher().getDefaultContextObjects()
      .put(PrimitiveFactory.class, atomix.getPrimitivesService());
  deployment.getDispatcher().getDefaultContextObjects()
      .put(PrimitivesService.class, atomix.getPrimitivesService());
  deployment.getDispatcher().getDefaultContextObjects()
      .put(EventManager.class, new EventManager());
  deployment.getDispatcher().getDefaultContextObjects()
      .put(AtomixRegistry.class, atomix.getRegistry());

  final ClassLoader classLoader = atomix.getClass().getClassLoader();
  final String[] whitelistPackages = StringUtils.split(System.getProperty("io.atomix.whitelistPackages"), ",");
  final ClassGraph classGraph = whitelistPackages != null
      ? new ClassGraph().enableAnnotationInfo().whitelistPackages(whitelistPackages).addClassLoader(classLoader)
      : new ClassGraph().enableAnnotationInfo().addClassLoader(classLoader);

  try (final ScanResult scanResult = classGraph.scan()) {
    scanResult.getClassesWithAnnotation(AtomixResource.class.getName()).forEach(classInfo -> {
      deployment.getRegistry().addPerInstanceResource(classInfo.loadClass(), "/v1");
    });
  }

  deployment.getDispatcher().getProviderFactory().register(new JacksonProvider(createObjectMapper()));

  server.requestHandler(new VertxRequestHandler(vertx, deployment));

  CompletableFuture<RestService> future = new CompletableFuture<>();
  server.listen(address.port(), address.address(true).getHostAddress(), result -> {
    if (result.succeeded()) {
      open.set(true);
      LOGGER.info("Started");
      future.complete(this);
    } else {
      future.completeExceptionally(result.cause());
    }
  });
  return future;
}
 
Example #11
Source File: ApiVerticle.java    From apiman with Apache License 2.0 4 votes vote down vote up
@Override
public void start(Future<Void> startFuture) {
    Future<Void> superFuture = Future.future();
    Future<HttpServer> listenFuture = Future.future();
    super.start(superFuture);

    CompositeFuture.all(superFuture, listenFuture)
        .setHandler(compositeResult -> {
            if (compositeResult.succeeded()) {
                startFuture.complete(null);
            } else {
                startFuture.fail(compositeResult.cause());
            }
        });

    VertxResteasyDeployment deployment = new VertxResteasyDeployment();
    deployment.start();

    addResources(deployment.getRegistry(),
            new SystemResourceImpl(apimanConfig, engine),
            new ApiResourceImpl(apimanConfig, engine),
            new ClientResourceImpl(apimanConfig, engine),
            new OrgResourceImpl(apimanConfig, engine));

    deployment.getProviderFactory().register(RestExceptionMapper.class);

    VertxRequestHandler resteasyRh = new VertxRequestHandler(vertx, deployment);

    Router router = Router.router(vertx)
                .exceptionHandler(error -> log.error(error.getMessage(), error));

    // Ensure body handler is attached early so that if AuthHandler takes an external action
    // we don't end up losing the body (e.g OAuth2).
    router.route()
        .handler(BodyHandler.create());

    AuthHandler authHandler = AuthFactory.getAuth(vertx, router, apimanConfig);

    router.route("/*")
        .handler(authHandler);

    router.route("/*") // We did the previous stuff, now we call into JaxRS.
        .handler(context -> resteasyRh.handle(new Router2ResteasyRequestAdapter(context)));

    HttpServerOptions httpOptions = new HttpServerOptions();

    if (apimanConfig.isSSL()) {
        httpOptions.setSsl(true)
        .setKeyStoreOptions(
                new JksOptions()
                    .setPath(apimanConfig.getKeyStore())
                    .setPassword(apimanConfig.getKeyStorePassword())
                )
        .setTrustStoreOptions(
                new JksOptions()
                    .setPath(apimanConfig.getTrustStore())
                    .setPassword(apimanConfig.getTrustStorePassword())
                );
        addAllowedSslTlsProtocols(httpOptions);
    } else {
        log.warn("API is running in plaintext mode. Enable SSL in config for production deployments.");
    }

    vertx.createHttpServer(httpOptions)
        .requestHandler(router::accept)
        .listen(apimanConfig.getPort(VERTICLE_TYPE),
                apimanConfig.getHostname(),
                listenFuture.completer());
}
 
Example #12
Source File: Plugin.java    From redpipe with Apache License 2.0 votes vote down vote up
public Completable deployToResteasy(VertxResteasyDeployment deployment){ return Completable.complete(); }