Java Code Examples for org.springframework.context.support.GenericApplicationContext#getEnvironment()

The following examples show how to use org.springframework.context.support.GenericApplicationContext#getEnvironment() . 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: GRPCAuthConfiguration.java    From liiklus with MIT License 6 votes vote down vote up
@Override
public void initialize(GenericApplicationContext applicationContext) {
    var environment = applicationContext.getEnvironment();

    var authProperties = PropertiesUtil.bind(environment, new GRPCAuthProperties());

    if (authProperties.getAlg() == GRPCAuthProperties.Alg.NONE) {
        return;
    }

    log.info("GRPC Authorization ENABLED with algorithm {}", authProperties.getAlg());

    applicationContext.registerBean(
            JWTAuthGRPCTransportConfigurer.class,
            () -> new JWTAuthGRPCTransportConfigurer(authProperties)
    );
}
 
Example 2
Source File: RedisPositionsConfiguration.java    From liiklus with MIT License 6 votes vote down vote up
@Override
public void initialize(GenericApplicationContext applicationContext) {
    var environment = applicationContext.getEnvironment();

    var type = environment.getRequiredProperty("storage.positions.type");
    if(!"REDIS".equals(type)) {
        return;
    }

    var redisProperties = PropertiesUtil.bind(environment, new RedisProperties());

    applicationContext.registerBean(RedisPositionsStorage.class, () -> {
        var redisURI = RedisURI.builder()
                .withHost(redisProperties.getHost())
                .withPort(redisProperties.getPort())
                .build();

        return new RedisPositionsStorage(
                Mono
                        .fromCompletionStage(() -> RedisClient.create().connectAsync(StringCodec.UTF8, redisURI))
                        .cache(),
                redisProperties.getPositionsProperties().getPrefix()
        );
    });
}
 
Example 3
Source File: PulsarRecordsStorageConfiguration.java    From liiklus with MIT License 6 votes vote down vote up
@Override
public void initialize(GenericApplicationContext applicationContext) {
    var environment = applicationContext.getEnvironment();

    if (!environment.acceptsProfiles(Profiles.of("gateway"))) {
        return;
    }

    if (!"PULSAR".equals(environment.getRequiredProperty("storage.records.type"))) {
        return;
    }

    var pulsarProperties = PropertiesUtil.bind(environment, new PulsarProperties());

    applicationContext.registerBean(PulsarRecordsStorage.class, () -> {
        return new PulsarRecordsStorage(createClient(pulsarProperties));
    });
}
 
Example 4
Source File: KafkaRecordsStorageConfiguration.java    From liiklus with MIT License 6 votes vote down vote up
@Override
public void initialize(GenericApplicationContext applicationContext) {
    var environment = applicationContext.getEnvironment();

    if (!environment.acceptsProfiles(Profiles.of("gateway"))) {
        return;
    }

    if (!"KAFKA".equals(environment.getRequiredProperty("storage.records.type"))) {
        return;
    }

    var kafkaProperties = PropertiesUtil.bind(environment, new KafkaProperties());

    applicationContext.registerBean(KafkaRecordsStorage.class, () -> {
        return new KafkaRecordsStorage(kafkaProperties.getBootstrapServers());
    });
}
 
Example 5
Source File: InMemoryRecordsConfiguration.java    From liiklus with MIT License 6 votes vote down vote up
@Override
public void initialize(GenericApplicationContext applicationContext) {
    var environment = applicationContext.getEnvironment();
    if (!environment.acceptsProfiles(Profiles.of("gateway"))) {
        return;
    }

    String type = environment.getRequiredProperty("storage.records.type");
    if (!"MEMORY".equals(type)) {
        return;
    }

    log.warn("\n" +
            String.format("%0106d", 0).replace("0", "=") + "\n" +
            String.format("%0106d", 0).replace("0", "=") + "\n" +
            String.format("%0106d", 0).replace("0", "=") + "\n" +
            "=== In-memory records storage is used. Please, DO NOT run it in production. ===\n" +
            String.format("%0106d", 0).replace("0", "=") + "\n" +
            String.format("%0106d", 0).replace("0", "=") + "\n" +
            String.format("%0106d", 0).replace("0", "=")
    );
    applicationContext.registerBean(InMemoryRecordsStorage.class, () -> new InMemoryRecordsStorage(32));
}
 
