Search in sources :

Example 16 with Singleton

use of jakarta.inject.Singleton in project glassfish-hk2 by eclipse-ee4j.

the class ServiceLocatorUtilitiesTest method testFindOrCreateWithServiceInLocator.

/**
 * Since SimpleService8 is in Singleton context, we can tell if it is coming from
 * the context if it is the same on two lookups
 */
@Test
public void testFindOrCreateWithServiceInLocator() {
    ServiceLocator locator = uniqueCreate();
    ServiceLocatorUtilities.addOneDescriptor(locator, BuilderHelper.link(SimpleService8.class).in(Singleton.class.getName()).build());
    SimpleService8 one = ServiceLocatorUtilities.findOrCreateService(locator, SimpleService8.class);
    Assert.assertNotNull(one);
    SimpleService8 two = ServiceLocatorUtilities.findOrCreateService(locator, SimpleService8.class);
    Assert.assertNotNull(two);
    Assert.assertEquals(one, two);
}
Also used : ServiceLocator(org.glassfish.hk2.api.ServiceLocator) Singleton(jakarta.inject.Singleton) Test(org.junit.Test)

Example 17 with Singleton

use of jakarta.inject.Singleton in project glassfish-hk2 by eclipse-ee4j.

the class ServiceLocatorTestRule method configureServiceLocator.

/**
 * Configures the supplied {@link ServiceLocator} for use by the
 * test described by the supplied {@link Description}.
 *
 * <p>This implementation:</p>
 *
 * <ol>
 *
 * <li>Adds the {@link ErrorServiceImpl} class to the supplied
 * {@link ServiceLocator} so that exceptions will be thrown from
 * tests</li>
 *
 * <li>Removes, via {@link
 * DynamicConfiguration#addUnbindFilter(Filter)}, all {@link
 * Descriptor}s that have {@link Description Description.class} as
 * one of their {@linkplain Descriptor#getAdvertisedContracts()
 * contracts}</li>
 *
 * <li>Adds a {@linkplain
 * BuilderHelper#createConstantDescriptor(Object) constant
 * descriptor} in {@link Singleton} scope with a {@linkplain
 * Descriptor#getName() name} equal to the return value of the
 * {@link Description#getDisplayName()} method for the supplied
 * {@link Description} so that the current test can inject the
 * {@link Description} for the current method if it wishes</li>
 *
 * <li>{@linkplain DynamicConfiguration#addActiveDescriptor(Class)
 * Adds any classes} found in an optional {@link Classes} annotation
 * decorating the test class&mdash;if they are assignable to {@link
 * Factory Factory.class} then they are {@linkplain
 * DynamicConfiguration#addActiveFactoryDescriptor(Class) added as
 * factories}</li>
 *
 * <li>Adds any classes found in any packages listed in an optional
 * {@link Packages} annotation decorating the test class, provided
 * they are annotated with {@link Service}</li>
 *
 * <li>Reads any locator files listed in an optional {@link
 * InhabitantFiles} annotation decorating the test class and adds
 * the services listed therein</li>
 *
 * <li>Calls the {@link #bind(DynamicConfiguration)} method</li>
 *
 * <li>Calls the {@link Binder#bind(DynamicConfiguration)} method on
 * the test if it is in fact an instance of {@link Binder}</li>
 *
 * </ol>
 *
 * @param serviceLocator the {@link ServiceLocator} to configure;
 * must not be {@code null}
 *
 * @param testDescription the {@link Description} describing the
 * particular test being run; must not be {@code null}
 *
 * @exception AssertionError if either {@code serviceLocator} or
 * {@code testDescription} is {@code null}
 *
 * @exception IOException if there was an error looking for classes
 * in packages or finding or reading locator files
 */
