org.springframework.core.env.Profiles Java Examples

The following examples show how to use org.springframework.core.env.Profiles. 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: 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 #2
Source File: MvcConfiguration.java    From alf.io with GNU General Public License v3.0 6 votes vote down vote up
@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/");

}
 
Example #3
Source File: RuntimeConfigurationService.java    From fredbet with Creative Commons Attribution Share Alike 4.0 International 6 votes vote down vote up
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;
}
 
Example #4
Source File: LoggingAspect.java    From jhipster-registry with Apache License 2.0 6 votes vote down vote up
/**
 * 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"
            );
    }
}
 
Example #5
Source File: PropertySourceUtils.java    From spring-cloud-kubernetes with Apache License 2.0 6 votes vote down vote up
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();
	};
}
 
Example #6
Source File: LoggingAspect.java    From jhipster-online with Apache License 2.0 6 votes vote down vote up
/**
 * 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"
            );
    }
}
 
Example #7
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 #8
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 #9
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 #10
Source File: LoggingAspect.java    From java-microservices-examples with Apache License 2.0 5 votes vote down vote up
/**
 * 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");
    }
}
 
Example #11
Source File: Initializer.java    From alf.io with GNU General Public License v3.0 5 votes vote down vote up
private void configureSessionCookie(ServletContext servletContext) {
    SessionCookieConfig config = servletContext.getSessionCookieConfig();

    config.setHttpOnly(true);
    
    Validate.notNull(environment, "environment cannot be null!");
    // set secure cookie only if current environment doesn't strictly need HTTP
    config.setSecure(environment.acceptsProfiles(Profiles.of(Initializer.PROFILE_LIVE)));

    // https://issues.jboss.org/browse/WFLY-3448 ?
    config.setPath(servletContext.getContextPath() + "/");
}
 
Example #12
Source File: SpringBootInitializer.java    From alf.io with GNU General Public License v3.0 5 votes vote down vote up
@Bean
public ServletContextInitializer servletContextInitializer() {
    return servletContext -> {
        WebApplicationContext ctx = getRequiredWebApplicationContext(servletContext);
        ConfigurableEnvironment environment = ctx.getBean(ConfigurableEnvironment.class);
        SessionCookieConfig config = servletContext.getSessionCookieConfig();
        config.setHttpOnly(true);
        config.setSecure(environment.acceptsProfiles(Profiles.of(Initializer.PROFILE_LIVE)));
        // force log initialization, then disable it
        XRLog.setLevel(XRLog.EXCEPTION, Level.WARNING);
        XRLog.setLoggingEnabled(false);
    };
}
 
Example #13
Source File: IndexController.java    From alf.io with GNU General Public License v3.0 5 votes vote down vote up
@GetMapping("/admin")
public void adminHome(Model model, @Value("${alfio.version}") String version, HttpServletRequest request, HttpServletResponse response, Principal principal) throws IOException {
    model.addAttribute("alfioVersion", version);
    model.addAttribute("username", principal.getName());
    model.addAttribute("basicConfigurationNeeded", configurationManager.isBasicConfigurationNeeded());

    boolean isDBAuthentication = !(principal instanceof WebSecurityConfig.OpenIdAlfioAuthentication);
    model.addAttribute("isDBAuthentication", isDBAuthentication);
    if (!isDBAuthentication) {
        String idpLogoutRedirectionUrl = ((WebSecurityConfig.OpenIdAlfioAuthentication) SecurityContextHolder.getContext().getAuthentication()).getIdpLogoutRedirectionUrl();
        model.addAttribute("idpLogoutRedirectionUrl", idpLogoutRedirectionUrl);
    } else {
        model.addAttribute("idpLogoutRedirectionUrl", null);
    }

    Collection<String> authorities = SecurityContextHolder.getContext().getAuthentication().getAuthorities()
        .stream().map(GrantedAuthority::getAuthority).collect(Collectors.toList());

    boolean isAdmin = authorities.contains(Role.ADMIN.getRoleName());
    model.addAttribute("isOwner", isAdmin || authorities.contains(Role.OWNER.getRoleName()));
    model.addAttribute("isAdmin", isAdmin);
    //
    model.addAttribute("request", request);
    model.addAttribute("demoModeEnabled", environment.acceptsProfiles(Profiles.of(Initializer.PROFILE_DEMO)));
    model.addAttribute("devModeEnabled", environment.acceptsProfiles(Profiles.of(Initializer.PROFILE_DEV)));
    model.addAttribute("prodModeEnabled", environment.acceptsProfiles(Profiles.of(Initializer.PROFILE_LIVE)));
    model.addAttribute(WebSecurityConfig.CSRF_PARAM_NAME, request.getAttribute(CsrfToken.class.getName()));
    //

    try (var os = response.getOutputStream()) {
        response.setContentType(TEXT_HTML_CHARSET_UTF_8);
        response.setCharacterEncoding(UTF_8);
        var nonce = addCspHeader(response);
        model.addAttribute("nonce", nonce);
        templateManager.renderHtml(new ClassPathResource("alfio/web-templates/admin-index.ms"), model.asMap(), os);
    }
}
 
Example #14
Source File: IndexController.java    From alf.io with GNU General Public License v3.0 5 votes vote down vote up
@GetMapping("/authentication")
public void getLoginPage(@RequestParam(value="failed", required = false) String failed, @RequestParam(value = "recaptchaFailed", required = false) String recaptchaFailed,
                         Model model,
                         Principal principal,
                         HttpServletRequest request,
                         HttpServletResponse response) throws IOException {
    if(principal != null) {
        response.sendRedirect("/admin/");
        return;
    }
    model.addAttribute("failed", failed != null);
    model.addAttribute("recaptchaFailed", recaptchaFailed != null);
    model.addAttribute("hasRecaptchaApiKey", false);

    //
    model.addAttribute("request", request);
    model.addAttribute("demoModeEnabled", environment.acceptsProfiles(Profiles.of(Initializer.PROFILE_DEMO)));
    model.addAttribute("devModeEnabled", environment.acceptsProfiles(Profiles.of(Initializer.PROFILE_DEV)));
    model.addAttribute("prodModeEnabled", environment.acceptsProfiles(Profiles.of(Initializer.PROFILE_LIVE)));
    model.addAttribute(WebSecurityConfig.CSRF_PARAM_NAME, request.getAttribute(CsrfToken.class.getName()));
    //

    var configuration = configurationManager.getFor(EnumSet.of(RECAPTCHA_API_KEY, ENABLE_CAPTCHA_FOR_LOGIN), ConfigurationLevel.system());

    configuration.get(RECAPTCHA_API_KEY).getValue()
        .filter(key -> configuration.get(ENABLE_CAPTCHA_FOR_LOGIN).getValueAsBooleanOrDefault(true))
        .ifPresent(key -> {
            model.addAttribute("hasRecaptchaApiKey", true);
            model.addAttribute("recaptchaApiKey", key);
        });
    try (var os = response.getOutputStream()) {
        response.setContentType(TEXT_HTML_CHARSET_UTF_8);
        response.setCharacterEncoding(UTF_8);
        var nonce = addCspHeader(response);
        model.addAttribute("nonce", nonce);
        templateManager.renderHtml(new ClassPathResource("alfio/web-templates/login.ms"), model.asMap(), os);
    }
}
 
Example #15
Source File: UtilsApiController.java    From alf.io with GNU General Public License v3.0 5 votes vote down vote up
@GetMapping("/alfio/info")
public Map<String, Object> getApplicationInfo(Principal principal) {
    Map<String, Object> applicationInfo = new HashMap<>();
    applicationInfo.put("version", version);
    applicationInfo.put("username", principal.getName());
    applicationInfo.put("isDemoMode", environment.acceptsProfiles(Profiles.of(Initializer.PROFILE_DEMO)));
    return applicationInfo;
}
 
Example #16
Source File: Mailer.java    From alf.io with GNU General Public License v3.0 5 votes vote down vote up
default String decorateSubjectIfDemo(String subject, Environment environment) {
    if(environment.acceptsProfiles(Profiles.of(Initializer.PROFILE_DEMO))) {
        return "THIS IS A TEST: " + subject;
    } else {
        return subject;
    }
}
 
Example #17
Source File: EventManager.java    From alf.io with GNU General Public License v3.0 5 votes vote down vote up
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);
}
 
Example #18
Source File: BaseStripeManager.java    From alf.io with GNU General Public License v3.0 5 votes vote down vote up
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();
    }
}
 
Example #19
Source File: AlarmService.java    From alchemy with Apache License 2.0 5 votes vote down vote up
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;
    }
}
 
Example #20
Source File: WebSecurityConfig.java    From fredbet with Creative Commons Attribution Share Alike 4.0 International 5 votes vote down vote up
@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/*");
    }
}
 
Example #21
Source File: SecurityConfig.java    From eds-starter6-jpa with Apache License 2.0 5 votes vote down vote up
@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");
	}
}
 
Example #22
Source File: UrlJarLoader.java    From alchemy with Apache License 2.0 5 votes vote down vote up
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");
        }
    }
}
 
Example #23
Source File: WebConfigurer.java    From jhipster-registry with Apache License 2.0 5 votes vote down vote up
@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");
}
 
Example #24
Source File: WebConfigurer.java    From alchemy with Apache License 2.0 5 votes vote down vote up
@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");
}
 
Example #25
Source File: UserRepositoryIntegrationTest.java    From code-examples with MIT License 5 votes vote down vote up
@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());
  }
}
 
Example #26
Source File: WebConfigurer.java    From jhipster-online with Apache License 2.0 5 votes vote down vote up
@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");
}
 
Example #27
Source File: LoggingAspect.java    From java-microservices-examples with Apache License 2.0 5 votes vote down vote up
/**
 * 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");
    }
}
 
Example #28
Source File: ProfileCondition.java    From java-technology-stack with MIT License 5 votes vote down vote up
@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;
}
 
Example #29
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 #30
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");
            }
    );
}