io.micronaut.context.ApplicationContext Java Examples

The following examples show how to use io.micronaut.context.ApplicationContext. 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: AbstractMicronautLambdaRuntime.java    From micronaut-aws with Apache License 2.0 6 votes vote down vote up
/**
 *
 * @param value Object to be serialized
 * @return A JSON String of the supplied object
 */
@Nullable
protected String serializeAsJsonString(Object value) {
    if (value == null) {
        return null;
    }
    ApplicationContext applicationContext = getApplicationContext();
    if (applicationContext != null) {
        if (applicationContext.containsBean(ObjectMapper.class)) {
            ObjectMapper objectMapper = applicationContext.getBean(ObjectMapper.class);
            try {
                return objectMapper.writeValueAsString(value);
            } catch (JsonProcessingException e) {
                return null;
            }
        }
    }
    return null;
}
 
Example #2
Source File: AbstractMicronautLambdaRuntime.java    From micronaut-aws with Apache License 2.0 6 votes vote down vote up
/**
 *
 * @param content JSON String
 * @param valueType Class Type to be read into
 * @param <T> Type to be read into
 * @return a new Class build from the JSON String
 * @throws JsonProcessingException if underlying input contains invalid content
 * @throws JsonMappingException if the input JSON structure does not match structure
 *   expected for result type (or has other mismatch issues)
 */
@Nullable
protected <T> T valueFromContent(String content, Class<T> valueType) throws JsonProcessingException, JsonMappingException {
    if (content == null) {
        return null;
    }
    ApplicationContext applicationContext = getApplicationContext();
    if (applicationContext != null) {
        if (applicationContext.containsBean(ObjectMapper.class)) {
            ObjectMapper objectMapper = applicationContext.getBean(ObjectMapper.class);

            return objectMapper.readValue(content, valueType);
        }
    }
    return null;
}
 
Example #3
Source File: MicronautAwsProxyTest.java    From micronaut-aws with Apache License 2.0 6 votes vote down vote up
@Test
public void stripBasePath_route_shouldReturn404() throws ContainerInitializationException {
    MicronautLambdaContainerHandler handler = new MicronautLambdaContainerHandler(
            ApplicationContext.build(CollectionUtils.mapOf(
                    "spec.name", "MicronautAwsProxyTest",
                    "micronaut.security.enabled", false,
                    "micronaut.views.handlebars.enabled", true,
                    "micronaut.router.static-resources.lorem.paths", "classpath:static-lorem/",
                    "micronaut.router.static-resources.lorem.mapping", "/static-lorem/**"
            ))
    );
    handler.stripBasePath("/custom");
    try {
        AwsProxyRequest request = getRequestBuilder("/custompath/echo/status-code", "GET")
                .json()
                .queryString("status", "201")
                .build();
        AwsProxyResponse output = handler.proxy(request, lambdaContext);
        assertEquals(404, output.getStatusCode());
    } finally {

        handler.stripBasePath("");
    }
}
 
Example #4
Source File: GrpcEmbeddedServer.java    From micronaut-grpc with Apache License 2.0 6 votes vote down vote up
/**
 * Default constructor.
 * @param applicationContext The application context
 * @param applicationConfiguration The application configuration
 * @param grpcServerConfiguration The GRPC server configuration
 * @param serverBuilder The server builder
 * @param eventPublisher The event publisher
 * @param computeInstanceMetadataResolver The computed instance metadata
 * @param metadataContributors The metadata contributors
 */
@Internal
GrpcEmbeddedServer(
        @Nonnull ApplicationContext applicationContext,
        @Nonnull ApplicationConfiguration applicationConfiguration,
        @Nonnull GrpcServerConfiguration grpcServerConfiguration,
        @Nonnull ServerBuilder<?> serverBuilder,
        @Nonnull ApplicationEventPublisher eventPublisher,
        @Nullable ComputeInstanceMetadataResolver computeInstanceMetadataResolver,
        @Nullable List<ServiceInstanceMetadataContributor> metadataContributors) {
    ArgumentUtils.requireNonNull("applicationContext", applicationContext);
    ArgumentUtils.requireNonNull("applicationConfiguration", applicationConfiguration);
    ArgumentUtils.requireNonNull("grpcServerConfiguration", grpcServerConfiguration);
    this.applicationContext = applicationContext;
    this.configuration = applicationConfiguration;
    this.grpcConfiguration = grpcServerConfiguration;
    this.eventPublisher = eventPublisher;
    this.server = serverBuilder.build();
    this.computeInstanceMetadataResolver = computeInstanceMetadataResolver;
    this.metadataContributors = metadataContributors;
}
 
