
org.kuali.common.util.spring.SpringUtils Maven / Gradle / Ivy
/**
* Copyright 2010-2013 The Kuali Foundation
*
* Licensed under the Educational Community License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.opensource.org/licenses/ecl2.php
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kuali.common.util.spring;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import org.codehaus.plexus.util.StringUtils;
import org.kuali.common.util.Assert;
import org.kuali.common.util.CollectionUtils;
import org.kuali.common.util.FormatUtils;
import org.kuali.common.util.LocationUtils;
import org.kuali.common.util.LoggerLevel;
import org.kuali.common.util.LoggerUtils;
import org.kuali.common.util.Project;
import org.kuali.common.util.ProjectContext;
import org.kuali.common.util.ProjectUtils;
import org.kuali.common.util.PropertyUtils;
import org.kuali.common.util.ReflectionUtils;
import org.kuali.common.util.Str;
import org.kuali.common.util.execute.Executable;
import org.kuali.common.util.execute.SpringExecutable;
import org.kuali.common.util.nullify.NullUtils;
import org.kuali.common.util.property.Constants;
import org.kuali.common.util.property.ProjectProperties;
import org.kuali.common.util.service.DefaultSpringService;
import org.kuali.common.util.service.PropertySourceContext;
import org.kuali.common.util.service.SpringContext;
import org.kuali.common.util.service.SpringService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.BeanFactoryUtils;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.EnumerablePropertySource;
import org.springframework.core.env.Environment;
import org.springframework.core.env.MutablePropertySources;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.core.env.PropertySource;
public class SpringUtils {
private static final Logger logger = LoggerFactory.getLogger(SpringUtils.class);
private static final String GLOBAL_SPRING_PROPERTY_SOURCE_NAME = "springPropertySource";
public static SpringContext getSpringContext(List> annotatedClasses, ProjectContext project, List others) {
// This PropertySource object is backed by a set of properties that has been
// 1 - fully resolved
// 2 - contains all properties needed by Spring
// 3 - contains system/environment properties where system/env properties override loaded properties
PropertySource> source = getGlobalPropertySource(project, others);
// Setup a property source context such that our single property source is the only one registered with Spring
// This will make it so our PropertySource is the ONLY thing used to resolve placeholders
PropertySourceContext psc = new PropertySourceContext(source, true);
// Setup a Spring context
SpringContext context = new SpringContext();
// Supply Spring with our PropertySource
context.setPropertySourceContext(psc);
// Supply Spring with java classes containing annotated config
context.setAnnotatedClasses(annotatedClasses);
// Return a Spring context configured with a single property source
return context;
}
public static SpringContext getSpringContext(Class> annotatedClass, ProjectContext project, List others) {
return getSpringContext(CollectionUtils.asList(annotatedClass), project, others);
}
/**
* project
needs to be a top level project eg rice-sampleapp, olefs-webapp. others
is projects for submodules organized into a list where the last one
* in wins.
*/
public static PropertySource> getGlobalPropertySource(ProjectContext project, ProjectContext other) {
return getGlobalPropertySource(project, Arrays.asList(other));
}
/**
* project
needs to be a top level project eg rice-sampleapp, olefs-webapp. others
is projects for submodules organized into a list where the last one
* in wins.
*/
public static PropertySource> getGlobalPropertySource(ProjectContext project, List others) {
return getGlobalPropertySource(project, others, null);
}
/**
* project
needs to be a top level project eg rice-sampleapp, olefs-webapp. others
is projects for submodules organized into a list where the last one
* in wins.
*/
public static PropertySource> getGlobalPropertySource(ProjectContext project, List others, Properties properties) {
ProjectProperties projectProperties = ProjectUtils.loadProjectProperties(project);
Properties existing = projectProperties.getPropertiesContext().getProperties();
Properties combined = PropertyUtils.combine(existing, properties);
projectProperties.getPropertiesContext().setProperties(combined);
List otherProjectProperties = new ArrayList();
for (ProjectContext other : CollectionUtils.toEmptyList(others)) {
ProjectProperties opp = ProjectUtils.loadProjectProperties(other);
otherProjectProperties.add(opp);
}
// Get a PropertySource object backed by the properties loaded from the list as well as system/environment properties
return getGlobalPropertySource(projectProperties, otherProjectProperties);
}
/**
* project
needs to be a top level project eg rice-sampleapp, olefs-webapp. others
is projects for submodules organized into a list where the last one
* in wins.
*/
public static PropertySource> getGlobalPropertySource(ProjectProperties project, List others) {
// Property loading uses a "last one in wins" strategy
List list = new ArrayList();
// Add project properties first so they can be used to resolve locations
list.add(project);
// Load in project properties
list.addAll(others);
// Add project properties last so they override loaded properties
list.add(project);
// Get a PropertySource object backed by the properties loaded from the list as well as system/environment properties
return getGlobalPropertySource(GLOBAL_SPRING_PROPERTY_SOURCE_NAME, list);
}
public static List getIncludes(Environment env, String key, String defaultValue) {
String includes = SpringUtils.getProperty(env, key, defaultValue);
if (NullUtils.isNull(includes) || StringUtils.equals(includes, Constants.WILDCARD)) {
return new ArrayList();
} else {
return CollectionUtils.getTrimmedListFromCSV(includes);
}
}
public static List getIncludes(Environment env, String key) {
return getIncludes(env, key, null);
}
public static List getExcludes(Environment env, String key, String defaultValue) {
String excludes = SpringUtils.getProperty(env, key, defaultValue);
if (NullUtils.isNullOrNone(excludes)) {
return new ArrayList();
} else {
return CollectionUtils.getTrimmedListFromCSV(excludes);
}
}
public static List getExcludes(Environment env, String key) {
return getExcludes(env, key, null);
}
/**
* Given a property holding the name of a class, return an instance of that class
*/
public static T getInstance(Environment env, String key, Class defaultValue) {
String className = getProperty(env, key, defaultValue.getCanonicalName());
return ReflectionUtils.newInstance(className);
}
/**
* Given a property holding the name of a class, return an instance of that class
*/
public static T getInstance(Environment env, String key) {
String className = getProperty(env, key, null);
return ReflectionUtils.newInstance(className);
}
public static List getListFromCSV(Environment env, String key, String defaultValue) {
String csv = SpringUtils.getProperty(env, key, defaultValue);
return CollectionUtils.getTrimmedListFromCSV(csv);
}
@Deprecated
public static List> getPropertySources(SpringService service, Class> annotatedClass, String mavenPropertiesBeanName, Properties mavenProperties) {
return getPropertySources(annotatedClass, mavenPropertiesBeanName, mavenProperties);
}
public static List> getPropertySources(Class> annotatedClass, String mavenPropertiesBeanName, Properties mavenProperties) {
ConfigurableApplicationContext parent = null;
if (mavenProperties == null) {
parent = getConfigurableApplicationContext();
} else {
parent = getContextWithPreRegisteredBean(mavenPropertiesBeanName, mavenProperties);
}
AnnotationConfigApplicationContext child = new AnnotationConfigApplicationContext();
child.setParent(parent);
child.register(annotatedClass);
child.refresh();
return SpringUtils.getPropertySources(child);
}
@Deprecated
public static List> getPropertySources(SpringService service, String location, String mavenPropertiesBeanName, Properties mavenProperties) {
return getPropertySources(location, mavenPropertiesBeanName, mavenProperties);
}
public static List> getPropertySources(String location, String mavenPropertiesBeanName, Properties mavenProperties) {
String[] locationsArray = { location };
ConfigurableApplicationContext parent = getContextWithPreRegisteredBean(mavenPropertiesBeanName, mavenProperties);
ConfigurableApplicationContext child = new ClassPathXmlApplicationContext(locationsArray, parent);
return SpringUtils.getPropertySources(child);
}
public static Executable getSpringExecutable(Environment env, boolean skip, PropertySource> ps, List> annotatedClasses) {
/**
* This line creates a property source containing 100% of the properties needed by Spring to resolve any/all placeholders. It will be the only property source available to
* Spring so it needs to include system properties and environment variables
*/
PropertySourceContext psc = new PropertySourceContext(ps, true);
// Setup the Spring context
SpringContext context = new SpringContext();
context.setAnnotatedClasses(annotatedClasses);
context.setPropertySourceContext(psc);
// Load the context
SpringExecutable se = new SpringExecutable();
se.setService(new DefaultSpringService());
se.setContext(context);
se.setSkip(skip);
return se;
}
public static int getInteger(Environment env, String key) {
String value = getProperty(env, key);
return Integer.parseInt(value);
}
public static int getInteger(Environment env, String key, int defaultValue) {
String value = getProperty(env, key, Integer.toString(defaultValue));
return Integer.parseInt(value);
}
public static long getLong(Environment env, String key) {
String value = getProperty(env, key);
return Long.parseLong(value);
}
public static long getLong(Environment env, String key, long defaultValue) {
String value = getProperty(env, key, Long.toString(defaultValue));
return Long.parseLong(value);
}
public static double getDouble(Environment env, String key) {
String value = getProperty(env, key);
return Double.parseDouble(value);
}
public static double getDouble(Environment env, String key, double defaultValue) {
String value = getProperty(env, key, Double.toString(defaultValue));
return Double.parseDouble(value);
}
/**
* Parse milliseconds from a time string that ends with a unit of measure. If no unit of measure is provided, milliseconds is assumed. Unit of measure is case insensitive.
*
* @see FormatUtils.getMillis(String time)
*/
public static long getMillis(Environment env, String key, String defaultValue) {
String value = getProperty(env, key, defaultValue);
return FormatUtils.getMillis(value);
}
/**
* Parse bytes from a size string that ends with a unit of measure. If no unit of measure is provided, bytes is assumed. Unit of measure is case insensitive.
*
* @see FormatUtils.getBytes(String size)
*/
public static long getBytes(Environment env, String key, String defaultValue) {
String value = getProperty(env, key, defaultValue);
return FormatUtils.getBytes(value);
}
/**
* Parse bytes from a size string that ends with a unit of measure. If no unit of measure is provided, bytes is assumed. Unit of measure is case insensitive.
*
* @see FormatUtils.getBytes(String size)
*/
public static long getBytes(Environment env, String key) {
String value = getProperty(env, key);
return FormatUtils.getBytes(value);
}
public static File getFile(Environment env, String key) {
String value = getProperty(env, key);
return new File(value);
}
public static boolean getBoolean(Environment env, String key, boolean defaultValue) {
String value = getProperty(env, key, Boolean.toString(defaultValue));
return Boolean.parseBoolean(value);
}
public static boolean getBoolean(Environment env, String key) {
String value = getProperty(env, key);
return Boolean.parseBoolean(value);
}
public static PropertySource> getGlobalPropertySource(String name, List pps) {
// Load them from disk
Properties source = PropertyUtils.load(pps);
// Add in system/environment properties
Properties globalSource = PropertyUtils.getGlobalProperties(source);
// Prepare them so they are ready for use
PropertyUtils.prepareContextProperties(globalSource);
PropertyUtils.info(globalSource);
// Return a PropertySource backed by the properties
return new PropertiesPropertySource(name, globalSource);
}
public static PropertySource> getPropertySource(String name, List pps) {
// Load them from disk
Properties source = PropertyUtils.load(pps);
// Prepare them so they are ready for use
PropertyUtils.prepareContextProperties(source);
// Return a PropertySource backed by the properties
return new PropertiesPropertySource(name, source);
}
/**
* Converts a GAV into Spring's classpath style notation for the default project properties context.
*
*
* org.kuali.common:kuali-jdbc -> classpath:org/kuali/common/kuali-jdbc-properties-context.xml
*
*/
public static String getDefaultPropertyContextLocation(String gav) {
Assert.hasText(gav, "gav has no text");
Project p = ProjectUtils.getProject(gav);
return "classpath:" + Str.getPath(p.getGroupId()) + "/" + p.getArtifactId() + "-properties-context.xml";
}
/**
* Make sure all of the locations actually exist
*/
public static void validateExists(List locations) {
StringBuilder sb = new StringBuilder();
for (String location : locations) {
if (!LocationUtils.exists(location)) {
sb.append("Location [" + location + "] does not exist\n");
}
}
if (sb.length() > 0) {
throw new IllegalArgumentException(sb.toString());
}
}
public static ConfigurableApplicationContext getContextWithPreRegisteredBeans(String id, String displayName, List beanNames, List
© 2015 - 2025 Weber Informatics LLC | Privacy Policy