下面列出了怎么用org.springframework.core.env.Profiles的API类实例代码及写法,或者点击链接到github查看源代码。
@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));
});
}
@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());
});
}
@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));
}
@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()
);
});
}
/**
* Advice that logs methods throwing exceptions.
*
* @param joinPoint join point for advice.
* @param e exception.
*/
@AfterThrowing(pointcut = "applicationPackagePointcut() && springBeanPointcut()", throwing = "e")
public void logAfterThrowing(JoinPoint joinPoint, Throwable e) {
if (env.acceptsProfiles(Profiles.of(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT))) {
logger(joinPoint)
.error(
"Exception in {}() with cause = \'{}\' and exception = \'{}\'",
joinPoint.getSignature().getName(),
e.getCause() != null ? e.getCause() : "NULL",
e.getMessage(),
e
);
} else {
logger(joinPoint)
.error(
"Exception in {}() with cause = {}",
joinPoint.getSignature().getName(),
e.getCause() != null ? e.getCause() : "NULL"
);
}
}
static Function<String, Properties> yamlParserGenerator(Environment environment) {
return s -> {
YamlPropertiesFactoryBean yamlFactory = new YamlPropertiesFactoryBean();
yamlFactory.setDocumentMatchers(properties -> {
String profiles = properties.getProperty("spring.profiles");
if (environment != null && StringUtils.hasText(profiles)) {
return environment.acceptsProfiles(Profiles.of(profiles)) ? FOUND
: NOT_FOUND;
}
else {
return ABSTAIN;
}
});
yamlFactory.setResources(new ByteArrayResource(s.getBytes()));
return yamlFactory.getObject();
};
}
/**
* Advice that logs methods throwing exceptions.
*
* @param joinPoint join point for advice.
* @param e exception.
*/
@AfterThrowing(pointcut = "applicationPackagePointcut() && springBeanPointcut()", throwing = "e")
public void logAfterThrowing(JoinPoint joinPoint, Throwable e) {
if (env.acceptsProfiles(Profiles.of(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT))) {
logger(joinPoint)
.error(
"Exception in {}() with cause = \'{}\' and exception = \'{}\'",
joinPoint.getSignature().getName(),
e.getCause() != null ? e.getCause() : "NULL",
e.getMessage(),
e
);
} else {
logger(joinPoint)
.error(
"Exception in {}() with cause = {}",
joinPoint.getSignature().getName(),
e.getCause() != null ? e.getCause() : "NULL"
);
}
}
private RuntimeConfig createDefaultRuntimeConfig() {
RuntimeConfig runtimeConfig = new RuntimeConfig();
// set defaults
runtimeConfig.setFavouriteCountry(FredbetConstants.DEFAULT_FAVOURITE_COUNTRY);
runtimeConfig.setPasswordForReset(FredbetConstants.DEFAULT_REST_PASSWORT);
runtimeConfig.setChangePasswordOnFirstLogin(true);
runtimeConfig.setSelfRegistrationEnabled(false);
runtimeConfig.setRegistrationCode(RandomStringUtils.randomAlphanumeric(6));
if (environment.acceptsProfiles(Profiles.of(FredBetProfile.DEV, FredBetProfile.H2))) {
runtimeConfig.setShowDemoDataNavigationEntry(true);
runtimeConfig.setEnableChangingUsername(true);
saveRuntimeConfig(runtimeConfig);
}
return runtimeConfig;
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
ResourceHandlerRegistration reg = registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
boolean isLive = environment.acceptsProfiles(Profiles.of(Initializer.PROFILE_LIVE));
int cacheMinutes = isLive ? 15 : 0;
reg.setCachePeriod(cacheMinutes * 60);
//
registry
.addResourceHandler("/webjars/**")
.addResourceLocations("/webjars/")
.setCacheControl(CacheControl.maxAge(Duration.ofDays(isLive ? 10 : 0)).mustRevalidate());
registry.addResourceHandler("/assets/**")
.addResourceLocations("/webjars/alfio-public-frontend/" + frontendVersion + "/alfio-public-frontend/assets/");
}
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
MultiValueMap<String, Object> attrs = metadata.getAllAnnotationAttributes(Profile.class.getName());
if (attrs != null) {
for (Object value : attrs.get("value")) {
if (context.getEnvironment().acceptsProfiles(Profiles.of((String[]) value))) {
return true;
}
}
return false;
}
return true;
}
public AlarmService(Environment env, DingTalkService dingTalkService) {
this.dingTalkService = dingTalkService;
if (env != null && env.acceptsProfiles(Profiles.of(JHipsterConstants.SPRING_PROFILE_PRODUCTION))) {
prod = true;
} else {
prod = false;
}
}
public UrlJarLoader(Environment env) {
if (env == null) {
//just for test
this.properties = createProperties("META-INF/alchemy-dev.properties");
} else {
if (env.acceptsProfiles(Profiles.of(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT))) {
this.properties = createProperties("META-INF/alchemy-dev.properties");
} else {
this.properties = createProperties("META-INF/alchemy.properties");
}
}
}
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
if (env.getActiveProfiles().length != 0) {
log.info("Web application configuration, using profiles: {}", (Object[]) env.getActiveProfiles());
}
EnumSet<DispatcherType> disps = EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD, DispatcherType.ASYNC);
if (env.acceptsProfiles(Profiles.of(JHipsterConstants.SPRING_PROFILE_PRODUCTION))) {
initCachingHttpHeadersFilter(servletContext, disps);
}
if (env.acceptsProfiles(Profiles.of(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT))) {
initH2Console(servletContext);
}
log.info("Web application fully configured");
}
/**
* Advice that logs methods throwing exceptions.
*
* @param joinPoint join point for advice.
* @param e exception.
*/
@AfterThrowing(pointcut = "applicationPackagePointcut() && springBeanPointcut()", throwing = "e")
public void logAfterThrowing(JoinPoint joinPoint, Throwable e) {
if (env.acceptsProfiles(Profiles.of(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT))) {
log.error("Exception in {}.{}() with cause = \'{}\' and exception = \'{}\'", joinPoint.getSignature().getDeclaringTypeName(),
joinPoint.getSignature().getName(), e.getCause() != null? e.getCause() : "NULL", e.getMessage(), e);
} else {
log.error("Exception in {}.{}() with cause = {}", joinPoint.getSignature().getDeclaringTypeName(),
joinPoint.getSignature().getName(), e.getCause() != null? e.getCause() : "NULL");
}
}
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
if (env.getActiveProfiles().length != 0) {
log.info("Web application configuration, using profiles: {}", (Object[]) env.getActiveProfiles());
}
EnumSet<DispatcherType> disps = EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD, DispatcherType.ASYNC);
if (env.acceptsProfiles(Profiles.of(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT))) {
initH2Console(servletContext);
}
log.info("Web application fully configured");
}
/**
* Advice that logs methods throwing exceptions.
*
* @param joinPoint join point for advice.
* @param e exception.
*/
@AfterThrowing(pointcut = "applicationPackagePointcut() && springBeanPointcut()", throwing = "e")
public void logAfterThrowing(JoinPoint joinPoint, Throwable e) {
if (env.acceptsProfiles(Profiles.of(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT))) {
log.error("Exception in {}.{}() with cause = \'{}\' and exception = \'{}\'", joinPoint.getSignature().getDeclaringTypeName(),
joinPoint.getSignature().getName(), e.getCause() != null? e.getCause() : "NULL", e.getMessage(), e);
} else {
log.error("Exception in {}.{}() with cause = {}", joinPoint.getSignature().getDeclaringTypeName(),
joinPoint.getSignature().getName(), e.getCause() != null? e.getCause() : "NULL");
}
}
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
if (env.getActiveProfiles().length != 0) {
log.info("Web application configuration, using profiles: {}", (Object[]) env.getActiveProfiles());
}
EnumSet<DispatcherType> disps = EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD, DispatcherType.ASYNC);
if (env.acceptsProfiles(Profiles.of(JHipsterConstants.SPRING_PROFILE_PRODUCTION))) {
initCachingHttpHeadersFilter(servletContext, disps);
}
if (env.acceptsProfiles(Profiles.of(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT))) {
initH2Console(servletContext);
}
log.info("Web application fully configured");
}
/**
* Advice that logs methods throwing exceptions.
*
* @param joinPoint join point for advice.
* @param e exception.
*/
@AfterThrowing(pointcut = "applicationPackagePointcut() && springBeanPointcut()", throwing = "e")
public void logAfterThrowing(JoinPoint joinPoint, Throwable e) {
if (env.acceptsProfiles(Profiles.of(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT))) {
log.error("Exception in {}.{}() with cause = \'{}\' and exception = \'{}\'", joinPoint.getSignature().getDeclaringTypeName(),
joinPoint.getSignature().getName(), e.getCause() != null? e.getCause() : "NULL", e.getMessage(), e);
} else {
log.error("Exception in {}.{}() with cause = {}", joinPoint.getSignature().getDeclaringTypeName(),
joinPoint.getSignature().getName(), e.getCause() != null? e.getCause() : "NULL");
}
}
/**
* Advice that logs methods throwing exceptions.
*
* @param joinPoint join point for advice.
* @param e exception.
*/
@AfterThrowing(pointcut = "applicationPackagePointcut() && springBeanPointcut()", throwing = "e")
public void logAfterThrowing(JoinPoint joinPoint, Throwable e) {
if (env.acceptsProfiles(Profiles.of(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT))) {
log.error("Exception in {}.{}() with cause = \'{}\' and exception = \'{}\'", joinPoint.getSignature().getDeclaringTypeName(),
joinPoint.getSignature().getName(), e.getCause() != null? e.getCause() : "NULL", e.getMessage(), e);
} else {
log.error("Exception in {}.{}() with cause = {}", joinPoint.getSignature().getDeclaringTypeName(),
joinPoint.getSignature().getName(), e.getCause() != null? e.getCause() : "NULL");
}
}
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
MultiValueMap<String, Object> attrs = metadata.getAllAnnotationAttributes(Profile.class.getName());
if (attrs != null) {
for (Object value : attrs.get("value")) {
if (context.getEnvironment().acceptsProfiles(Profiles.of((String[]) value))) {
return true;
}
}
return false;
}
return true;
}
@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);
}
@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");
}
);
}
@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();
});
}
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
if (env.getActiveProfiles().length != 0) {
log.info("Web application configuration, using profiles: {}", (Object[]) env.getActiveProfiles());
}
EnumSet<DispatcherType> disps = EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD, DispatcherType.ASYNC);
if (env.acceptsProfiles(Profiles.of(JHipsterConstants.SPRING_PROFILE_PRODUCTION))) {
initCachingHttpHeadersFilter(servletContext, disps);
}
log.info("Web application fully configured");
}
@Override
public void initialize(@NotNull ConfigurableApplicationContext configurableApplicationContext) {
if (configurableApplicationContext.getEnvironment().acceptsProfiles(Profiles.of("docker"))) {
postgreSQLContainer.start();
configurableApplicationContext.getEnvironment().getSystemProperties()
.put("spring.datasource.url", postgreSQLContainer.getJdbcUrl());
configurableApplicationContext.getEnvironment().getSystemProperties()
.put("spring.datasource.username", postgreSQLContainer.getUsername());
configurableApplicationContext.getEnvironment().getSystemProperties()
.put("spring.datasource.password", postgreSQLContainer.getPassword());
}
}
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
if (env.getActiveProfiles().length != 0) {
log.info("Web application configuration, using profiles: {}", (Object[]) env.getActiveProfiles());
}
EnumSet<DispatcherType> disps = EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD, DispatcherType.ASYNC);
if (env.acceptsProfiles(Profiles.of(JHipsterConstants.SPRING_PROFILE_PRODUCTION))) {
initCachingHttpHeadersFilter(servletContext, disps);
}
log.info("Web application fully configured");
}
@Override
public void configure(WebSecurity web) {
if (this.environment.acceptsProfiles(Profiles.of("development"))) {
web.ignoring().antMatchers("/resources/**", "/build/**", "/ext/**",
"/**/*.js", "/bootstrap.json", "/robots.txt");
}
else {
web.ignoring().antMatchers("/resources/**", "/app.js", "/app.json",
"/locale-de.js", "/i18n-de.js", "/i18n-en.js", "/robots.txt");
}
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/login", "/logout", "/console/*", "/registration").permitAll();
http.authorizeRequests().antMatchers("/user/**").hasAnyAuthority(FredBetPermission.PERM_USER_ADMINISTRATION);
http.authorizeRequests().antMatchers("/admin/**").hasAnyAuthority(FredBetPermission.PERM_ADMINISTRATION);
http.authorizeRequests().antMatchers("/buildinfo/**").hasAnyAuthority(FredBetPermission.PERM_SYSTEM_INFO);
http.authorizeRequests().antMatchers("/administration/**").hasAnyAuthority(FredBetPermission.PERM_ADMINISTRATION);
http.authorizeRequests().anyRequest().authenticated();
http.formLogin().loginPage("/login").defaultSuccessUrl("/matches/upcoming").permitAll();
http.logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout")).logoutSuccessUrl("/login").invalidateHttpSession(true)
.deleteCookies("JSESSIONID", "remember-me").permitAll();
http.rememberMe().tokenRepository(persistentTokenRepository()).tokenValiditySeconds(REMEMBER_ME_TOKEN_VALIDITY_SECONDS);
// disable cache control to allow usage of ETAG headers (no image reload
// if the image has not been changed)
http.headers().cacheControl().disable();
if (environment.acceptsProfiles(Profiles.of(FredBetProfile.DEV))) {
// this is for the embedded h2 console
http.headers().frameOptions().disable();
// otherwise the H2 console will not work
http.csrf().ignoringAntMatchers("/console/*");
}
}
Optional<Boolean> processWebhookEvent(String body, String signature) {
try {
com.stripe.model.Event event = Webhook.constructEvent(body, signature, getWebhookSignatureKey());
if("account.application.deauthorized".equals(event.getType())
&& event.getLivemode() != null
&& event.getLivemode() == environment.acceptsProfiles(Profiles.of("dev", "test", "demo"))) {
return Optional.of(revokeToken(event.getAccount()));
}
return Optional.of(true);
} catch (Exception e) {
log.error("got exception while handling stripe webhook", e);
return Optional.empty();
}
}
public void toggleActiveFlag(int id, String username, boolean activate) {
Event event = eventRepository.findById(id);
checkOwnership(event, username, event.getOrganizationId());
if(environment.acceptsProfiles(Profiles.of(Initializer.PROFILE_DEMO))) {
throw new IllegalStateException("demo mode");
}
Event.Status status = activate ? Event.Status.PUBLIC : Event.Status.DRAFT;
eventRepository.updateEventStatus(id, status);
extensionManager.handleEventStatusChange(event, status);
}