@Override public boolean isTemplateAvailable(String view, Environment environment, ClassLoader classLoader, ResourceLoader resourceLoader) { if (ClassUtils.isPresent("org.apache.velocity.app.VelocityEngine", classLoader)) { PropertyResolver resolver = new RelaxedPropertyResolver(environment, "spring.velocity."); String loaderPath = resolver.getProperty("resource-loader-path", VelocityProperties.DEFAULT_RESOURCE_LOADER_PATH); String prefix = resolver.getProperty("prefix", VelocityProperties.DEFAULT_PREFIX); String suffix = resolver.getProperty("suffix", VelocityProperties.DEFAULT_SUFFIX); return resourceLoader.getResource(loaderPath + prefix + view + suffix) .exists(); } return false; }
/** * 创建配置Bean * * @param propertyName 属性名 * @param beanType 配置Bean类型 * @param converterType 转换器类型 * @param configBeanPropertyResolver 属性解析器 * @param conversionService 转换服务 * @param <T> * @return */ public static <T> T createConfigBean(String propertyName, Class<T> beanType, Class<? extends ConfigBeanConverter> converterType, ConfigPropertyResolver configBeanPropertyResolver, ConfigBeanConversionService conversionService) { PropertyResolver propertyResolver = configBeanPropertyResolver.getObject(); String propertyValue = propertyResolver.getRequiredProperty(propertyName); if (converterType != null && !converterType.isInterface()) { ConfigBeanConverter converter = BeanUtils.instantiate(converterType); return (T) converter.convert(propertyName, propertyValue, TypeDescriptor.valueOf(beanType)); } else { return (T) conversionService.convert(propertyName, propertyValue, TypeDescriptor.valueOf(beanType)); } }
public RedisDatastore(MappingContext mappingContext, PropertyResolver configuration, ConfigurableApplicationContext ctx) { super(mappingContext, configuration, ctx); int resourceCount = 10; if (configuration != null) { host = configuration.getProperty(CONFIG_HOST, DEFAULT_HOST); port = configuration.getProperty(CONFIG_PORT, Integer.class, DEFAULT_PORT); timeout = configuration.getProperty(CONFIG_TIMEOUT, Integer.class, 2000); pooled = configuration.getProperty(CONFIG_POOLED, Boolean.class, true); password = configuration.getProperty(CONFIG_PASSWORD, (String)null); resourceCount = configuration.getProperty(CONFIG_RESOURCE_COUNT, Integer.class, resourceCount); } if (pooled && useJedis()) { this.pool = JedisTemplateFactory.createPool(host, port, timeout, resourceCount, password); } initializeConverters(mappingContext); }
@Override public void printBanner(Environment environment, Class<?> sourceClass, PrintStream out) { try { String banner = StreamUtils.copyToString(this.resource.getInputStream(), environment.getProperty("banner.charset", Charset.class, Charset.forName("UTF-8"))); for (PropertyResolver resolver : getPropertyResolvers(environment, sourceClass)) { banner = resolver.resolvePlaceholders(banner); } out.println(banner); } catch (Exception ex) { logger.warn("Banner not printable: " + this.resource + " (" + ex.getClass() + ": '" + ex.getMessage() + "')", ex); } }
/** * Gets a test instance of this class that uses only the given mapping. * * @param instanceTypes map of virtualization types to instance types * @param localizationContext the localization context * @return new mapping object */ public static VirtualizationMappings getTestInstance( final Map<String, List<String>> instanceTypes, LocalizationContext localizationContext) { Map<String, String> propertyMap = Maps.transformValues(instanceTypes, new Function<List<String>, String>() { @Override public String apply(@Nonnull List<String> input) { return JOINER.join(input); } }); PropertyResolver virtualizationMappingsResolver = PropertyResolvers.newMapPropertyResolver(propertyMap); File tempDir = Files.createTempDir(); tempDir.deleteOnExit(); VirtualizationMappingsConfigProperties virtualizationMappingsConfigProperties = new VirtualizationMappingsConfigProperties(new SimpleConfiguration(), tempDir, localizationContext); return new VirtualizationMappings(virtualizationMappingsConfigProperties, virtualizationMappingsResolver); }
/** * Gets a test instance of this class that uses only the given encryption * instance classes. * * @param encryptionInstanceClasses list of instance classes that support storage encryption * @param localizationContext the localization context * @return new encryption instance classes object */ public static RDSEncryptionInstanceClasses getTestInstance( final List<String> encryptionInstanceClasses, LocalizationContext localizationContext) { Map<String, String> encryptionInstanceClassesMap = Maps.newHashMap(); for (String instanceClass : encryptionInstanceClasses) { encryptionInstanceClassesMap.put(instanceClass, "true"); } PropertyResolver resolver = PropertyResolvers.newMapPropertyResolver(encryptionInstanceClassesMap); File tempDir = Files.createTempDir(); tempDir.deleteOnExit(); RDSEncryptionInstanceClassesConfigProperties configProperties = new RDSEncryptionInstanceClassesConfigProperties(new SimpleConfiguration(), tempDir, localizationContext); return new RDSEncryptionInstanceClasses(configProperties, resolver); }
/** * Creates a property resolver that pulls from multiple property resource * locations. The first "built-in" location must be successfully loaded, but * all other "custom" locations must load only if {code}allowMissing{code} is * false. * * @param allowMissing true to allow custom resource locations to fail to load * @param builtInResourceLocation lowest precedence, required resource * location for properties * @param customResourceLocations additional resource locations for * properties, in increasing order of precedence * @return new property resolver * @throws IOException if the built-in resource location could not be loaded, * or if {code}allowMissing{code} is false and any custom resource location * fails to load * @throws NullPointerException if any resource location is null */ public static PropertyResolver newMultiResourcePropertyResolver(boolean allowMissing, String builtInResourceLocation, String... customResourceLocations) throws IOException { MutablePropertySources sources = new MutablePropertySources(); checkNotNull(builtInResourceLocation, "builtInResourceLocation is null"); sources.addLast(buildPropertySource(BUILT_IN_NAME, builtInResourceLocation, false)); String lastname = BUILT_IN_NAME; int customCtr = 1; for (String loc : customResourceLocations) { checkNotNull(loc, "customResourceLocations[" + (customCtr - 1) + "] is null"); String thisname = CUSTOM_NAME_PREFIX + customCtr++; PropertySource source = buildPropertySource(thisname, loc, allowMissing); if (source != null) { sources.addBefore(lastname, source); lastname = thisname; } } return new PropertySourcesPropertyResolver(sources); }
@Test public void testDispatcher() { Map<String, Object> properties = newHashMap(); properties.put("check.targetTypes", "test.TestFirst,test.TestSecond"); properties.put("check.TestFirst", "checkType"); properties.put("check.TestSecond", "checkBoundaries"); PropertyResolver propResolver = makePropertyResolver(properties); TypeBasedMatcherDispatcher<AnnotationFS> actualMatcher = new MatchingConfigurationInitializer(ts, propResolver).create(); Type firstType = ts.getType("test.TestFirst"); Type secondType = ts.getType("test.TestSecond"); Builder<AnnotationFS> expectedBuilder = TypeBasedMatcherDispatcher.builder(ts); expectedBuilder.addSubmatcher(firstType, CompositeMatcher.builderForAnnotation(firstType).addTypeChecker().build()); expectedBuilder.addSubmatcher(secondType, CompositeMatcher.builderForAnnotation(secondType).addBoundaryMatcher().build()); assertMatchersEqual(expectedBuilder.build(), actualMatcher); }
@Override public void printBanner(Environment environment, Class<?> sourceClass, PrintStream out) { try { String banner = StreamUtils.copyToString(this.resource.getInputStream(), environment.getProperty("banner.charset", Charset.class, Charset.forName("UTF-8"))); for (PropertyResolver resolver : getPropertyResolvers(environment, sourceClass)) { banner = resolver.resolvePlaceholders(banner); } out.println(banner); } catch (Exception ex) { log.warn("Banner not printable: " + this.resource + " (" + ex.getClass() + ": '" + ex.getMessage() + "')", ex); } }
public static String resolvePlaceholders(Object applicationContext, String value, boolean throwIfNotResolved){ String newValue = value; if (StringUtils.hasText(value) && DOLOR.isExpresstion(value)){ if(applicationContext instanceof ConfigurableApplicationContext){ ConfigurableApplicationContext appcontext = (ConfigurableApplicationContext)applicationContext; newValue = appcontext.getEnvironment().resolvePlaceholders(value); }else if(applicationContext instanceof PropertyResolver){ PropertyResolver env = (PropertyResolver)applicationContext; newValue = env.resolvePlaceholders(value); } if(DOLOR.isExpresstion(newValue) && throwIfNotResolved){ throw new BaseException("can not resolve placeholders value: " + value + ", resovled value: " + newValue); } } return newValue; }
@Subscribe public void sendPendingEmail(UserJoinedEvent userJoinedEvent) throws SignatureException { log.info("Sending pending review email: {}", userJoinedEvent.getPersistable()); PropertyResolver propertyResolver = new RelaxedPropertyResolver(env, "registration."); List<User> administrators = userRepository.findByRole("agate-administrator"); Context ctx = new Context(); User user = userJoinedEvent.getPersistable(); String organization = configurationService.getConfiguration().getName(); ctx.setLocale(LocaleUtils.toLocale(user.getPreferredLanguage())); ctx.setVariable("user", user); ctx.setVariable("organization", organization); ctx.setVariable("publicUrl", configurationService.getPublicUrl()); administrators.stream().forEach(u -> mailService .sendEmail(u.getEmail(), "[" + organization + "] " + propertyResolver.getProperty("pendingForReviewSubject"), templateEngine.process("pendingForReviewEmail", ctx))); mailService .sendEmail(user.getEmail(), "[" + organization + "] " + propertyResolver.getProperty("pendingForApprovalSubject"), templateEngine.process("pendingForApprovalEmail", ctx)); }
@Subscribe public void sendConfirmationEmail(UserApprovedEvent userApprovedEvent) throws SignatureException { log.info("Sending confirmation email: {}", userApprovedEvent.getPersistable()); PropertyResolver propertyResolver = new RelaxedPropertyResolver(env, "registration."); Context ctx = new Context(); User user = userApprovedEvent.getPersistable(); String organization = configurationService.getConfiguration().getName(); ctx.setLocale(LocaleUtils.toLocale(user.getPreferredLanguage())); ctx.setVariable("user", user); ctx.setVariable("organization", organization); ctx.setVariable("publicUrl", configurationService.getPublicUrl()); ctx.setVariable("key", configurationService.encrypt(user.getName())); mailService .sendEmail(user.getEmail(), "[" + organization + "] " + propertyResolver.getProperty("confirmationSubject"), templateEngine.process("confirmationEmail", ctx)); }
public boolean verify(String reCaptchaResponse) { PropertyResolver propertyResolver = new RelaxedPropertyResolver(env, "recaptcha."); MultiValueMap<String, String> map = new LinkedMultiValueMap<>(); map.add("secret", propertyResolver.getProperty("secret")); map.add("response", reCaptchaResponse); ReCaptchaVerifyResponse recaptchaVerifyResponse = restTemplate .postForObject(propertyResolver.getProperty("verifyUrl"), map, ReCaptchaVerifyResponse.class); if(!recaptchaVerifyResponse.isSuccess() && (recaptchaVerifyResponse.getErrorCodes().contains("invalid-input-secret") || recaptchaVerifyResponse.getErrorCodes().contains("missing-input-secret"))) { log.error("Error verifying recaptcha: " + reCaptchaResponse); throw new RuntimeException("Error verifying recaptcha."); } return recaptchaVerifyResponse.isSuccess(); }
@Bean public WroManagerFactory wroManagerFactory(WroModelFactory wroModelFactory, PropertyResolver propertyResolver) { ConfigurableWroManagerFactory factory = new ConfigurableWroManagerFactory(); factory.setModelFactory(wroModelFactory); factory.setUriLocatorFactory(new MidPointUrlLocatorFactory(propertyResolver)); SimpleProcessorsFactory processors = new SimpleProcessorsFactory(); Collection<ResourcePreProcessor> preProcessors = new ArrayList<>(); preProcessors.add(new CssUrlRewritingProcessor()); preProcessors.add(new CssImportPreProcessor()); preProcessors.add(new SemicolonAppenderPreProcessor()); Collection<ResourcePostProcessor> postProcessors = new ArrayList<>(); postProcessors.add(new Less4jProcessor()); processors.setResourcePreProcessors(preProcessors); processors.setResourcePostProcessors(postProcessors); factory.setProcessorsFactory(processors); return factory; }
public static String getDefaultInstanceId(PropertyResolver resolver, boolean includeHostname) { String vcapInstanceId = resolver.getProperty("vcap.application.instance_id"); if (StringUtils.hasText(vcapInstanceId)) { return vcapInstanceId; } String hostname = null; if (includeHostname) { hostname = resolver.getProperty("spring.cloud.client.hostname"); } String appName = resolver.getProperty("spring.application.name"); String namePart = combineParts(hostname, SEPARATOR, appName); String indexPart = resolver.getProperty("spring.application.instance_id", resolver.getProperty("server.port")); return combineParts(namePart, SEPARATOR, indexPart); }
public static final ShortLinkRepository newShortLinkRepository(PropertyResolver props) throws PropertyException { final String repoType; boolean enabled; enabled = props.getProperty("shortlink.enabled", Boolean.class, true); if(!enabled) { log.info("Shortlinking disabled in config"); return new NoOpRepository(); } repoType = props.getProperty("shortlink.backend", String.class, "HDFS"); if ("HDFS".equals(repoType)) { return new HDFSShortLinkRepository(props); } if ("S3".equals(repoType)) { return new S3ShortLinkRepository(props); } throw new PropertyException("Unknown cache type (property: shortlink.backend): " + repoType); }
public HDFSShortLinkRepository(final PropertyResolver props) { enabled = true; try { kerberosLogin(props); linkPath = new Path(props.getProperty("shortlink.hdfs.path", String.class)); hdfs = linkPath.getFileSystem(new Configuration()); log.info("Short linking will use HDFS path: " + linkPath); worldWritable = props.getProperty("shortlink.hdfs.worldwritable", Boolean.class, true); if(!hdfs.exists(linkPath)) { hdfs.mkdirs(linkPath); if(worldWritable) { hdfs.setPermission(linkPath, FsPermission.valueOf("-rwxrwxrwx")); } } log.info("HDFSShortLinkRepository initialized"); } catch (Exception e) { log.info("Failed to initialize the HDFS client. Shortlinking disabled.", e); enabled = false; } }
public static final QueryCache newQueryCache(PropertyResolver props) throws PropertyException { final String cacheType; boolean enabled; enabled = props.getProperty("query.cache.enabled", Boolean.class, true); if(!enabled) { log.info("Query caching disabled in config"); return new NoOpQueryCache(); } cacheType = props.getProperty("query.cache.backend", String.class, "HDFS"); if ("HDFS".equals(cacheType)) { return new HDFSQueryCache(props); } if ("S3".equals(cacheType)) { return new S3QueryCache(props); } throw new PropertyException("Unknown cache type (property: query.cache.backend): " + cacheType); }
public HDFSQueryCache(PropertyResolver props) { enabled = true; try { kerberosLogin(props); cachePath = new Path(props.getProperty("query.cache.hdfs.path")); hdfs = cachePath.getFileSystem(new org.apache.hadoop.conf.Configuration()); cacheDirWorldWritable = props.getProperty("query.cache.worldwritable", Boolean.class); makeSurePathExists(cachePath); } catch (Exception e) { log.info("Failed to initialize the HDFS query cache. Caching disabled.", e); enabled = false; } }
private static PropertyResolver convertToResolver(Map<String, Object> config) { if(config instanceof PropertyResolver) { return (PropertyResolver) config; } else { StandardEnvironment env = new StandardEnvironment(); env.getPropertySources().addFirst(new MapPropertySource("datastoreConfig", config)); return env; } }
@Override protected Session createSession(PropertyResolver connDetails) { if (!useJedis()) { throw new IllegalStateException( "Cannot create RedisSession. No Redis client library found on classpath. " + "Please make sure you have the Jedis library on your classpath"); } return new RedisSession(this, getMappingContext(), JedisTemplateFactory.create(host, port, timeout, pooled, password), getApplicationEventPublisher()); }
@Override public boolean isTemplateAvailable(String view, Environment environment, ClassLoader classLoader, ResourceLoader resourceLoader) { if (ClassUtils.isPresent("org.thymeleaf.spring4.SpringTemplateEngine", classLoader) && ClassUtils.isPresent("org.thymeleaf.Thymeleaf", classLoader)) { PropertyResolver resolver = new RelaxedPropertyResolver(environment, "spring.thymeleaf3."); String prefix = resolver.getProperty("prefix", DEFAULT_PREFIX); String suffix = resolver.getProperty("suffix", DEFAULT_SUFFIX); return resourceLoader.getResource(prefix + view + suffix).exists(); } return false; }
/** * Create a new ResourceArrayPropertyEditor with the given {@link ResourcePatternResolver} * and {@link PropertyResolver} (typically an {@link Environment}). * @param resourcePatternResolver the ResourcePatternResolver to use * @param propertyResolver the PropertyResolver to use * @param ignoreUnresolvablePlaceholders whether to ignore unresolvable placeholders * if no corresponding system property could be found */ public ResourceArrayPropertyEditor(ResourcePatternResolver resourcePatternResolver, PropertyResolver propertyResolver, boolean ignoreUnresolvablePlaceholders) { Assert.notNull(resourcePatternResolver, "ResourcePatternResolver must not be null"); this.resourcePatternResolver = resourcePatternResolver; this.propertyResolver = propertyResolver; this.ignoreUnresolvablePlaceholders = ignoreUnresolvablePlaceholders; }
@Override public boolean isTemplateAvailable(String view, Environment environment, ClassLoader classLoader, ResourceLoader resourceLoader) { if (ClassUtils.isPresent("com.mitchellbosecke.pebble.PebbleEngine", classLoader)) { PropertyResolver resolver = new RelaxedPropertyResolver(environment, "pebble."); String prefix = resolver.getProperty("prefix", PebbleProperties.DEFAULT_PREFIX); String suffix = resolver.getProperty("suffix", PebbleProperties.DEFAULT_SUFFIX); return resourceLoader.getResource(ResourceLoader.CLASSPATH_URL_PREFIX + prefix + view + suffix).exists(); } else { return false; } }
/** * Get a {@link LogFile} from the given Spring {@link Environment}. * @param propertyResolver the {@link PropertyResolver} used to obtain the logging * properties * @return a {@link LogFile} or {@code null} if the environment didn't contain any * suitable properties */ public static LogFile get(PropertyResolver propertyResolver) { String file = propertyResolver.getProperty(FILE_PROPERTY); String path = propertyResolver.getProperty(PATH_PROPERTY); if (StringUtils.hasLength(file) || StringUtils.hasLength(path)) { return new LogFile(file, path); } return null; }
protected List<PropertyResolver> getPropertyResolvers(Environment environment, Class<?> sourceClass) { List<PropertyResolver> resolvers = new ArrayList<PropertyResolver>(); resolvers.add(environment); resolvers.add(getVersionResolver(sourceClass)); resolvers.add(getAnsiResolver()); resolvers.add(getTitleResolver(sourceClass)); return resolvers; }
private PropertyResolver getTitleResolver(Class<?> sourceClass) { MutablePropertySources sources = new MutablePropertySources(); String applicationTitle = getApplicationTitle(sourceClass); Map<String, Object> titleMap = Collections.<String, Object>singletonMap( "application.title", (applicationTitle == null ? "" : applicationTitle)); sources.addFirst(new MapPropertySource("title", titleMap)); return new PropertySourcesPropertyResolver(sources); }
private void printBanner(Environment environment, PrintStream out) throws IOException { PropertyResolver properties = new RelaxedPropertyResolver(environment, "banner.image."); int width = properties.getProperty("width", Integer.class, 76); int height = properties.getProperty("height", Integer.class, 0); int margin = properties.getProperty("margin", Integer.class, 2); boolean invert = properties.getProperty("invert", Boolean.class, false); BufferedImage image = readImage(width, height); printBanner(image, margin, invert, out); }
@Test public void loggingFile() throws Exception { PropertyResolver resolver = getPropertyResolver("log.file", null); LogFile logFile = LogFile.get(resolver); Properties properties = new Properties(); logFile.applyTo(properties); assertThat(logFile.toString()).isEqualTo("log.file"); assertThat(properties.getProperty("LOG_FILE")).isEqualTo("log.file"); assertThat(properties.getProperty("LOG_PATH")).isNull(); }
@Test public void loggingPath() throws Exception { PropertyResolver resolver = getPropertyResolver(null, "logpath"); LogFile logFile = LogFile.get(resolver); Properties properties = new Properties(); logFile.applyTo(properties); assertThat(logFile.toString()).isEqualTo("logpath/spring.log"); assertThat(properties.getProperty("LOG_FILE")).isEqualTo("logpath/spring.log"); assertThat(properties.getProperty("LOG_PATH")).isEqualTo("logpath"); }
@Test public void loggingFileAndPath() throws Exception { PropertyResolver resolver = getPropertyResolver("log.file", "logpath"); LogFile logFile = LogFile.get(resolver); Properties properties = new Properties(); logFile.applyTo(properties); assertThat(logFile.toString()).isEqualTo("log.file"); assertThat(properties.getProperty("LOG_FILE")).isEqualTo("log.file"); assertThat(properties.getProperty("LOG_PATH")).isEqualTo("logpath"); }
private PropertyResolver getPropertyResolver(String file, String path) { Map<String, Object> properties = new LinkedHashMap<String, Object>(); properties.put("logging.file", file); properties.put("logging.path", path); PropertySource<?> propertySource = new MapPropertySource("properties", properties); MutablePropertySources propertySources = new MutablePropertySources(); propertySources.addFirst(propertySource); return new PropertySourcesPropertyResolver(propertySources); }
private String getResourceName(String view, Environment environment) { PropertyResolver resolver = new RelaxedPropertyResolver(environment, "spring.mvc.view."); String prefix = resolver.getProperty("prefix", WebMvcAutoConfiguration.DEFAULT_PREFIX); String suffix = resolver.getProperty("suffix", WebMvcAutoConfiguration.DEFAULT_SUFFIX); return prefix + view + suffix; }
@Override public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { PropertyResolver resolver = new RelaxedPropertyResolver( context.getEnvironment(), "security.oauth2.client."); String clientId = resolver.getProperty("client-id"); return new ConditionOutcome(StringUtils.hasLength(clientId), "Non empty security.oauth2.client.client-id"); }
@Override public boolean isTemplateAvailable(String view, Environment environment, ClassLoader classLoader, ResourceLoader resourceLoader) { if (ClassUtils.isPresent("groovy.text.TemplateEngine", classLoader)) { PropertyResolver resolver = new RelaxedPropertyResolver(environment, "spring.groovy.template."); String prefix = resolver.getProperty("prefix", GroovyTemplateProperties.DEFAULT_PREFIX); String suffix = resolver.getProperty("suffix", GroovyTemplateProperties.DEFAULT_SUFFIX); return resourceLoader.getResource(prefix + view + suffix).exists(); } return false; }