Example #5
Source File: MicronautAwsProxyTest.java    From micronaut-aws with Apache License 2.0 6 votes vote down vote up
@Test
public void error_statusCode_methodNotAllowed() throws ContainerInitializationException {
    MicronautLambdaContainerHandler handler = new MicronautLambdaContainerHandler(
            ApplicationContext.build(CollectionUtils.mapOf(
                    "spec.name", "MicronautAwsProxyTest",
                    "micronaut.security.enabled", false,
                    "micronaut.views.handlebars.enabled", true,
                    "micronaut.router.static-resources.lorem.paths", "classpath:static-lorem/",
                    "micronaut.router.static-resources.lorem.mapping", "/static-lorem/**"
            ))
    );
    AwsProxyRequest request = getRequestBuilder("/echo/status-code", "POST")
            .json()
            .queryString("status", "201")
            .build();

    AwsProxyResponse output = handler.proxy(request, lambdaContext);
    assertEquals(405, output.getStatusCode());
}
 
Example #6
Source File: MicronautAwsProxyTest.java    From micronaut-aws with Apache License 2.0 6 votes vote down vote up
@Test
public void errors_unknownRoute_expect404() throws ContainerInitializationException {
    MicronautLambdaContainerHandler handler = new MicronautLambdaContainerHandler(
            ApplicationContext.build(CollectionUtils.mapOf(
                    "spec.name", "MicronautAwsProxyTest",
                    "micronaut.security.enabled", false,
                    "micronaut.views.handlebars.enabled", true,
                    "micronaut.router.static-resources.lorem.paths", "classpath:static-lorem/",
                    "micronaut.router.static-resources.lorem.mapping", "/static-lorem/**"
            ))
    );
    AwsProxyRequest request = getRequestBuilder("/echo/test33", "GET").build();

    AwsProxyResponse output = handler.proxy(request, lambdaContext);
    assertEquals(404, output.getStatusCode());
}
 
Example #7
Source File: GrpcEmbeddedServer.java    From micronaut-grpc with Apache License 2.0 6 votes vote down vote up
/**
 * Default constructor.
 * @param applicationContext The application context
 * @param applicationConfiguration The application configuration
 * @param grpcServerConfiguration The GRPC server configuration
 * @param serverBuilder The server builder
 * @param eventPublisher The event publisher
 * @param computeInstanceMetadataResolver The computed instance metadata
 * @param metadataContributors The metadata contributors
 */
@Internal
GrpcEmbeddedServer(
        @Nonnull ApplicationContext applicationContext,
        @Nonnull ApplicationConfiguration applicationConfiguration,
        @Nonnull GrpcServerConfiguration grpcServerConfiguration,
        @Nonnull ServerBuilder<?> serverBuilder,
        @Nonnull ApplicationEventPublisher eventPublisher,
        @Nullable ComputeInstanceMetadataResolver computeInstanceMetadataResolver,
        @Nullable List<ServiceInstanceMetadataContributor> metadataContributors) {
    ArgumentUtils.requireNonNull("applicationContext", applicationContext);
    ArgumentUtils.requireNonNull("applicationConfiguration", applicationConfiguration);
    ArgumentUtils.requireNonNull("grpcServerConfiguration", grpcServerConfiguration);
    this.applicationContext = applicationContext;
    this.configuration = applicationConfiguration;
    this.grpcConfiguration = grpcServerConfiguration;
    this.eventPublisher = eventPublisher;
    this.server = serverBuilder.build();
    this.computeInstanceMetadataResolver = computeInstanceMetadataResolver;
    this.metadataContributors = metadataContributors;
}
 
Example #8
Source File: MicronautRequestHandler.java    From micronaut-aws with Apache License 2.0 6 votes vote down vote up
/**
 * Register the beans in the application.
 *
 * @param context context
 * @param applicationContext application context
 */
static void registerContextBeans(Context context, ApplicationContext applicationContext) {
    applicationContext.registerSingleton(context);
    LambdaLogger logger = context.getLogger();
    if (logger != null) {
        applicationContext.registerSingleton(logger);
    }
    ClientContext clientContext = context.getClientContext();
    if (clientContext != null) {
        applicationContext.registerSingleton(clientContext);
    }
    CognitoIdentity identity = context.getIdentity();
    if (identity != null) {
        applicationContext.registerSingleton(identity);
    }
}
 