protected void configureServiceLocator(final ServiceLocator serviceLocator, final Description testDescription) throws IOException {
    assertNotNull(serviceLocator);
    assertNotNull(testDescription);
    final Class<?> testClass = testDescription.getTestClass();
    if (testClass != null) {
        final DynamicConfigurationService dynamicConfigurationService = serviceLocator.getService(DynamicConfigurationService.class);
        assertNotNull(dynamicConfigurationService);
        final DynamicConfiguration dynamicConfiguration = dynamicConfigurationService.createDynamicConfiguration();
        assertNotNull(dynamicConfiguration);
        dynamicConfiguration.addActiveDescriptor(ErrorServiceImpl.class);
        final Filter unbindFilter = BuilderHelper.createContractFilter(Description.class.getName());
        assertNotNull(unbindFilter);
        dynamicConfiguration.addUnbindFilter(unbindFilter);
        final AbstractActiveDescriptor<?> descriptionDescriptor = BuilderHelper.createConstantDescriptor(testDescription);
        assertNotNull(descriptionDescriptor);
        descriptionDescriptor.setName(testDescription.getDisplayName());
        descriptionDescriptor.setScope(Singleton.class.getName());
        dynamicConfiguration.addActiveDescriptor(descriptionDescriptor);
        this.bind(dynamicConfiguration, this.getClass());
        this.bind(dynamicConfiguration, testClass);
        this.bind(dynamicConfiguration);
        if (this.test instanceof Binder) {
            ((Binder) this.test).bind(dynamicConfiguration);
        }
        dynamicConfiguration.commit();
    }
}
Also used : Binder(org.glassfish.hk2.utilities.Binder) DynamicConfigurationService(org.glassfish.hk2.api.DynamicConfigurationService) Description(org.junit.runner.Description) DynamicConfiguration(org.glassfish.hk2.api.DynamicConfiguration) Filter(org.glassfish.hk2.api.Filter) FilenameFilter(java.io.FilenameFilter) Singleton(jakarta.inject.Singleton)

Example 18 with Singleton

use of jakarta.inject.Singleton in project glassfish-hk2 by eclipse-ee4j.

the class ClassVisitorImpl method visitEnd.

/* (non-Javadoc)
     * @see org.objectweb.asm.ClassVisitor#visitEnd()
     */
@Override
public void visitEnd() {
    if (!isAService) {
        if (decorateData != null) {
            String with = decorateData.getWith();
            GenerateMethodAnnotationData gbad = classLevelGenerators.get(with);
            if (gbad != null) {
                DescriptorImpl generatedDescriptor = new DescriptorImpl();
                generatedDescriptor.setImplementation(gbad.getImplementation());
                for (String contract : gbad.getContracts()) {
                    generatedDescriptor.addAdvertisedContract(contract);
                }
                if (gbad.getName() != null) {
                    generatedDescriptor.setName(gbad.getName());
                }
                generatedDescriptor.addMetadata(METHOD_ACTUAL, implName);
                generatedDescriptor.addMetadata(METHOD_NAME, decorateData.getMethodName());
                generatedDescriptor.addMetadata(PARENT_CONFIGURED, decorateData.getTargetType());
                if (verbose) {
                    System.out.println("Generated Descriptor for class-level GenerateServiceFromMethod annotation: " + generatedDescriptor);
                }
                ;
                generatedDescriptors.add(generatedDescriptor);
                return;
            }
        }
        if (verbose) {
            System.out.println("Class " + implName + " is not annotated with @Service");
        }
        return;
    }
    DescriptorImpl generatedDescriptor = new DescriptorImpl();
    generatedDescriptor.setImplementation(implName);
    if (scopeClass == null) {
        // The default for classes with Service is Singleton
        generatedDescriptor.setScope(Singleton.class.getName());
    } else {
        generatedDescriptor.setScope(scopeClass);
    }
    if (providedContracts != null) {
        for (String providedContract : providedContracts) {
            generatedDescriptor.addAdvertisedContract(providedContract);
        }
    } else {
        generatedDescriptor.addAdvertisedContract(implName);
        for (String iFace : iFaces) {
            generatedDescriptor.addAdvertisedContract(iFace);
        }
    }
    for (String qualifier : qualifiers) {
        generatedDescriptor.addQualifier(qualifier);
    }
    if (baseName != null) {
        generatedDescriptor.setName(baseName.getName());
    }
    generatedDescriptor.setClassAnalysisName(classAnalyzer);
    if (metadataString != null) {
        Map<String, List<String>> serviceMetadata = new HashMap<String, List<String>>();
        ReflectionHelper.parseServiceMetadataString(metadataString, serviceMetadata);
        generatedDescriptor.addMetadata(serviceMetadata);
    }
    if (rank != null) {
        generatedDescriptor.setRanking(rank.intValue());
    }
    if (useProxy != null) {
        generatedDescriptor.setProxiable(useProxy);
    }
    generatedDescriptor.setDescriptorVisibility(visibility);
    if (!metadata.isEmpty()) {
        for (Map.Entry<String, List<String>> entry : metadata.entrySet()) {
            String key = entry.getKey();
            List<String> values = entry.getValue();
            for (String value : values) {
                generatedDescriptor.addMetadata(key, value);
            }
        }
    }
    if (verbose) {
        System.out.println("Generated Descriptor: " + generatedDescriptor);
    }
    generatedDescriptors.add(generatedDescriptor);
}
Also used : HashMap(java.util.HashMap) DescriptorImpl(org.glassfish.hk2.utilities.DescriptorImpl) Singleton(jakarta.inject.Singleton) List(java.util.List) LinkedList(java.util.LinkedList) HashMap(java.util.HashMap) Map(java.util.Map)

