public static void main(String[] args) { WeldContainer weldContainer = new Weld().initialize(); Car car = weldContainer.instance().select(Car.class).get(); weldContainer.instance().select(PoliceStation.class).get(); weldContainer.instance().select(AARoadsideAssistant.class).get(); car.getDriver().drive(); }
/** Shuts down all the containers initialized by this builder. */ public void shutdown() { if (!initializedContainers.isEmpty()) { for (WeldContainer container : initializedContainers.values()) { container.shutdown(); } } }
@Override public String execute(CliContext context) { StringBuffer result = new StringBuffer(); WeldContainer container = context.getContainer(); RepositoryService repositoryService = container.instance().select(RepositoryService.class).get(); InputReader input = context.getInput(); System.out.print(">>Repository alias:"); String alias = input.nextLine(); Repository repo = repositoryService.getRepository(alias); if (repo == null) { return "No repository " + alias + " was found"; } System.out.print(">>Security groups (comma separated list):"); String groupsIn = input.nextLine(); if (groupsIn.trim().length() > 0) { String[] groups = groupsIn.split(","); for (String group : groups) { if (repo.getGroups().contains(group)) { continue; } repositoryService.addGroup(repo, group); result.append( "Group " + group + " added successfully to repository " + repo.getAlias() + "\n"); } } return result.toString(); }
@Override @SuppressWarnings("unchecked") public JCDIInjectionContext createManagedObject( Class managedClass, BundleDescriptor bundle, boolean invokePostConstruct) { JCDIInjectionContext context = null; Object managedObject = null; try { managedObject = createEEManagedObject(bundle.getManagedBeanByBeanClass(managedClass.getName())); } catch (Exception e) { e.printStackTrace(); } WeldContainer wc = getWeldContainer(); if (wc != null) { BeanManager beanManager = wc.getBeanManager(); AnnotatedType annotatedType = beanManager.createAnnotatedType(managedClass); InjectionTarget target = beanManager.createInjectionTarget(annotatedType); CreationalContext cc = beanManager.createCreationalContext(null); target.inject(managedObject, cc); if (invokePostConstruct) { target.postConstruct(managedObject); } context = new JCDIInjectionContextImpl(target, cc, managedObject); } return context; }
@Override public String execute(CliContext context) { StringBuffer result = new StringBuffer(); WeldContainer container = context.getContainer(); OrganizationalUnitService organizationalUnitService = container.instance().select(OrganizationalUnitService.class).get(); InputReader input = context.getInput(); System.out.print(">>Organizational Unit name:"); String name = input.nextLine(); OrganizationalUnit organizationalUnit = organizationalUnitService.getOrganizationalUnit(name); if (organizationalUnit == null) { return "No Organizational Unit " + name + " was found"; } System.out.print(">>Security roles (comma separated list):"); String rolesIn = input.nextLine(); if (rolesIn.trim().length() > 0) { String[] roles = rolesIn.split(","); for (String role : roles) { organizationalUnitService.removeRole(organizationalUnit, role); result.append( "Role " + role + " removed successfully from Organizational Unit " + organizationalUnit.getName() + "\n"); } } return result.toString(); }
public static void main(String[] args) { // TODO Auto-generated method stub Weld weld = new Weld(); WeldContainer container = weld.initialize(); BookService bookService = container.instance().select(BookService.class).get(); System.out.println("Запсукаемся..."); bookService.test(); }
@Before public void setUp() { WeldContainer container = new Weld().initialize(); this.keeper = container.instance().select(Keeper.class).get(); this.manager = container.instance().select(EntityManager.class).get(); this.transaction = this.manager.getTransaction(); this.transaction.begin(); }
@Test public void shouldCheckNumberIsMOCK() { Weld weld = new Weld(); WeldContainer container = weld.initialize(); BookService bookService = container.instance().select(BookService.class).get(); Book book = bookService.createBook("title", 19.99F, "best book"); Assert.assertTrue(book.getNumber().startsWith("Mock")); }
@Test public void test() { WeldContainer weld = new Weld().initialize(); Instance<CalculatorService> instance = weld.instance().select(CalculatorService.class); CalculatorService service = instance.get(); assertEquals(21, service.sum(Arrays.asList(1, 2, 3, 4, 5, 6))); double resultDiv = service.div(42.0, 2.0); assertEquals(21.0, resultDiv, 0.0001); }
@Override public void run() { for (String id : getRunningContainerIds()) { WeldContainer container = instance(id); if (container != null) { container.shutdown(); // At this time the logger service may not be available - print some basic info to the // standard output System.out.println(String.format("Weld SE container %s shut down by shutdown hook", id)); } } }
void createInstance(Class type) { WeldContainer weld = new Weld() .disableDiscovery() .extensions(new Fabric8Extension()) .beanClasses(MyFactory.class, MyBean.class) .initialize(); CreationalContext ctx = weld.getBeanManager().createCreationalContext(null); for (Bean bean : weld.getBeanManager().getBeans(type)) { weld.getBeanManager().getReference(bean, type, ctx); } }
@Override @SuppressWarnings("unchecked") public void injectManagedObject(Object managedObject, BundleDescriptor bundle) { WeldContainer wc = getWeldContainer(); if (wc != null) { BeanManager beanManager = wc.getBeanManager(); AnnotatedType annotatedType = beanManager.createAnnotatedType(managedObject.getClass()); InjectionTarget target = beanManager.createInjectionTarget(annotatedType); CreationalContext cc = beanManager.createCreationalContext(null); target.inject(managedObject, cc); } }
public static void main(String[] args) { // MyFactory m = MyFactory.getInstance(); // MyService service = m.getMyServiceImpl(); Weld weld = new Weld(); WeldContainer container = weld.initialize(); MyService service = container.select(MyService.class).get(); System.out.println(service.getValue()); Scanner s = new Scanner(System.in); s.nextInt(); container.shutdown(); }
@Test public void shouldCheckNumberIsThirteenDigits() { LibroService36 bookService = container.instance().select(LibroService36.class).get(); Libro36 book = bookService.createBook("H2G2", 12.5f, "Geeky scifi Book"); assertTrue(book.getIsbn().startsWith("8")); bookService.deleteBook(book); }
public void startUp() { // As per BRDRLPersistence.marshalRHS() String dateFormatProperty = System.getProperty("drools.dateformat"); if (dateFormatProperty == null || dateFormatProperty.length() == 0) System.setProperty("drools.dateformat", "dd-MM-yyyy"); weld = new Weld(); weldContainer = weld.initialize(); exporter = weldContainer.instance().select(JcrExporter.class).get(); }
@Override public String execute(CliContext context) { StringBuffer result = new StringBuffer(); WeldContainer container = context.getContainer(); OrganizationalUnitService organizationalUnitService = container.instance().select(OrganizationalUnitService.class).get(); RepositoryService repositoryService = container.instance().select(RepositoryService.class).get(); InputReader input = context.getInput(); System.out.print(">>Organizational Unit name:"); String name = input.nextLine(); System.out.print(">>Organizational Unit owner:"); String owner = input.nextLine(); System.out.print(">>Default Group Id for this Organizational Unit:"); String defaultGroupId = input.nextLine(); System.out.print(">>Repositories (comma separated list):"); String repos = input.nextLine(); Collection<Repository> repositories = new ArrayList<Repository>(); if (repos != null && repos.trim().length() > 0) { String[] repoAliases = repos.split(","); for (String alias : repoAliases) { Repository repo = repositoryService.getRepository(alias); if (repo != null) { repositories.add(repo); } else { System.out.println( "WARN: Repository with alias " + alias + " does not exists and will be skipped"); } } } OrganizationalUnit organizationalUnit = organizationalUnitService.createOrganizationalUnit( name, owner, defaultGroupId, repositories); result.append("Organizational Unit " + organizationalUnit.getName() + " successfully created"); return result.toString(); }
@Test public void testGo() { Weld w = new Weld(); WeldContainer wc = w.initialize(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(baos); CDIInstanceExample bean = wc.instance().select(CDIInstanceExample.class).get(); bean.go(ps); ps.close(); String actual = new String(baos.toByteArray()); String expected = "" + "Dave: Hello, HAL. Do you read me, HAL?" + NL + "HAL: Dave. I read you." + NL; assertEquals(expected, actual); w.shutdown(); }
@Test @Ignore public void test1() { final List<String> classes = new ArrayList<String>(); classes.add(TestClass.class.getName()); classes.add(TestClassImpl.class.getName()); Weld weldContainer = new Weld() { @Override protected Deployment createDeployment( ResourceLoader resourceLoader, Bootstrap bootstrap) { return new TestWeldSEDeployment(resourceLoader, bootstrap, classes); } }; WeldContainer weld = weldContainer.initialize(); TestClass bean = weld.instance().select(TestClass.class).get(); System.out.println(bean.getKBase1()); }
@Override public <T> T createInterceptorInstance(Class<T> interceptorClass, BundleDescriptor bundle) { T interceptorInstance = null; WeldContainer wc = getWeldContainer(); if (wc != null) { BeanManager beanManager = wc.getBeanManager(); AnnotatedType annotatedType = beanManager.createAnnotatedType(interceptorClass); InjectionTarget target = ((WeldManager) beanManager) .getInjectionTargetFactory(annotatedType) .createInterceptorInjectionTarget(); CreationalContext cc = beanManager.createCreationalContext(null); interceptorInstance = (T) target.produce(cc); target.inject(interceptorInstance, cc); } return interceptorInstance; }
/** * Bootstraps a new Weld SE container with the current {@link #containerId}. * * <p>The container must be shut down properly when an application is stopped. Applications are * encouraged to use the try-with-resources statement or invoke {@link WeldContainer#shutdown()} * explicitly. * * <p>However, a shutdown hook is also registered during initialization so that all running * containers are shut down automatically when a program exits or VM is terminated. This means * that it's not necessary to implement the shutdown logic in a class where a main method is used * to start the container. * * @return the Weld container * @see #enableDiscovery() * @see WeldContainer#shutdown() */ public WeldContainer initialize() { // If also building a synthetic bean archive the check for beans.xml is not necessary if (!isSyntheticBeanArchiveRequired() && resourceLoader.getResource(WeldDeployment.BEANS_XML) == null) { throw CommonLogger.LOG.missingBeansXml(); } final WeldBootstrap bootstrap = new WeldBootstrap(); final Deployment deployment = createDeployment(resourceLoader, bootstrap); final ExternalConfigurationBuilder configurationBuilder = new ExternalConfigurationBuilder() // weld-se uses CommonForkJoinPoolExecutorServices by default .add(EXECUTOR_THREAD_POOL_TYPE.get(), COMMON.toString()) // weld-se uses relaxed construction by default .add(ConfigurationKey.RELAXED_CONSTRUCTION.get(), true); for (Entry<String, Object> property : properties.entrySet()) { configurationBuilder.add(property.getKey(), property.getValue()); } deployment.getServices().add(ExternalConfiguration.class, configurationBuilder.build()); // Set up the container bootstrap.startContainer(containerId, Environments.SE, deployment); // Start the container bootstrap.startInitialization(); // Bean builders - set bean deployment finder if (!beanBuilders.isEmpty()) { BeanDeploymentFinder beanDeploymentFinder = bootstrap.getBeanDeploymentFinder(); for (BeanBuilderImpl<?> beanBuilder : beanBuilders) { beanBuilder.setBeanDeploymentFinder(beanDeploymentFinder); } } bootstrap.deployBeans(); bootstrap.validateBeans(); bootstrap.endInitialization(); final WeldManager manager = bootstrap.getManager(deployment.loadBeanDeploymentArchive(WeldContainer.class)); final WeldContainer weldContainer = WeldContainer.initialize(containerId, manager, bootstrap); initializedContainers.put(containerId, weldContainer); return weldContainer; }
@Test public void createMultpleJarAndFileResources() throws IOException, ClassNotFoundException, InterruptedException { createKProjectJar("jar1", true); createKProjectJar("jar2", true); createKProjectJar("jar3", true); createKProjectJar("fol4", false); ClassLoader origCl = Thread.currentThread().getContextClassLoader(); try { java.io.File file1 = fileManager.newFile("jar1.jar"); java.io.File file2 = fileManager.newFile("jar2.jar"); java.io.File file3 = fileManager.newFile("jar3.jar"); java.io.File fol4 = fileManager.newFile("fol4"); URLClassLoader urlClassLoader = new URLClassLoader( new URL[] { file1.toURI().toURL(), file2.toURI().toURL(), file3.toURI().toURL(), fol4.toURI().toURL() }); Thread.currentThread().setContextClassLoader(urlClassLoader); Enumeration<URL> e = urlClassLoader.getResources("META-INF/kproject.xml"); while (e.hasMoreElements()) { URL url = e.nextElement(); System.out.println(url); } Class cls = Thread.currentThread() .getContextClassLoader() .loadClass("org.drools.cdi.test.KProjectTestClassjar1"); assertNotNull(cls); cls = Thread.currentThread() .getContextClassLoader() .loadClass("org.drools.cdi.test.KProjectTestClassjar2"); assertNotNull(cls); cls = Thread.currentThread() .getContextClassLoader() .loadClass("org.drools.cdi.test.KProjectTestClassjar3"); assertNotNull(cls); Weld weldContainer = new Weld(); WeldContainer weld = weldContainer.initialize(); Set<Bean<?>> beans = weld.getBeanManager().getBeans(KProjectTestClass.class, new KPTestLiteral("jar1")); Bean bean = (Bean) beans.toArray()[0]; KProjectTestClass o1 = (KProjectTestClass) bean.create(weld.getBeanManager().createCreationalContext(null)); assertNotNull(o1); testEntry(o1, "jar1"); beans = weld.getBeanManager().getBeans(KProjectTestClass.class, new KPTestLiteral("jar2")); bean = (Bean) beans.toArray()[0]; KProjectTestClass o2 = (KProjectTestClass) bean.create(weld.getBeanManager().createCreationalContext(null)); assertNotNull(o2); testEntry(o2, "jar2"); beans = weld.getBeanManager().getBeans(KProjectTestClass.class, new KPTestLiteral("jar3")); bean = (Bean) beans.toArray()[0]; KProjectTestClass o3 = (KProjectTestClass) bean.create(weld.getBeanManager().createCreationalContext(null)); assertNotNull(o3); testEntry(o3, "jar3"); beans = weld.getBeanManager().getBeans(KProjectTestClass.class, new KPTestLiteral("fol4")); bean = (Bean) beans.toArray()[0]; KProjectTestClass o4 = (KProjectTestClass) bean.create(weld.getBeanManager().createCreationalContext(null)); assertNotNull(o4); testEntry(o4, "fol4"); weldContainer.shutdown(); } finally { Thread.currentThread().setContextClassLoader(origCl); } }
@Override public String execute(CliContext context) { StringBuffer result = new StringBuffer(); WeldContainer container = context.getContainer(); OrganizationalUnitService organizationalUnitService = container.instance().select(OrganizationalUnitService.class).get(); RepositoryService repositoryService = container.instance().select(RepositoryService.class).get(); ExplorerService projectExplorerService = container.instance().select(ExplorerService.class).get(); InputReader input = context.getInput(); System.out.print(">>Repository alias:"); String alias = input.nextLine(); Repository repo = repositoryService.getRepository(alias); if (repo == null) { return "No repository " + alias + " was found"; } OrganizationalUnit ou = null; Collection<OrganizationalUnit> units = organizationalUnitService.getOrganizationalUnits(); for (OrganizationalUnit unit : units) { if (unit.getRepositories().contains(repo)) { ou = unit; break; } } if (ou == null) { return "Could not find Organizational Unit containing repository. Unable to proceed."; } ArrayList<Project> projects = new ArrayList<Project>(); ProjectExplorerContentQuery query = new ProjectExplorerContentQuery(ou, repo, "master"); query.setOptions(new ActiveOptions()); ProjectExplorerContent content = projectExplorerService.getContent(query); projects.addAll(content.getProjects()); if (projects.size() == 0) { return "No projects found in repository " + alias; } int projectIndex = 0; while (projectIndex == 0) { System.out.println(">>Select project:"); for (int i = 0; i < projects.size(); i++) { System.out.println((i + 1) + ") " + projects.get(i).getProjectName()); } try { projectIndex = Integer.parseInt(input.nextLine()); } catch (NumberFormatException e) { System.out.println("Invalid index"); } if (projectIndex < 1 || projectIndex > projects.size()) { projectIndex = 0; System.out.println("Invalid index"); } } Project project = projects.get(projectIndex - 1); result.append("\tProject " + project.getProjectName() + "\n"); result.append("\t Modules: " + project.getModules() + "\n"); result.append("\t Root path: " + project.getRootPath().toURI() + "\n"); result.append("\t Pom path: " + project.getPomXMLPath().toURI() + "\n"); return result.toString(); }
@Override protected Object createTest() throws Exception { return container.instance().select(klass).get(); }
@Before public void init() { this.localeProvider = container.instance().select(LocaleProvider.class).get(); this.localeProvider.setCurrentLocale(expected.getLocale()); this.bean = container.instance().select(TestBean.class).get(); }
@Override public ArtifactLoader produce(final Dependencies dependencies, final PropertyLookup properties) { return new CdiArtifactLoader(container.getBeanManager()); }
@Override protected void visitJobOperatorModel(final JobOperatorModel model) throws Exception { super.visitJobOperatorModel(model); model.getArtifactLoaders().add().setValue(new CdiArtifactLoader(container.getBeanManager())); }