Java源码示例:io.micronaut.context.ApplicationContext
示例1
@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());
}
示例2
@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());
}
示例3
@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("");
}
}
示例4
/**
*
* @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;
}
示例5
/**
*
* @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;
}
示例6
/**
* 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);
}
}
示例7
/**
* 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;
}
示例8
/**
* 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;
}
示例9
@Override
protected void startThis(ApplicationContext applicationContext) {
final long time = System.currentTimeMillis();
try {
super.startThis(applicationContext);
} finally {
if (LOG.isInfoEnabled()) {
LOG.info("Initialized function in: " + (System.currentTimeMillis() - time) + "ms");
}
}
}
示例10
@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));
}
示例11
@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());
}
示例12
/**
* 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);
}
示例13
/**
*
* @return returns the current application context or starts a new one.
*/
@NonNull
protected ApplicationContext buildApplicationContext() {
if (applicationContext == null) {
applicationContext = newApplicationContextBuilder().build().start();
}
return applicationContext;
}
示例14
@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();
}
}
示例15
@Override
public ApplicationContext getApplicationContext() {
if (handler instanceof ApplicationContextProvider) {
return ((ApplicationContextProvider) handler).getApplicationContext();
}
return null;
}
示例16
/**
* @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));
}
示例17
@Override
protected ApplicationContext buildApplicationContext(Context context) {
ApplicationContext applicationContext = super.buildApplicationContext(context);
if (context != null) {
registerContextBeans(context, applicationContext);
this.functionName = context.getFunctionName();
}
return applicationContext;
}
示例18
/**
* 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;
}
示例19
/**
* @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;
}
示例20
@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);
}
}
示例21
@BeforeClass
public static void setup() {
kafkaContainer.start();
applicationContext = ApplicationContext.run(
CollectionUtils.mapOf(
"kafka.bootstrap.servers", kafkaContainer.getBootstrapServers()
)
);
}
示例22
public static void main(String...args) {
ApplicationContext applicationContext = ApplicationContext.run(
Collections.singletonMap(
AbstractKafkaConfiguration.EMBEDDED, true
)
, Environment.TEST);
KafkaEmbedded embedded = applicationContext.getBean(KafkaEmbedded.class);
}
示例23
@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)
));
}
示例24
@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)
));
}
示例25
@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)
));
}
示例26
@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)
));
}
示例27
/**
* @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;
}
示例28
@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));
}
示例29
/**
* @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;
}
示例30
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));
}