Example 19 with Singleton

use of jakarta.inject.Singleton in project glassfish-hk2 by eclipse-ee4j.

the class DescriptorImplTest method testReadAndWriteExternal.

/**
 * Tests the read and write external form of DescriptorImpl
 *
 * @throws IOException
 */
@Test
public void testReadAndWriteExternal() throws IOException {
    DescriptorImpl writeA = BuilderHelper.createDescriptorFromClass(WriteServiceA.class);
    DescriptorImpl writeB = BuilderHelper.createDescriptorFromClass(WriteServiceB.class);
    writeB.addMetadata(FullDescriptorImpl.FULL_KEY1, FullDescriptorImpl.FULL_VALUE1);
    writeB.addMetadata(FullDescriptorImpl.FULL_KEY2, FullDescriptorImpl.FULL_VALUE1);
    writeB.addMetadata(KEY_WITH_ESCAPED_CHARACTERS, ESCAPED_VALUE);
    writeB.addMetadata(KEY_WITH_ESCAPED_CHARACTERS, NON_ESCAPED_VALUE);
    writeB.addMetadata(FullDescriptorImpl.FULL_KEY2, FullDescriptorImpl.FULL_VALUE2);
    writeB.setRanking(13);
    // Write out a completely empty one
    DescriptorImpl writeC = new DescriptorImpl();
    // Write out ones that use directives
    DescriptorImpl singletonOnlyContract = new DescriptorImpl();
    singletonOnlyContract.setImplementation(DescriptorImplTest.class.getName());
    singletonOnlyContract.addAdvertisedContract(DescriptorImplTest.class.getName());
    singletonOnlyContract.setScope(Singleton.class.getName());
    // This one has a set of contracts that does NOT contain the implementation
    DescriptorImpl implNotInContractsPerLookup = new DescriptorImpl();
    implNotInContractsPerLookup.setImplementation(DescriptorImplTest.class.getName());
    implNotInContractsPerLookup.addAdvertisedContract(String.class.getName());
    // This one has a set of contracts that does NOT contain the implementation and is singleton
    DescriptorImpl implNotInContractsSingleton = new DescriptorImpl();
    implNotInContractsSingleton.setImplementation(DescriptorImplTest.class.getName());
    implNotInContractsSingleton.addAdvertisedContract(String.class.getName());
    implNotInContractsSingleton.setScope(Singleton.class.getName());
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    PrintWriter pw = new PrintWriter(baos);
    pw.println("# I can have a comment at the start of the file");
    writeA.writeObject(pw);
    pw.println("# I can add a comment");
    writeB.writeObject(pw);
    pw.println("# I can add a multi-line comment");
    pw.println("# that has multiple lines");
    writeC.writeObject(pw);
    singletonOnlyContract.writeObject(pw);
    implNotInContractsPerLookup.writeObject(pw);
    implNotInContractsSingleton.writeObject(pw);
    pw.println("# I can add a comment and the end of the file");
    pw.close();
    baos.close();
    // System.out.println(new String(baos.toByteArray()));
    ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
    BufferedReader br = new BufferedReader(new InputStreamReader(bais));
    int lcv = 0;
    while (br.ready()) {
        DescriptorImpl di = new DescriptorImpl();
        if (!di.readObject(br)) {
            continue;
        }
        if (lcv == 0) {
            Assert.assertEquals(writeA, di);
            Assert.assertEquals(writeA.hashCode(), di.hashCode());
        } else if (lcv == 1) {
            Assert.assertEquals(writeB, di);
            Assert.assertEquals(writeB.hashCode(), di.hashCode());
            // Ranking is not considered in equals, but should have been written out
            Assert.assertEquals(13, di.getRanking());
            Assert.assertEquals(Boolean.TRUE, di.isProxiable());
            Assert.assertEquals(Boolean.FALSE, di.isProxyForSameScope());
            // Additional tests for B, make sure the escaped characters are read back in properly
            String escapedValue = di.getMetadata().get(KEY_WITH_ESCAPED_CHARACTERS).get(0);
            Assert.assertEquals(ESCAPED_VALUE, escapedValue);
            String nonEscapedValue = di.getMetadata().get(KEY_WITH_ESCAPED_CHARACTERS).get(1);
            Assert.assertEquals(NON_ESCAPED_VALUE, nonEscapedValue);
        } else if (lcv == 2) {
            Assert.assertEquals(writeC, di);
            Assert.assertEquals(writeC.hashCode(), di.hashCode());
        } else if (lcv == 3) {
            Assert.assertEquals(singletonOnlyContract, di);
            Assert.assertEquals(singletonOnlyContract.hashCode(), di.hashCode());
        } else if (lcv == 4) {
            Assert.assertEquals(implNotInContractsPerLookup, di);
            Assert.assertEquals(implNotInContractsPerLookup.hashCode(), di.hashCode());
        } else if (lcv == 5) {
            Assert.assertEquals(implNotInContractsSingleton, di);
            Assert.assertEquals(implNotInContractsSingleton.hashCode(), di.hashCode());
        } else {
            Assert.fail("More descriptors were read than were written: " + di + " lcv=" + lcv);
        }
        lcv++;
    }
    Assert.assertEquals(6, lcv);
}
Also used : InputStreamReader(java.io.InputStreamReader) ByteArrayInputStream(java.io.ByteArrayInputStream) DescriptorImpl(org.glassfish.hk2.utilities.DescriptorImpl) Singleton(jakarta.inject.Singleton) BufferedReader(java.io.BufferedReader) ByteArrayOutputStream(java.io.ByteArrayOutputStream) PrintWriter(java.io.PrintWriter) Test(org.junit.Test)