Example #9
Source File: JpaConfiguration.java    From micronaut-sql with Apache License 2.0 5 votes vote down vote up
/**
 * @param applicationContext      The application context
 * @param integrator              The {@link Integrator}
 * @param entityScanConfiguration The entity scan configuration
 */
@Inject
protected JpaConfiguration(ApplicationContext applicationContext,
                           @Nullable Integrator integrator,
                           @Nullable EntityScanConfiguration entityScanConfiguration) {
    ClassLoader classLoader = applicationContext.getClassLoader();
    BootstrapServiceRegistryBuilder bootstrapServiceRegistryBuilder =
            createBootstrapServiceRegistryBuilder(integrator, classLoader);

    this.bootstrapServiceRegistry = bootstrapServiceRegistryBuilder.build();
    this.entityScanConfiguration = entityScanConfiguration != null ? entityScanConfiguration : new EntityScanConfiguration(applicationContext.getEnvironment());
    this.environment = applicationContext.getEnvironment();
    this.applicationContext = applicationContext;
}
 
Example #10
Source File: DocTests.java    From micronaut-kafka with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public static void setup() {
    kafkaContainer.start();
    applicationContext = ApplicationContext.run(
            CollectionUtils.mapOf(
                    "kafka.bootstrap.servers", kafkaContainer.getBootstrapServers()
        )
    );
}
 
Example #11
Source File: BookSenderTest.java    From micronaut-kafka with Apache License 2.0 5 votes vote down vote up
@Test
public void testBookSender() throws IOException {
    Map<String, Object> config = Collections.singletonMap( // <1>
            AbstractKafkaConfiguration.EMBEDDED, true
    );

    try (ApplicationContext ctx = ApplicationContext.run(config)) {
        BookSender bookSender = ctx.getBean(BookSender.class); // <2>
        Book book = new Book();
        book.setTitle("The Stand");
        bookSender.send("Stephen King", book);
    }
}
 
Example #12
Source File: BookRepositoryTest.java    From micronaut-data with Apache License 2.0 5 votes vote down vote up
@BeforeAll
void setup() {
    this.context = ApplicationContext.run();
    this.bookRepository = context.getBean(BookRepository.class);
    this.bookRepository.saveAll(Arrays.asList(
            new Book("The Stand", 1000),
            new Book("The Shining", 600),
            new Book("The Power of the Dog", 500),
            new Book("The Border", 700),
            new Book("Along Came a Spider", 300),
            new Book("Pet Cemetery", 400),
            new Book("A Game of Thrones", 900),
            new Book("A Clash of Kings", 1100)
    ));
}
 
Example #13
Source File: AlexaFunction.java    From micronaut-aws with Apache License 2.0 5 votes vote down vote up
/**
 * Builds a new builder.
 *
 * @return The {@link ApplicationContextBuilder}
 */
@SuppressWarnings("unchecked")
@NonNull
protected ApplicationContextBuilder newApplicationContextBuilder() {
    return ApplicationContext.build(Environment.FUNCTION, MicronautLambdaContext.ENVIRONMENT_LAMBDA, AlexaEnvironment.ENV_ALEXA)
            .eagerInitSingletons(true)
            .eagerInitConfiguration(true);
}
 
Example #14
Source File: MicronautRequestStreamHandler.java    From micronaut-aws with Apache License 2.0 5 votes vote down vote up
@Override
protected ApplicationContext buildApplicationContext(Context context) {
    ApplicationContext applicationContext = super.buildApplicationContext(context);
    if (context != null) {
        registerContextBeans(context, applicationContext);
        this.functionName = context.getFunctionName();
    }
    return applicationContext;
}
 
Example #15
Source File: LocalFunctionInvokeJavaSpec.java    From micronaut-aws with Apache License 2.0 5 votes vote down vote up
@Test
public void testInvokingALocalFunctionRX() {
    Sum sum = new Sum();
    sum.setA(5);
    sum.setB(10);

    EmbeddedServer server = ApplicationContext.run(EmbeddedServer.class);
    RxMathClient mathClient = server.getApplicationContext().getBean(RxMathClient.class);

    assertEquals(Long.valueOf(Integer.MAX_VALUE), mathClient.max().blockingGet());
    assertEquals(2, mathClient.rnd(1.6f).blockingGet().longValue());
    assertEquals(15, mathClient.sum(sum).blockingGet().longValue());

}
 
