@Override public boolean configure(final FeatureContext featureContext) { final UserRepository userRepo = CDI.current().select(UserRepository.class).get(); final Authenticator<String, User> authenticator = new GoogleAuthenticator( authConfig.getClientId(), userRepo, authConfig.getHostedDomain() ); final Authenticator<String, User> cachingAuthenticator = new CachingAuthenticator<>( metricRegistry, authenticator, authConfig.getAuthenticationCachePolicy() ); featureContext.register(new AuthDynamicFeature( new OAuthCredentialAuthFilter.Builder<User>() .setAuthenticator(cachingAuthenticator) .setPrefix("Bearer") .buildAuthFilter())); featureContext.register(new AuthValueFactoryProvider.Binder<>(User.class)); return true; }
@Test public void testProducer() { logger.info("starting producer spi test"); CDI<Object> cdi = current(); BeanManager beanManager = cdi.select(BeanManager.class).get(); AnnotatedField<? super AnotherFactory> field = this .<AnotherFactory, AnnotatedField<AnotherFactory>>getAnnotatedMember(AnotherFactory.class, "jessie", beanManager); Bean<AnotherFactory> declaringBean = cast(beanManager.resolve(beanManager.getBeans(AnotherFactory.class))); ProducerFactory<AnotherFactory> producerFactory = beanManager.getProducerFactory(field, declaringBean); Producer<Toy> producer = cast(producerFactory.createProducer(null)); assertNotNull(producer); assertTrue(producer.getInjectionPoints().isEmpty()); Toy jessie = producer.produce(beanManager.<Toy>createCreationalContext(null)); assertEquals("Jessie", jessie.getName()); }
private String getAppData(){ activeUser = CDI.current().select(ActiveUser.class).get(); CharSequence http = "http://"; CharSequence https = "https://"; AppContext appContext = CDI.current().select(AppContext.class).get(); Gson gson = new Gson(); Map map = new HashMap(); map.put("base_url", requestContext.getBaseURL()); map.put("base64_url", new BASE64Encoder().encode(requestContext.getBaseURL().getBytes())); map.put("simple_base_url", requestContext.getBaseURL().replace(http,"").replace(https,"")); map.put("deployId",appContext.getDeployId()); map.put("deployMode",appContext.getDeployMode().toString()); map.put("csrfToken",activeUser.getCsrfToken()); return gson.toJson(map); }
@BeforeClass(alwaysRun=true) public static void loadTokenParser() throws Exception { System.out.printf("TokenValidationTest.initClass\n"); publicKey = TokenUtils.readPublicKey("/publicKey.pem"); if(publicKey == null) { throw new IllegalStateException("Failed to load /publicKey.pem resource"); } // Load the ITokenParser via the ServiceLoader ServiceLoader<ITokenParser> serviceLoader = ServiceLoader.load(ITokenParser.class); if(serviceLoader.iterator().hasNext() == false) { // Try to obtain ITokenParser via CDI tokenParser = CDI.current().select(ITokenParser.class).get(); if(tokenParser == null) { throw new IllegalStateException(String.format("An %s service provider or producer is required", ITokenParser.class.getName())); } } else { tokenParser = serviceLoader.iterator().next(); if (tokenParser == null) { throw new IllegalStateException(String.format("Service provider for %s produced a null parser", ITokenParser.class.getName())); } } System.out.printf("Using ITokenParser: %s\n", tokenParser); }
@Override public void aroundRequest(HttpRequest req, RunnableWithException<IOException> continuation) throws IOException { BoundRequestContext cdiContext = CDI.current().select(BoundRequestContext.class).get(); Map<String,Object> contextMap = new HashMap<String,Object>(); cdiContext.associate(contextMap); cdiContext.activate(); try { // FIXME: associate CDI thread context on thread change, like Resteasy context? continuation.run(); }finally { if(req.getAsyncContext().isSuspended()) { req.getAsyncContext().getAsyncResponse().register((CompletionCallback)(t) -> { cdiContext.invalidate(); cdiContext.deactivate(); cdiContext.dissociate(contextMap); }); }else { cdiContext.invalidate(); cdiContext.deactivate(); cdiContext.dissociate(contextMap); } } }
private void runInstallTasks() { logger.info("Running installation tasks..."); List<Class<? extends SetupTask>> setupTasksClasses = findSetupTasksAndPrioritize(); setupTasksClasses.forEach(setupTaskClass -> { SetupTask setupTask = CDI.current().select(setupTaskClass).get(); try { logger.info("Installation task: {}", setupTask.getDisplayName()); setupTask.install(); } catch (Exception e) { logger.error("Error while running installation task: {}", setupTask.getDisplayName(), e); } finally { CDI.current().destroy(setupTask); } }); logger.info("Installation tasks completed, do not forget to change biliomi.core.updateMode to {}", UpdateModeType.OFF); }
private void runUpdateTasks() { logger.info("Running update tasks..."); List<Class<? extends SetupTask>> setupTasksClasses = findSetupTasksAndPrioritize(); setupTasksClasses.forEach(setupTaskClass -> { SetupTask setupTask = CDI.current().select(setupTaskClass).get(); try { logger.info("Update task: {}", setupTask.getDisplayName()); setupTask.update(); } catch (Exception e) { logger.error("Error while running update task: {}", setupTask.getDisplayName(), e); } finally { CDI.current().destroy(setupTask); } }); logger.info("Update tasks completed, do not forget to change biliomi.core.updateMode to {}\n", UpdateModeType.OFF); }
@Override public <A extends Annotation> List<Object> getInstancesByAnnotation(Class<A> annotationClass) { BeanManager beanManager = CDI.current().getBeanManager(); Set<Bean<?>> beans = beanManager.getBeans(Object.class); List<Object> list = new ArrayList<>(); for (Bean<?> bean : beans) { Class<?> beanClass = bean.getBeanClass(); Optional<A> annotation = ClassUtils.getAnnotation(beanClass, annotationClass); if (annotation.isPresent()) { CreationalContext<?> creationalContext = beanManager.createCreationalContext(bean); Object object = beanManager.getReference(bean, beanClass, creationalContext); list.add(object); } } return list; }
/** * First check a CDI provider, if available use those. * Try to lookup in a JNDI if no provider is registered. * If one of the above is found {@link BeanManagerInstanceCreator} is returned, * or {@link DefaultConstructorCreator} otherwise. * @return Component instance creator, either CDI or default constructor. */ public static JsonbComponentInstanceCreator getComponentInstanceCreator() { try { return new BeanManagerInstanceCreator(CDI.current().getBeanManager()); } catch (Throwable e) { log.finest(Messages.getMessage(MessageKeys.BEAN_MANAGER_NOT_FOUND_NO_PROVIDER)); try { InitialContext context = new InitialContext(); final BeanManager lookup = (BeanManager) context.lookup(BEAN_MANAGER_NAME); return new BeanManagerInstanceCreator(lookup); } catch (NamingException e1) { log.finest(Messages.getMessage(MessageKeys.BEAN_MANAGER_NOT_FOUND_JNDI, BEAN_MANAGER_NAME, e1.getExplanation())); } } log.finest(Messages.getMessage(MessageKeys.BEAN_MANAGER_NOT_FOUND_USING_DEFAULT)); return new DefaultConstructorCreator(); }
@Override public void filter(ContainerRequestContext requestContext) throws IOException { Instance<Object> instance = CDI.current(); User user = instance.select(User.class).get(); List<AccountRole> roles = user.getAccountRoles(); if (Arrays.stream(permissions.roles()).anyMatch(roles::contains)) { return; } Permission permission = instance.select(permissions.value()).get(); if (permission.test(requestContext)) { return; } throw new ForbiddenException(); }
@Override public void onStartup(Set<Class<?>> c, ServletContext ctx) throws ServletException { // Obtain a reference to the CdiExtension that was used to see if // there's an enabled bean CdiExtension cdiExtension = CDI.current().select(CdiExtension.class).get(); if (cdiExtension.isHttpAuthenticationMechanismFound()) { // A SAM must be registered at this point, since the programmatically added // Listener is for some reason restricted (not allow) from calling // getVirtualServerName. At this point we're still allowed to call this. // TODO: Ask the Servlet EG to address this? Is there any ground for this restriction??? registerServerAuthModule(new HttpBridgeServerAuthModule(), ctx); // Add a listener so we can process the context destroyed event, which is needed // to de-register the SAM correctly. ctx.addListener(this); } }
@Override public AuthStatus validateRequest(HttpServletRequest request, HttpServletResponse response, HttpMessageContext httpMsgContext) throws AuthException { String[] credentials = getCredentials(request); if (!isEmpty(credentials)) { IdentityStore identityStore = CDI.current().select(IdentityStore.class).get(); CredentialValidationResult result = identityStore.validate( new UsernamePasswordCredential(credentials[0], new Password(credentials[1]))); if (result.getStatus() == VALID) { return httpMsgContext.notifyContainerAboutLogin( result.getCallerName(), result.getCallerGroups()); } } if (httpMsgContext.isProtected()) { response.setHeader("WWW-Authenticate", basicHeaderValue); return httpMsgContext.responseUnAuthorized(); } return httpMsgContext.doNothing(); }
public static void main(String[] args) throws Exception { final CdiContainer container = CdiContainerLoader.getCdiContainer(); try { container.boot(); ContextControl contextControl = container.getContextControl(); contextControl.startContext(ApplicationScoped.class); Quickstart quickstart = CDI.current().select(Quickstart.class).get(); quickstart.run(); } catch (Exception e) { e.printStackTrace(); } finally { container.shutdown(); System.out.println("Shutting down..."); System.exit(0); } }
private Runnable newWorkflowRunnable(final IWorkflowListener listener) { return new Runnable() { @Override public void run() { LOG.info("Workflow started... {}", CDI.current()); for (IWorkflowStep step : newWorkflowSteps(listener)) { try { step.run(); /* sync */ } catch (WorkflowException e) { listener.onException(String.format(EXCEPTION_PATTERN, "Workflow", e.getMessage())); } } } }; }
public void login(UserAccessToken token) { this.logout(); this.accessToken = token; UserBS bs = CDI.current().select(UserBS.class).get(); // TODO Recuperar as permissões de fato. List<UserPermission> perms = null; if (GeneralUtils.isEmpty(perms)) { this.permissions = new ArrayList<String>(); } else { this.permissions = new ArrayList<String>(perms.size()); for (UserPermission perm : perms) { this.permissions.add(perm.getPermission()); } } this.accessLevel = token.getUser().getAccessLevel(); this.loginEvent.fire(new AuthEvent(this.accessToken)); }
/** * Processes requests for both HTTP * <code>GET</code> and * <code>POST</code> methods. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); try (PrintWriter out = response.getWriter()) { out.println("<!DOCTYPE html>"); out.println("<html>"); out.println("<head>"); out.println("<title>BeanManager using CDI.current</title>"); out.println("</head>"); out.println("<body>"); out.println("<h1>BeanManager using CDI.current</h1>"); // Second way to get BeanManager BeanManager bm = CDI.current().getBeanManager(); Set<Bean<?>> beans = bm.getBeans(Greeting.class); for (Bean<?> b : beans) { out.println(b.getBeanClass().getName() + "<br>"); } out.println("</body>"); out.println("</html>"); } }
@Test public void testInit() throws InterruptedException { /** * Some TODOs: * * 1. Add an extension that observes ProcessAnnotatedType, keeps in a class, and then add a getter to get the list of these that are annotated @Path * 2. Override CDIRequestDispatcher to start a request context, and then stop when done. * */ BasicConfigurator.configure(); Weld weld = new Weld(); weld.initialize(); LoadPathsExtension paths = CDI.current().select(LoadPathsExtension.class).get(); CDINettyJaxrsServer netty = new CDINettyJaxrsServer(); ResteasyDeployment rd = new ResteasyDeployment(); rd.setActualResourceClasses(paths.getResources()); rd.setInjectorFactoryClass(CdiInjectorFactory.class.getName()); netty.setDeployment(rd); netty.setPort(8087); netty.setRootResourcePath(""); netty.setSecurityDomain(null); netty.start(); Client c = ClientBuilder.newClient(); String result = c.target("http://localhost:8087").path("/").request("text/plain").accept("text/plain").get(String.class); Assert.assertEquals("pong", result); }
@AroundInvoke public Object startRequestScope(final InvocationContext ctx) throws Exception { Object result = null; ContextControl contextControl = null; if(!isRequestScopeActive()) { contextControl = CDI.current().select(ContextControl.class).get(); contextControl.startContext(RequestScoped.class); } try { result = ctx.proceed(); } finally { if(contextControl != null) { contextControl.stopContext(RequestScoped.class); } } return result; }
@Override public Iterator<Object> iterator() { BeanManager beanManager = CDI.current().getBeanManager(); Bean<WindowBeanHolder> bean = resolveBean(beanManager, WindowBeanHolder.class); if (bean != null) { Context sessionContext = beanManager.getContext(bean.getScope()); if (sessionContext != null) { WindowBeanHolder beanHolder = sessionContext.get(bean); Map<String, ContextualStorage> storageMap = (Map<String, ContextualStorage>) ReflectionHelper.get(beanHolder, "storageMap"); if (storageMap != null) { return new WindowContextsIterator(new ArrayList<String>(storageMap.keySet())); } } else { LOGGER.debug("No WindowBeanHolder found, no active session context."); } } return null; }
@Override public void handleNotification(final SecurityNotification notification) { switch (notification.getEventType()) { case AUTHENTICATED: CDI.current().getBeanManager().fireEvent(new AuthenticatedEvent(notification, notification.getAccount().getPrincipal())); break; case LOGGED_OUT: CDI.current().getBeanManager().fireEvent(new LoggedOutEvent(notification, notification.getAccount().getPrincipal())); break; case FAILED_AUTHENTICATION: CDI.current().getBeanManager().fireEvent(new FailedAuthenticatedEvent(notification, FAILED_AUTH_USER)); break; default: break; } }
public final <T> T lookup(Class<T> clazz) { if (!cdiEnabled) { return null; } try { // lookup first instance found return CDI.current().select(clazz).get(); } catch (Exception e) { if (e instanceof CreationException) { throw e; } // may fail if CDI was not setup correctly // which is acceptable so return nothing.. // fix: new Weld().initialize() at bootstrap return null; } }
@Override public <T> Collection<T> lookupAll(Class<T> clazz) { if (!cdiEnabled) { return Lists.newArrayList(); } // return all instances found try { if (clazz.getName().equals(RECURSION_SHORTCIRCUIT.get())) { return new ArrayList<>(); } else { RECURSION_SHORTCIRCUIT.set(clazz.getName()); return Lists.newArrayList(CDI.current().select(clazz)); } } catch (Exception e) { if (e instanceof CreationException) { throw e; } // may fail if CDI was not setup correctly // which is acceptable so return nothing.. // fix: new Weld().initialize() at bootstrap return new ArrayList<>(); } finally { RECURSION_SHORTCIRCUIT.remove(); } }
@Override public <T> T get(Contextual<T> contextual, CreationalContext<T> creationalContext) { Bean<T> bean = (Bean<T>) contextual; cctx = creationalContext; if (ctx == null) { ctx = CDI.current().select(ConfigContext.class).get(); } final Object object; if (cache.containsKey(bean.getBeanClass())) { object = cache.get(bean.getBeanClass()); } else { object = ctx.get(bean.getBeanClass()); cache.put(bean.getBeanClass(), object); } return (T) object; }
@Override public <T> T get(Contextual<T> contextual) { if (cctx == null) { return null; } if (ctx == null) { ctx = CDI.current().select(ConfigContext.class).get(); } Bean<T> bean = (Bean<T>) contextual; final Object object; if (cache.containsKey(bean.getBeanClass())) { object = cache.get(bean.getBeanClass()); } else { object = ctx.get(bean.getBeanClass()); cache.put(bean.getBeanClass(), object); } return (T) object; }
@BeforeClass(alwaysRun=true) public static void generateToken() throws Exception { HashMap<String, Long> timeClaims = new HashMap<>(); token = TokenUtils.generateTokenString("/Token1.json", null, timeClaims); iatClaim = timeClaims.get(Claims.iat.name()); authTimeClaim = timeClaims.get(Claims.auth_time.name()); expClaim = timeClaims.get(Claims.exp.name()); System.out.printf("TokenValidationTest.initClass\n"); publicKey = TokenUtils.readPublicKey("/publicKey.pem"); if(publicKey == null) { throw new IllegalStateException("Failed to load /publicKey.pem resource"); } // Load the ITokenParser via the ServiceLoader ServiceLoader<ITokenParser> serviceLoader = ServiceLoader.load(ITokenParser.class); if(serviceLoader.iterator().hasNext() == false) { // Try to obtain ITokenParser via CDI tokenParser = CDI.current().select(ITokenParser.class).get(); if(tokenParser == null) { throw new IllegalStateException(String.format("An %s service provider or producer is required", ITokenParser.class.getName())); } } else { tokenParser = serviceLoader.iterator().next(); if (tokenParser == null) { throw new IllegalStateException(String.format("Service provider for %s produced a null parser", ITokenParser.class.getName())); } } System.out.printf("Using ITokenParser: %s\n", tokenParser); jwt = tokenParser.parse(token, TEST_ISSUER, publicKey); }
@Override public Single<Void> init() { // Setup the Vertx-CDI integration VertxExtension vertxExtension = CDI.current().select(VertxExtension.class).get(); BeanManager beanManager = CDI.current().getBeanManager(); // has to be done in a blocking thread Vertx vertx = AppGlobals.get().getVertx(); return vertx.rxExecuteBlocking(future -> { vertxExtension.registerConsumers(vertx.getDelegate(), BeanManagerProxy.unwrap(beanManager).event()); future.complete(); }); }
@Override public Single<Void> 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 Single.just(null); }
public BeanManager getBeanManager() { if (beanManager != null) { return beanManager; } else { return CDI.current().getBeanManager(); } }
/** * Export custom commands to CSV * Usage: /exportcommands */ @CliCommandRoute(command = "importsteamlibrary", description = "Import your Steam library using the information in the user settings") public boolean importSteamLibraryCommand(ConsoleInputEvent event) { SteamLibraryImporter steamLibraryImporter = CDI.current().select(SteamLibraryImporter.class).get(); steamLibraryImporter.run(); return true; }
public void run() { CDI<Object> cdi = CDI.current(); // Start console listener ConsoleApi consoleApi = cdi.select(ConsoleApi.class).get(); consoleApi.init(); // Run system boot SystemBoot systemBoot = cdi.select(SystemBoot.class).get(); systemBoot.runSetupTasks(); cdi.destroy(systemBoot); // Init ComponentManager cdi.select(ComponentManager.class).get(); // Start IrcSession cdi.select(IrcSession.class).get().start(); cdi.select(TwitchWebhookSession.class).get().start(); // Start REST API cdi.select(RestServerController.class).get().start(); // Start listening for console commands consoleApi.initCliCommands(); // The EventBusSubscriberInterceptor will register subscribers // Events are emitted by the IRC clients to bootstrap components and services }
private void runBootTasks() { List<Class<? extends SetupTask>> setupTasksClasses = findSetupTasksAndPrioritize(); setupTasksClasses.forEach(setupTaskClass -> { SetupTask setupTask = CDI.current().select(setupTaskClass).get(); try { setupTask.boot(); } catch (Exception e) { logger.error("Error while running boot task: {}", setupTask.getDisplayName(), e); } finally { CDI.current().destroy(setupTask); } }); }
/** * Run a bot command as another user. * Biliomi will temporarily be muted, to prevent unwanted whispers. * After execution the mute will be turned off. * Usage: !execute [runas username] [command] [arguments...] */ @CommandRoute(command = "execute", systemCommand = true) public boolean executeCommand(User user, Arguments arguments) { CommandRouter commandRouter = CDI.current().select(CommandRouter.class).get(); if (!arguments.assertMinSize(2)) { chat.whisper(user, i18n.get("ChatCommand.executeCommand.execute.usage")); return false; } String runAs = arguments.pop(); User runAsUser = usersService.getUser(runAs); if (runAsUser == null) { chat.whisper(user, i18n.getUserNonExistent(runAs)); return false; } OnOff originalMuteState = OnOff.fromBoolean(settingsService.getSystemSettings().isMuted()); if (OnOff.OFF.equals(originalMuteState)) { muteCommand(user, new Arguments("mute", "on")); } String commandMessage = Joiner.on(" ").join(arguments); IrcChatMessageEvent event = new IrcChatMessageEvent(runAs, null, commandMessage); commandRouter.runCommand(event, false); if (OnOff.OFF.equals(originalMuteState)) { muteCommand(user, new Arguments("mute", "off")); } chat.whisper(user, i18n.get("ChatCommand.executeCommand.execute.done") .add("command", commandMessage) .add("user", runAsUser::getDisplayName)); return true; }
private boolean exportCommands(Class<? extends Exporter> exporterClass) { Exporter exporter = CDI.current().select(exporterClass).get(); try { exporter.generateRows(); exporter.save(); logger.info(exporter.getDoneMessage()); return true; } catch (Exception e) { logger.error("An error uccurred during export", e); } return false; }
@Override public void afterScan(Reader reader, OpenAPI openAPI) { openAPI.info( new Info() .title("Simple Project Api") .version(getClass().getPackage().getImplementationVersion()) ); openAPI.servers(Collections.singletonList(new Server().description("Current Server").url(CDI.current().select(ServletContext.class).get().getContextPath()))); //error Schema errorObject = ModelConverters.getInstance().readAllAsResolvedSchema(ErrorValueObject.class).schema; openAPI.getComponents().addSchemas("Error", errorObject); openAPI.getPaths() .values() .stream() .flatMap(pathItem -> pathItem.readOperations().stream()) .forEach(operation -> { ApiResponses responses = operation.getResponses(); responses .addApiResponse(String.valueOf(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()), new ApiResponse().description("Unexpected exception. Error code = 1") .content( new Content().addMediaType(javax.ws.rs.core.MediaType.APPLICATION_JSON, new MediaType() .schema(errorObject)))); if (operation.getParameters() != null && !operation.getParameters().isEmpty()) { responses .addApiResponse(String.valueOf(Response.Status.BAD_REQUEST.getStatusCode()), new ApiResponse().description("Bad request. Error code = 2") .content( new Content().addMediaType(javax.ws.rs.core.MediaType.APPLICATION_JSON, new MediaType() .schema(errorObject)))); } }); }
@Override public Publisher<T> get(Object event) { CDI<Object> cdi = CDI.current(); List<InstanceHolder> instanceHolders = new ArrayList<>(); List<Object> parameters = new ArrayList<>(); for(AnnotatedParameter<?> ap : annotatedMethod.getParameters()) { if(ap.isAnnotationPresent(ObservesReactor.class)) { parameters.add(event); } else { InstanceHolder holder = getReference(cdi, ap.getJavaParameter().getType(), ap.getAnnotations()); instanceHolders.add(holder); parameters.add(holder.instance); } } InstanceHolder eventReceiver = getReference(cdi,annotatedType.getJavaClass(), findQualifiers(annotatedType.getAnnotations())); Object[] params = parameters.toArray(); try { Object result = targetMethod.invoke(eventReceiver.instance, params); if(returnsPublisher) { return (Publisher<T>) result; } else { return Mono.just((T)result).doAfterTerminate(() -> instanceHolders.forEach(InstanceHolder::destroy)); } } catch (IllegalAccessException | InvocationTargetException e) { return Mono.fromSupplier(() -> { throw new RuntimeException(e); }); } finally { eventReceiver.destroy(); } }
public CDINotifyUpdate( FileSystemIO delegate, Map<String, Object> env ) { super( delegate, (OverlaySender) pathName -> { FileSystem fs = (FileSystem) env.get( FileSystem.class.getName() ); if( fs != null ) { if( fs instanceof AbstractFileSystem ) { Path path = ((AbstractFileSystem) fs).createPath( pathName ); CDI.current().getBeanManager().fireEvent( (PathUpdated) () -> path ); } } } ); }