Example 6
Source File: SchemaPluginConfiguration.java    From liiklus with MIT License 6 votes vote down vote up
@Override
public void initialize(GenericApplicationContext applicationContext) {
    var environment = applicationContext.getEnvironment();
    if (!environment.acceptsProfiles(Profiles.of("gateway"))) {
        return;
    }

    var schemaProperties = PropertiesUtil.bind(environment, new SchemaProperties());

    if (!schemaProperties.isEnabled()) {
        return;
    }

    applicationContext.registerBean(RecordPreProcessor.class, () -> {
        return new JsonSchemaPreProcessor(
                schemaProperties.getSchemaURL(),
                JsonPointer.compile(schemaProperties.getEventTypeJsonPointer()),
                schemaProperties.isAllowDeprecatedProperties()
        );
    });
}
 
Example 7
Source File: FunctionExporterInitializer.java    From spring-cloud-function with Apache License 2.0 6 votes vote down vote up
private boolean isExporting(GenericApplicationContext context) {
	Boolean enabled = context.getEnvironment().getProperty("spring.cloud.function.web.export.enabled",
			Boolean.class);
	if (enabled != null) {
		return enabled;
	}
	if (ClassUtils.isPresent("org.springframework.web.context.WebApplicationContext",
			getClass().getClassLoader())) {
		if (context instanceof WebApplicationContext || context instanceof ReactiveWebApplicationContext
				|| context.getEnvironment() instanceof ConfigurableWebEnvironment
				|| context.getEnvironment() instanceof ConfigurableReactiveWebEnvironment) {
			return false;
		}
	}
	return true;
}
 
Example 8
Source File: GatewayConfiguration.java    From liiklus with MIT License 5 votes vote down vote up
@Override
public void initialize(GenericApplicationContext applicationContext) {
    var environment = applicationContext.getEnvironment();

    if (!environment.acceptsProfiles(Profiles.of("gateway"))) {
        return;
    }

    var layersProperties = PropertiesUtil.bind(environment, new LayersProperties());

    var comparator = Comparator
            .comparingInt(it -> layersProperties.getOrders().getOrDefault(it.getClass().getName(), 0))
            .thenComparing(it -> it.getClass().getName());

    applicationContext.registerBean(RecordPreProcessorChain.class, () -> new RecordPreProcessorChain(
            applicationContext.getBeansOfType(RecordPreProcessor.class).values().stream()
                    .sorted(comparator)
                    .collect(Collectors.toList())
    ));

    applicationContext.registerBean(RecordPostProcessorChain.class, () -> new RecordPostProcessorChain(
            applicationContext.getBeansOfType(RecordPostProcessor.class).values().stream()
                    .sorted(comparator.reversed())
                    .collect(Collectors.toList())
    ));

    applicationContext.registerBean(LiiklusService.class);
}
 
Example 9
Source File: RSocketConfiguration.java    From liiklus with MIT License 5 votes vote down vote up
@Override
public void initialize(GenericApplicationContext applicationContext) {
    var environment = applicationContext.getEnvironment();

    if (!environment.acceptsProfiles(Profiles.of("gateway"))) {
        return;
    }

    var serverProperties = PropertiesUtil.bind(environment, new RSocketServerProperties());

    if (!serverProperties.isEnabled()) {
        return;
    }

    applicationContext.registerBean(RSocketLiiklusService.class);

    applicationContext.registerBean(
            CloseableChannel.class,
            () -> {
                var liiklusService = applicationContext.getBean(LiiklusService.class);

                return RSocketFactory.receive()
                        .acceptor((setup, sendingSocket) -> Mono.just(new RequestHandlingRSocket(new LiiklusServiceServer(liiklusService, Optional.empty(), Optional.empty()))))
                        .transport(TcpServerTransport.create(serverProperties.getHost(), serverProperties.getPort()))
                        .start()
                        .block();
            },
            it -> {
                it.setDestroyMethodName("dispose");
            }
    );
}
 
Example 10
Source File: MetricsConfiguration.java    From liiklus with MIT License 5 votes vote down vote up
@Override
public void initialize(GenericApplicationContext applicationContext) {
    var environment = applicationContext.getEnvironment();

    if (!environment.acceptsProfiles(Profiles.of("exporter"))) {
        return;
    }

    applicationContext.registerBean(MetricsCollector.class);

    applicationContext.registerBean("prometheus", RouterFunction.class, () -> {
        var metricsCollector = applicationContext.getBean(MetricsCollector.class);
        return RouterFunctions.route()
                .GET("/prometheus", __ -> {
                    return metricsCollector.collect()
                            .collectList()
                            .flatMap(metrics -> {
                                try {
                                    var writer = new StringWriter();
                                    TextFormat.write004(writer, Collections.enumeration(metrics));
                                    return ServerResponse.ok()
                                            .contentType(MediaType.valueOf(TextFormat.CONTENT_TYPE_004))
                                            .bodyValue(writer.toString());
                                } catch (IOException e) {
                                    return ServerResponse.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
                                }
                            });
                })
                .build();

    });
}
 
