Example usage for org.apache.commons.lang.text StrSubstitutor replaceSystemProperties

List of usage examples for org.apache.commons.lang.text StrSubstitutor replaceSystemProperties

Introduction

In this page you can find the example usage for org.apache.commons.lang.text StrSubstitutor replaceSystemProperties.

Prototype

public static String replaceSystemProperties(Object source) 

Source Link

Document

Replaces all the occurrences of variables in the given source object with their matching values from the system properties.

Usage

From source file:com.googlecode.fascinator.common.JsonConfigHelper.java

/**
 * Gets the value of the specified node, with a specified default if the not
 * was not found/* w  w  w .j  av  a2s .c om*/
 * 
 * @param path XPath to node
 * @param defaultValue value to return if the node was not found
 * @return node value or defaultValue if not found
 */
public String get(String path, String defaultValue) {
    Object valueNode = null;
    try {
        valueNode = getJXPath().getValue(path);
    } catch (Exception e) {
    }
    String value = valueNode == null ? defaultValue : valueNode.toString();
    return StrSubstitutor.replaceSystemProperties(value);
}

From source file:com.haulmont.cuba.core.sys.AbstractWebAppContextLoader.java

protected void initAppProperties(ServletContext sc) {
    // get properties from web.xml
    String appProperties = sc.getInitParameter(APP_PROPS_PARAM);
    if (appProperties != null) {
        StrTokenizer tokenizer = new StrTokenizer(appProperties);
        for (String str : tokenizer.getTokenArray()) {
            int i = str.indexOf("=");
            if (i < 0)
                continue;
            String name = StringUtils.substring(str, 0, i);
            String value = StringUtils.substring(str, i + 1);
            if (!StringUtils.isBlank(name)) {
                AppContext.setProperty(name, value);
            }/*from   ww w.j a v a  2s.  c  o  m*/
        }
    }

    // get properties from a set of app.properties files defined in web.xml
    String propsConfigName = getAppPropertiesConfig(sc);
    if (propsConfigName == null)
        throw new IllegalStateException(APP_PROPS_CONFIG_PARAM + " servlet context parameter not defined");

    final Properties properties = new Properties();

    DefaultResourceLoader resourceLoader = new DefaultResourceLoader();
    StrTokenizer tokenizer = new StrTokenizer(propsConfigName);
    tokenizer.setQuoteChar('"');
    for (String str : tokenizer.getTokenArray()) {
        log.trace("Processing properties location: {}", str);
        str = StrSubstitutor.replaceSystemProperties(str);
        InputStream stream = null;
        try {
            if (ResourceUtils.isUrl(str) || str.startsWith(ResourceLoader.CLASSPATH_URL_PREFIX)) {
                Resource resource = resourceLoader.getResource(str);
                if (resource.exists())
                    stream = resource.getInputStream();
            } else {
                stream = sc.getResourceAsStream(str);
            }

            if (stream != null) {
                log.info("Loading app properties from {}", str);
                try (Reader reader = new InputStreamReader(stream, StandardCharsets.UTF_8)) {
                    properties.load(reader);
                }
            } else {
                log.trace("Resource {} not found, ignore it", str);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            IOUtils.closeQuietly(stream);
        }
    }

    for (Object key : properties.keySet()) {
        AppContext.setProperty((String) key, properties.getProperty((String) key).trim());
    }
}

From source file:ddf.security.PropertiesLoader.java

/**
 * Will attempt to load properties from a file using the given classloader. If that fails,
 * several other methods will be tried until the properties file is located.
 *
 * @param propertiesFile/*www .j a va  2 s.co  m*/
 * @param classLoader
 * @return Properties
 */
public static Properties loadProperties(String propertiesFile, ClassLoader classLoader) {
    boolean error = false;
    Properties properties = new Properties();
    if (propertiesFile != null) {
        try {
            LOGGER.debug("Attempting to load properties from {} with Spring PropertiesLoaderUtils.",
                    propertiesFile);
            properties = PropertiesLoaderUtils.loadAllProperties(propertiesFile);
        } catch (IOException e) {
            error = true;
            LOGGER.error("Unable to load properties using default Spring properties loader.", e);
        }
        if (error || properties.isEmpty()) {
            if (classLoader != null) {
                try {
                    LOGGER.debug(
                            "Attempting to load properties from {} with Spring PropertiesLoaderUtils with class loader.",
                            propertiesFile);
                    properties = PropertiesLoaderUtils.loadAllProperties(propertiesFile, classLoader);
                    error = false;
                } catch (IOException e) {
                    error = true;
                    LOGGER.error("Unable to load properties using default Spring properties loader.", e);
                }
            } else {
                try {
                    LOGGER.debug(
                            "Attempting to load properties from {} with Spring PropertiesLoaderUtils with class loader.",
                            propertiesFile);
                    properties = PropertiesLoaderUtils.loadAllProperties(propertiesFile,
                            PropertiesLoader.class.getClassLoader());
                    error = false;
                } catch (IOException e) {
                    error = true;
                    LOGGER.error("Unable to load properties using default Spring properties loader.", e);
                }
            }
        }

        if (error || properties.isEmpty()) {
            LOGGER.debug("Attempting to load properties from file system: {}", propertiesFile);
            File propFile = new File(propertiesFile);
            // If properties file has fully-qualified absolute path (which
            // the blueprint file specifies) then can load it directly.
            if (propFile.isAbsolute()) {
                LOGGER.debug("propertiesFile {} is absolute", propertiesFile);
                propFile = new File(propertiesFile);
            } else {
                String karafHome = System.getProperty("karaf.home");
                if (karafHome != null && !karafHome.isEmpty()) {
                    propFile = new File(karafHome, propertiesFile);
                } else {
                    karafHome = System.getProperty("ddf.home");
                    if (karafHome != null && !karafHome.isEmpty()) {
                        propFile = new File(karafHome, propertiesFile);
                    } else {
                        propFile = new File(propertiesFile);
                    }
                }
            }
            properties = new Properties();

            try (InputStreamReader reader = new InputStreamReader(new FileInputStream(propertiesFile),
                    StandardCharsets.UTF_8)) {
                properties.load(reader);
            } catch (FileNotFoundException e) {
                error = true;
                LOGGER.error("Could not find properties file: {}", propFile.getAbsolutePath(), e);
            } catch (IOException e) {
                error = true;
                LOGGER.error("Error reading properties file: {}", propFile.getAbsolutePath(), e);
            }
        }
        if (error || properties.isEmpty()) {
            LOGGER.debug("Attempting to load properties as a resource: {}", propertiesFile);
            InputStream ins = PropertiesLoader.class.getResourceAsStream(propertiesFile);
            if (ins != null) {
                try {
                    properties.load(ins);
                    ins.close();
                } catch (IOException e) {
                    LOGGER.error("Unable to load properties: {}", propertiesFile, e);
                } finally {
                    IOUtils.closeQuietly(ins);
                }
            }
        }

        //replace any ${prop} with system properties
        Properties filtered = new Properties();
        for (Map.Entry<?, ?> entry : properties.entrySet()) {
            filtered.put(StrSubstitutor.replaceSystemProperties(entry.getKey()),
                    StrSubstitutor.replaceSystemProperties(entry.getValue()));
        }
        properties = filtered;

    } else {
        LOGGER.debug("Properties file must not be null.");
    }

    return properties;
}

From source file:com.googlecode.fascinator.common.JsonConfigHelper.java

/**
 * Gets values of the specified node as a list. Use this method for JSON
 * arrays./*w w w  .  j av a 2 s.  com*/
 * 
 * @param path XPath to node
 * @return value list, possibly empty
 */
public List<Object> getList(String path) {
    List<Object> valueList = new ArrayList<Object>();
    Iterator<?> valueIterator = getJXPath().iterate(path);
    while (valueIterator.hasNext()) {
        Object value = valueIterator.next();
        valueList.add(value instanceof String ? StrSubstitutor.replaceSystemProperties(value) : value);
    }
    return valueList;
}

From source file:com.haulmont.cuba.desktop.App.java

protected void initHomeDir() {
    String homeDir = System.getProperty(DesktopAppContextLoader.HOME_DIR_SYS_PROP);
    if (StringUtils.isBlank(homeDir)) {
        homeDir = getDefaultHomeDir();//from   w w w .jav  a 2 s  .co  m
    }
    homeDir = StrSubstitutor.replaceSystemProperties(homeDir);
    System.setProperty(DesktopAppContextLoader.HOME_DIR_SYS_PROP, homeDir);

    File file = new File(homeDir);
    if (!file.exists()) {
        boolean success = file.mkdirs();
        if (!success) {
            System.out.println("Unable to create home dir: " + homeDir);
            System.exit(-1);
        }
    }
    if (!file.isDirectory()) {
        System.out.println("Invalid home dir: " + homeDir);
        System.exit(-1);
    }
}

From source file:com.googlecode.fascinator.common.JsonConfigHelper.java

/**
 * Gets a map of the child nodes of the specified node
 * //  w w  w. ja  va  2s  .co  m
 * @param path XPath to node
 * @return node map, possibly empty
 */
public Map<String, Object> getMap(String path) {
    Map<String, Object> valueMap = new LinkedHashMap<String, Object>();
    Object valueNode = getJXPath().getValue(path);
    if (valueNode instanceof Map) {
        Map<String, Object> map = (Map<String, Object>) valueNode;
        for (String key : map.keySet()) {
            Object value = map.get(key);
            if (value instanceof String) {
                valueMap.put(key, StrSubstitutor.replaceSystemProperties(value));
            } else {
                valueMap.put(key, value);
            }
        }
    }
    return valueMap;
}

From source file:com.googlecode.fascinator.common.JsonSimple.java

/**
 * Retrieve the String value on the given path.
 *
 * @param defaultValue : The fallback value to use if the path is
 * invalid or not found/* www  . ja  v a2 s .  c o m*/
 * @param path : An array of indeterminate length to use as the path
 * @return String : The String value found on the given path, or null if
 * no default provided
 */
public String getString(String defaultValue, Object... path) {
    String response = null;

    Object object = getPath(path);
    if (object == null) {
        response = defaultValue;
    } else {
    }
    if (isNumber(object)) {
        response = Integer.toString(makeNumber(object));
    }
    if (object instanceof String) {
        response = (String) object;
    }
    if (object instanceof Boolean) {
        response = Boolean.toString((Boolean) object);
    }

    if (object instanceof JSONArray) {
        jsonArray = (JSONArray) object;
        if (jsonArray.size() == 1) {
            Object value = jsonArray.get(0);
            if (value instanceof String) {
                response = (String) value;
            }
        }
        if (!(response instanceof String)) {
            log.warn("Unable to convert JSONArray: " + object + " to string.");
        }
    }

    // Are we substituting system properites?
    if (substitueProperties) {
        response = StrSubstitutor.replaceSystemProperties(response);
    }

    return response;
}

From source file:com.googlecode.fascinator.common.JsonSimple.java

/**
 * <p>//w  ww. j  a va2s  .  c o m
 * Retrieve a list of Strings found on the given path. Note that this is a
 * utility function, and not designed for data traversal. It <b>will</b>
 * only retrieve Strings found on the provided node, and the node must be
 * a JSONArray.
 * </p>
 *
 * @param path : An array of indeterminate length to use as the path
 * @return List<String> : A list of Strings, null if the node is not found
 */
public List<String> getStringList(Object... path) {
    Object target = getPath(path);
    List<String> response = new LinkedList<String>();
    if (isArray(target)) {
        if (substitueProperties) {
            List<String> temp = JsonSimple.getStringList((JSONArray) target);
            for (String string : temp) {
                response.add(StrSubstitutor.replaceSystemProperties(string));
            }
            return response;
        } else {
            return JsonSimple.getStringList((JSONArray) target);
        }
    }
    if (isString(target)) {
        // Are we substituting system properites?
        if (substitueProperties) {
            response.add(StrSubstitutor.replaceSystemProperties((String) target));
        } else {
            response.add((String) target);
        }
        return response;
    }
    return null;
}

From source file:org.apache.qpid.disttest.charting.definition.SeriesDefinitionCreator.java

public List<SeriesDefinition> createFromProperties(Properties properties) {
    final List<SeriesDefinition> seriesDefinitions = new ArrayList<SeriesDefinition>();

    int index = 1;
    boolean moreSeriesDefinitions = true;
    while (moreSeriesDefinitions) {
        String seriesStatement = properties.getProperty(String.format(SERIES_STATEMENT_KEY_FORMAT, index));
        String seriesLegend = properties.getProperty(String.format(SERIES_LEGEND_KEY_FORMAT, index));
        String seriesDir = StrSubstitutor.replaceSystemProperties(
                properties.getProperty(String.format(SERIES_DIRECTORY_KEY_FORMAT, index)));
        String seriesColourName = properties.getProperty(String.format(SERIES_COLOUR_NAME_FORMAT, index));
        Integer seriesStrokeWidth = properties
                .getProperty(String.format(SERIES_STROKE_WIDTH_FORMAT, index)) == null ? null
                        : Integer.parseInt(
                                properties.getProperty(String.format(SERIES_STROKE_WIDTH_FORMAT, index)));

        if (seriesStatement != null) {
            final SeriesDefinition seriesDefinition = new SeriesDefinition(seriesStatement, seriesLegend,
                    seriesDir, seriesColourName, seriesStrokeWidth);
            seriesDefinitions.add(seriesDefinition);
        } else {//from  ww w .ja  v  a2s  . co m
            moreSeriesDefinitions = false;
        }
        index++;
    }
    return seriesDefinitions;
}

From source file:org.codice.ddf.admin.common.services.ServiceCommons.java

public String resolveProperty(String str) {
    return StrSubstitutor.replaceSystemProperties(str);
}