Example #16
Source File: AbstractMicronautLambdaRuntime.java    From micronaut-aws with Apache License 2.0 5 votes vote down vote up
/**
 * @param args command line arguments
 * @return An {@link ApplicationContextBuilder} with the command line arguments as a property source and the environment set to lambda
 */
public ApplicationContextBuilder createApplicationContextBuilderWithArgs(String... args) {
    CommandLine commandLine = CommandLine.parse(args);
    return ApplicationContext.build()
            .environments(MicronautLambdaContext.ENVIRONMENT_LAMBDA)
            .propertySources(new CommandLinePropertySource(commandLine));
}
 
Example #17
Source File: HelloWorldMicronautTest.java    From micronaut-aws with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public static void initializeServer() throws ContainerInitializationException {
    try {
        handler = new MicronautLambdaContainerHandler(
                ApplicationContext.build()
                        .properties(CollectionUtils.mapOf(
                                "spec.name", "HelloWorldMicronautTest"
                        ))
        );
    } catch (RuntimeException e) {
        e.printStackTrace();
        fail();
    }
}
 
Example #18
Source File: EmbeddedMain.java    From micronaut-kafka with Apache License 2.0 5 votes vote down vote up
public static void main(String...args) {
    ApplicationContext applicationContext = ApplicationContext.run(
            Collections.singletonMap(
                    AbstractKafkaConfiguration.EMBEDDED, true
            )
    , Environment.TEST);
    KafkaEmbedded embedded = applicationContext.getBean(KafkaEmbedded.class);
}
 
Example #19
Source File: SimpleQuery.java    From micronaut-data with Apache License 2.0 5 votes vote down vote up
@Setup
public void prepare() {
    this.applicationContext = ApplicationContext.build().packages("example").start();
    this.bookRepository = applicationContext.getBean(BookRepository.class);
    this.bookRepository.saveAll(Arrays.asList(
            new Book("The Stand", 1000),
            new Book("The Shining", 600),
            new Book("The Power of the Dog", 500),
            new Book("The Border", 700),
            new Book("Along Came a Spider", 300),
            new Book("Pet Cemetery", 400),
            new Book("A Game of Thrones", 900),
            new Book("A Clash of Kings", 1100)
    ));
}
 
Example #20
Source File: LocalFunctionInvokeJavaSpec.java    From micronaut-aws with Apache License 2.0 5 votes vote down vote up
@Test
public void testInvokingALocalFunction() {
    Sum sum = new Sum();
    sum.setA(5);
    sum.setB(10);

    EmbeddedServer server = ApplicationContext.run(EmbeddedServer.class);
    MathClient mathClient = server.getApplicationContext().getBean(MathClient.class);

    assertEquals(Long.valueOf(Integer.MAX_VALUE), mathClient.max());
    assertEquals(2, mathClient.rnd(1.6f));
    assertEquals(15, mathClient.sum(sum));

}
 
Example #21
Source File: SimpleQuery.java    From micronaut-data with Apache License 2.0 5 votes vote down vote up
@Setup
public void prepare() {
    this.applicationContext = ApplicationContext.build().packages("example").start();
    this.bookRepository = applicationContext.getBean(BookRepository.class);
    this.bookRepository.saveAll(Arrays.asList(
            new Book("The Stand", 1000),
            new Book("The Shining", 600),
            new Book("The Power of the Dog", 500),
            new Book("The Border", 700),
            new Book("Along Came a Spider", 300),
            new Book("Pet Cemetery", 400),
            new Book("A Game of Thrones", 900),
            new Book("A Clash of Kings", 1100)
    ));
}
 
Example #22
Source File: BookRepositoryTest.java    From micronaut-data with Apache License 2.0 5 votes vote down vote up
@BeforeAll
void setup() {
    this.context = ApplicationContext.run();
    this.bookRepository = context.getBean(BookRepository.class);
    this.bookRepository.saveAll(Arrays.asList(
            new Book("The Stand", 1000),
            new Book("The Shining", 600),
            new Book("The Power of the Dog", 500),
            new Book("The Border", 700),
            new Book("Along Came a Spider", 300),
            new Book("Pet Cemetery", 400),
            new Book("A Game of Thrones", 900),
            new Book("A Clash of Kings", 1100)
    ));
}
 