Example 11
Source File: DynamoDBConfiguration.java    From liiklus with MIT License 4 votes vote down vote up
@Override
public void initialize(GenericApplicationContext applicationContext) {
    var environment = applicationContext.getEnvironment();

    if (!"DYNAMODB".equals(environment.getRequiredProperty("storage.positions.type"))) {
        return;
    }

    var dynamoDBProperties = PropertiesUtil.bind(environment, new DynamoDBProperties());

    applicationContext.registerBean(DynamoDBPositionsStorage.class, () -> {
        var builder = DynamoDbAsyncClient.builder();

        dynamoDBProperties.getEndpoint()
                .map(URI::create)
                .ifPresent(builder::endpointOverride);

        var dynamoDB = builder
                .build();

        if (dynamoDBProperties.isAutoCreateTable()) {
            log.info("Going to automatically create a table with name '{}'", dynamoDBProperties.getPositionsTable());
            var request = CreateTableRequest.builder()
                    .keySchema(
                            KeySchemaElement.builder().attributeName(DynamoDBPositionsStorage.HASH_KEY_FIELD).keyType(KeyType.HASH).build(),
                            KeySchemaElement.builder().attributeName(DynamoDBPositionsStorage.RANGE_KEY_FIELD).keyType(KeyType.RANGE).build()
                    )
                    .attributeDefinitions(
                            AttributeDefinition.builder().attributeName(DynamoDBPositionsStorage.HASH_KEY_FIELD).attributeType(ScalarAttributeType.S).build(),
                            AttributeDefinition.builder().attributeName(DynamoDBPositionsStorage.RANGE_KEY_FIELD).attributeType(ScalarAttributeType.S).build()
                            )
                    .tableName(dynamoDBProperties.getPositionsTable())
                    .provisionedThroughput(ProvisionedThroughput.builder().readCapacityUnits(10L).writeCapacityUnits(10L).build())
                    .build();

            try {
                dynamoDB.createTable(request).get();
            } catch (Exception e) {
                throw new IllegalStateException("Can't create positions dynamodb table", e);
            }
        }

        return new DynamoDBPositionsStorage(
                dynamoDB,
                dynamoDBProperties.getPositionsTable()
        );
    });
}
 
Example 12
Source File: GRPCConfiguration.java    From liiklus with MIT License 4 votes vote down vote up
@Override
public void initialize(GenericApplicationContext applicationContext) {
    var environment = applicationContext.getEnvironment();

    if (!environment.acceptsProfiles(Profiles.of("gateway"))) {
        return;
    }

    var serverProperties = PropertiesUtil.bind(environment, new GRpcServerProperties());

    if (!serverProperties.isEnabled()) {
        return;
    }

    applicationContext.registerBean(GRPCLiiklusService.class);

    applicationContext.registerBean(
            Server.class,
            () -> {
                var serverBuilder = NettyServerBuilder
                        .forPort(serverProperties.getPort())
                        .permitKeepAliveTime(150, TimeUnit.SECONDS)
                        .permitKeepAliveWithoutCalls(true)
                        .directExecutor()
                        .intercept(new ServerInterceptor() {
                            @Override
                            public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(ServerCall<ReqT, RespT> call, Metadata headers, ServerCallHandler<ReqT, RespT> next) {
                                call.setCompression("gzip");
                                return next.startCall(call, headers);
                            }
                        })
                        .addService(ProtoReflectionService.newInstance());

                for (var bindableService : applicationContext.getBeansOfType(BindableService.class).values()) {
                    serverBuilder.addService(bindableService);
                }

                for (var transportConfigurer : applicationContext.getBeansOfType(GRPCLiiklusTransportConfigurer.class).values()) {
                    transportConfigurer.apply(serverBuilder);
                }

                return serverBuilder.build();
            },
            it -> {
                it.setInitMethodName("start");
                it.setDestroyMethodName("shutdownNow");
            }
    );
}