Example 20 with Singleton

use of jakarta.inject.Singleton in project micronaut-views by micronaut-projects.

the class VelocityFactory method getVelocityEngine.

/**
 * @return The velocity engine
 */
@Singleton
public VelocityEngine getVelocityEngine() {
    final Properties p = new Properties();
    p.setProperty("resource.loaders", "class");
    p.setProperty("resource.loader.class.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
    return new VelocityEngine(p);
}
Also used : VelocityEngine(org.apache.velocity.app.VelocityEngine) Properties(java.util.Properties) Singleton(jakarta.inject.Singleton)

Aggregations

Singleton (jakarta.inject.Singleton)26 Bean (io.micronaut.context.annotation.Bean)7 Factory (io.micronaut.context.annotation.Factory)6 Properties (java.util.Properties)6 GraphQLSchema (graphql.schema.GraphQLSchema)5 BufferedReader (java.io.BufferedReader)5 InputStreamReader (java.io.InputStreamReader)5 GraphQL (graphql.GraphQL)4 RuntimeWiring (graphql.schema.idl.RuntimeWiring)4 SchemaGenerator (graphql.schema.idl.SchemaGenerator)4 SchemaParser (graphql.schema.idl.SchemaParser)4 TypeDefinitionRegistry (graphql.schema.idl.TypeDefinitionRegistry)4 ResourceResolver (io.micronaut.core.io.ResourceResolver)4 Named (jakarta.inject.Named)4 Test (org.junit.Test)3 ConfiguredStreamBuilder (io.micronaut.configuration.kafka.streams.ConfiguredStreamBuilder)2 ByteArrayInputStream (java.io.ByteArrayInputStream)2 Arrays (java.util.Arrays)2 Locale (java.util.Locale)2 ConsumerConfig (org.apache.kafka.clients.consumer.ConsumerConfig)2