Example #23
Source File: TestContext.java    From micronaut-test with Apache License 2.0 5 votes vote down vote up
/**
 * @param applicationContext The application context
 * @param testClass The test class
 * @param testMethod The test method
 * @param testInstance The test instance
 * @param testException The exception thrown by the test execution
 */
public TestContext(
    final ApplicationContext applicationContext,
    final Class<?> testClass,
    final AnnotatedElement testMethod,
    final Object testInstance,
    final Throwable testException) {

  this.applicationContext = applicationContext;
  this.testClass = testClass;
  this.testException = testException;
  this.testInstance = testInstance;
  this.testMethod = testMethod;

}
 
Example #24
Source File: MicronautJunit5Extension.java    From micronaut-test with Apache License 2.0 5 votes vote down vote up
@Override
public void beforeAll(ExtensionContext extensionContext) throws Exception {
    final Class<?> testClass = extensionContext.getRequiredTestClass();
    final MicronautTest micronautTest = AnnotationSupport.findAnnotation(testClass, MicronautTest.class).orElse(null);
    beforeClass(extensionContext, testClass, micronautTest);
    getStore(extensionContext).put(ApplicationContext.class, applicationContext);
    if (specDefinition != null) {
        TestInstance ti = AnnotationSupport.findAnnotation(testClass, TestInstance.class).orElse(null);
        if (ti != null && ti.value() == TestInstance.Lifecycle.PER_CLASS) {
            Object testInstance = extensionContext.getRequiredTestInstance();
            applicationContext.inject(testInstance);
        }
    }
    beforeTestClass(buildContext(extensionContext));
}
 
Example #25
Source File: DataSourceMigrationRunner.java    From micronaut-flyway with Apache License 2.0 5 votes vote down vote up
/**
 * @param applicationContext The application context
 * @param eventPublisher     The event publisher
 * @param dataSourceResolver The data source resolver
 */
public DataSourceMigrationRunner(ApplicationContext applicationContext,
                                 ApplicationEventPublisher eventPublisher,
                                 @Nullable DataSourceResolver dataSourceResolver) {
    super(applicationContext, eventPublisher);
    this.dataSourceResolver = dataSourceResolver != null ? dataSourceResolver : DataSourceResolver.DEFAULT;
}
 
Example #26
Source File: Registry.java    From micronaut-microservices-poc with Apache License 2.0 5 votes vote down vote up
public Registry(ApplicationContext applicationContext) {
    Collection<BeanDefinition<CommandHandler>> commandHandlers = applicationContext.getBeanDefinitions(CommandHandler.class);
    commandHandlers.forEach(x -> registerCommand(applicationContext, x));

    Collection<BeanDefinition<QueryHandler>> queryHandlers = applicationContext.getBeanDefinitions(QueryHandler.class);
    queryHandlers.forEach(x -> registerQuery(applicationContext, x));
}
 
Example #27
Source File: GrpcChannelBuilderFactory.java    From micronaut-grpc with Apache License 2.0 5 votes vote down vote up
/**
 * Default constructor.
 * @param beanContext The bean context
 * @param executorService The I/O executor service
 */
public GrpcChannelBuilderFactory(
        ApplicationContext beanContext,
        @javax.inject.Named(TaskExecutors.IO) ExecutorService executorService) {
    this.beanContext = beanContext;
    this.executorService = executorService;
}
 
Example #28
Source File: Bootstrap.java    From vlingo-examples with Mozilla Public License 2.0 5 votes vote down vote up
public static Bootstrap instance() {
    if (instance == null) {
        final ApplicationContext applicationContext = Bootstrap.run();

        instance = new Bootstrap(applicationContext.getBean(VlingoServer.class));
    }
    return instance;
}
 
Example #29
Source File: Bootstrap.java    From vlingo-examples with Mozilla Public License 2.0 5 votes vote down vote up
public static Bootstrap instance() {
    if (instance == null) {
        final ApplicationContext applicationContext = Bootstrap.run();

        instance = new Bootstrap(applicationContext.getBean(VlingoServer.class));
    }
    return instance;
}
 
Example #30
Source File: Bootstrap.java    From vlingo-examples with Mozilla Public License 2.0 5 votes vote down vote up
public static Bootstrap instance() {
    if (instance == null) {
        final ApplicationContext applicationContext = run();

        final VlingoServer vlingoServer =
                applicationContext.getBean(VlingoServer.class);

        instance = new Bootstrap(vlingoServer);
    }
    return instance;
}