Example usage for org.apache.commons.lang.text StrLookup StrLookup

List of usage examples for org.apache.commons.lang.text StrLookup StrLookup

Introduction

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

Prototype

protected StrLookup() 

Source Link

Document

Constructor.

Usage

From source file:at.bestsolution.persistence.java.Util.java

public static final ProcessedSQL processSQL(String sql, final Function<String, List<?>> listLookup) {
    final List<String> dynamicParameterNames = new ArrayList<String>();
    final Map<String, List<TypedValue>> typedValuesMap = new HashMap<String, List<TypedValue>>();
    String s = new StrSubstitutor(new StrLookup() {

        @Override/*ww  w .j  av  a 2 s .co  m*/
        public String lookup(String key) {
            List<?> data = listLookup.execute(key);
            if (data == null) {
                dynamicParameterNames.add(key);
                return "?";
            } else {
                List<TypedValue> list = null;
                StringBuilder rv = new StringBuilder();
                for (Object o : data) {
                    if (rv.length() > 0) {
                        rv.append(", ");
                    }

                    if (o == null) {
                        rv.append("NULL");
                    } else if (o instanceof Long || o instanceof Integer) {
                        rv.append(o);
                    } else {
                        if (list == null) {
                            list = new ArrayList<TypedValue>();
                            typedValuesMap.put(key, list);
                        }
                        list.add(new TypedValue(o, JDBCType.fromJavaType(o.getClass())));
                        rv.append("?");
                    }
                }
                return rv.toString();
            }
        }
    }, "#{", "}", '#').replace(sql);
    return new ProcessedSQL(s, dynamicParameterNames, null);
}

From source file:at.bestsolution.persistence.java.Util.java

public static final ProcessedSQL processSQL(String sql) {
    final List<String> dynamicParameterNames = new ArrayList<String>();
    String s = new StrSubstitutor(new StrLookup() {

        @Override/*from ww  w  . jav a2 s . c  o  m*/
        public String lookup(String key) {
            dynamicParameterNames.add(key);
            return "?";
        }
    }, "#{", "}", '#').replace(sql);
    return new ProcessedSQL(s, dynamicParameterNames, null);
}

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

private String handleInterpolation(String value) {
    StrSubstitutor substitutor = new StrSubstitutor(new StrLookup() {
        @Override//  w  ww .j a  v a2s  .  c  o m
        public String lookup(String key) {
            String property = getSystemOrAppProperty(key);
            return property != null ? property : System.getProperty(key);
        }
    });
    return substitutor.replace(value);
}

From source file:com.thinkbiganalytics.feedmgr.nifi.PropertyExpressionResolver.java

public String replaceAll(String str, String replacement) {
    if (str != null) {
        StrLookup lookup = new StrLookup() {
            @Override//from  w ww.  ja v a2s . c om
            public String lookup(String key) {
                return replacement;
            }
        };
        StrSubstitutor ss = new StrSubstitutor(lookup);
        return ss.replace(str);
    }
    return null;
}

From source file:com.thinkbiganalytics.feedmgr.nifi.PropertyExpressionResolver.java

/**
 * Resolve the str with values from the supplied {@code properties} This will recursively fill out the str looking back at the properties to get the correct value. NOTE the property values will be
 * overwritten if replacement is found!/*www . j ava 2s.c  o m*/
 */
public ResolvedVariables resolveVariables(String str, List<NifiProperty> properties) {
    ResolvedVariables variables = new ResolvedVariables(str);

    StrLookup resolver = new StrLookup() {
        @Override
        public String lookup(String key) {
            Optional<NifiProperty> optional = properties.stream().filter(prop -> key.equals(prop.getKey()))
                    .findFirst();
            if (optional.isPresent()) {
                NifiProperty property = optional.get();
                String value = StringUtils.isNotBlank(property.getValue()) ? property.getValue().trim() : "";
                variables.getResolvedVariables().put(property.getKey(), value);
                return value;
            } else {
                return null;
            }
        }
    };

    StrSubstitutor ss = new StrSubstitutor(resolver);
    variables.setResolvedString(ss.replace(str));

    Map<String, String> map = variables.getResolvedVariables();
    Map<String, String> vars = map.entrySet().stream()
            .collect(Collectors.toMap(Map.Entry::getKey, entry -> ss.replace(entry.getValue())));
    variables.getResolvedVariables().putAll(vars);

    return variables;
}

From source file:com.haulmont.cuba.testsupport.TestContainer.java

protected void initAppProperties() {
    final Properties properties = new Properties();

    List<String> locations = getAppPropertiesFiles();
    DefaultResourceLoader resourceLoader = new DefaultResourceLoader();
    for (String location : locations) {
        Resource resource = resourceLoader.getResource(location);
        if (resource.exists()) {
            InputStream stream = null;
            try {
                stream = resource.getInputStream();
                properties.load(stream);
            } catch (IOException e) {
                throw new RuntimeException(e);
            } finally {
                IOUtils.closeQuietly(stream);
            }/*  w  ww . jav a 2 s.com*/
        } else {
            log.warn("Resource " + location + " not found, ignore it");
        }
    }

    StrSubstitutor substitutor = new StrSubstitutor(new StrLookup() {
        @Override
        public String lookup(String key) {
            String subst = properties.getProperty(key);
            return subst != null ? subst : System.getProperty(key);
        }
    });
    for (Object key : properties.keySet()) {
        String value = substitutor.replace(properties.getProperty((String) key));
        appProperties.put((String) key, value);
    }

    File dir;
    dir = new File(appProperties.get("cuba.confDir"));
    dir.mkdirs();
    dir = new File(appProperties.get("cuba.logDir"));
    dir.mkdirs();
    dir = new File(appProperties.get("cuba.tempDir"));
    dir.mkdirs();
    dir = new File(appProperties.get("cuba.dataDir"));
    dir.mkdirs();
}

From source file:com.thinkbiganalytics.feedmgr.nifi.PropertyExpressionResolver.java

/**
 * Resolves the variables in the value of the specified property.
 *
 * @param property the property//from w  w  w .j  a  va  2s .c  o  m
 * @param metadata the feed
 * @return the result of the transformation
 */
private ResolveResult resolveVariables(@Nonnull final NifiProperty property,
        @Nonnull final FeedMetadata metadata) {
    // Filter blank values
    final String value = property.getValue();
    if (StringUtils.isBlank(value)) {
        return new ResolveResult(false, false);
    }

    final boolean[] hasConfig = { false };
    final boolean[] isModified = { false };

    StrLookup resolver = new StrLookup() {
        @Override
        public String lookup(String variable) {
            // Resolve configuration variables
            final String configValue = getConfigurationPropertyValue(property, variable);
            if (configValue != null && property.getValue() != null
                    && !property.getValue().equalsIgnoreCase(configValue)) {
                hasConfig[0] = true;
                isModified[0] = true;
                //if this is the first time we found the config var, set the template value correctly
                if (!property.isContainsConfigurationVariables()) {
                    property.setTemplateValue(property.getValue());
                    property.setContainsConfigurationVariables(true);
                }
                return configValue;

            }

            // Resolve metadata variables
            try {
                final String metadataValue = getMetadataPropertyValue(metadata, variable);
                if (metadataValue != null) {
                    isModified[0] = true;
                    return metadataValue;
                }
            } catch (Exception e) {
                log.error("Unable to resolve variable: " + variable, e);
            }

            return null;
        }
    };
    StrSubstitutor ss = new StrSubstitutor(resolver);
    ss.setEnableSubstitutionInVariables(true);
    //escape
    String val = StringUtils.trim(ss.replace(value));
    //fix
    property.setValue(val);

    return new ResolveResult(hasConfig[0], isModified[0]);
}

From source file:ome.services.blitz.repo.ManagedRepositoryI.java

/**
 * Turn the current template into a relative path. Makes use of the data
 * returned by {@link #replacementMap(Ice.Current)}.
 *
 * @param curr//from w  ww.ja va2  s. c  om
 * @return
 */
protected String expandTemplate(final String template, EventContext ec) {

    if (template == null) {
        return ""; // EARLY EXIT.
    }

    final Map<String, String> map = replacementMap(ec);
    final StrSubstitutor strSubstitutor = new StrSubstitutor(new StrLookup() {
        @Override
        public String lookup(final String key) {
            return map.get(key);
        }
    }, "%", "%", '%');
    return strSubstitutor.replace(template);
}

From source file:org.apache.marmotta.platform.core.services.config.ConfigurationServiceImpl.java

/**
 * Initialise the ConfigurationService. Takes the marmotta.home system property from the servlet
 * init parameters/* w ww .  j  a va  2  s .c o m*/
 * (web.xml) as bootstrap home. In case a system-config.properties file is found in this
 * directory, the
 * configuration is then loaded from this file. In case a system-config.properties file does not
 * yet exist,
 * the method loads bootstrap settings from the resource default-config.properties in the
 * classpath (in the
 * standard bundling, the file is in the kiwi-core-XXX.jar archive). After loading the
 * configuration, the
 * service initialises the plugin subsystem and the SOLR home directory by unpacking the default
 * configuration
 * if the SOLR configuration does not yet exist.
 * @param override
 */
@Override
public void initialize(String home, Configuration override) {
    lock.writeLock().lock();
    try {
        initialising = true;

        log.info("Apache Marmotta Configuration Service starting up ...");

        if (isTomcat7()) {
            log.info("Apache Marmotta running on Apache Tomcat 7.x");
        } else if (isTomcat6()) {
            log.info("Apache Marmotta running on Apache Tomcat <= 6.x");
        } else if (isJetty7()) {
            log.info("Apache Marmotta running on Jetty 7.x");
        } else if (isJetty6()) {
            log.info("Apache Marmotta running on Jetty <= 6.x");
        } else {
            log.info("Apache Marmotta running on an unknown servlet container");
        }

        setHome(home);

        if (getHome() != null) {
            File f1 = new File(getHome());
            if (!f1.exists()) {
                f1.mkdirs();
            }
            // ensure directory for user configuration files
            File f2 = new File(getHome() + File.separator + DIR_CONFIG);
            if (!f2.exists()) {
                f2.mkdirs();
            }

            // ensure directory for logging messages
            File f3 = new File(getHome() + File.separator + DIR_LOG);
            if (!f3.exists()) {
                f3.mkdirs();
            }

            // ensure directory for importing data
            File f4 = new File(getHome() + File.separator + DIR_IMPORT);
            if (!f4.exists()) {
                f4.mkdirs();
            }

        }

        // the save configuration will be in the  home directory
        try {
            if (getHome() != null) {
                configFileName = getHome() + File.separator + "system-config.properties";
                metaFileName = getHome() + File.separator + "system-meta.properties";

                File configFile = new File(configFileName);
                if (!configFile.exists()) {
                    log.info("creating system configuration in configuration file {}",
                            configFile.getAbsolutePath());
                } else {
                    log.info("reading system configuration from existing configuration file {}",
                            configFile.getAbsolutePath());
                }
                saveConfiguration = new PropertiesConfiguration(configFile);

                File metaFile = new File(metaFileName);
                if (!metaFile.exists()) {
                    log.info("creating system configuration metadata in configuration file {}",
                            metaFile.getAbsolutePath());
                } else {
                    log.info("reading system configuration metadata from existing configuration file {}",
                            metaFile.getAbsolutePath());
                }
                saveMetadata = new PropertiesConfiguration(metaFile);

            } else {
                log.error(
                        "error while initialising configuration: no marmotta.home property given; creating memory-only configuration");
                saveConfiguration = new MapConfiguration(new HashMap<String, Object>());
                saveMetadata = new MapConfiguration(new HashMap<String, Object>());
            }
        } catch (Exception e) {
            log.error("error while initialising configuration file {}: {}; creating memory-only configuration",
                    configFileName, e.getMessage());
            saveConfiguration = new MapConfiguration(new HashMap<String, Object>());
            saveMetadata = new MapConfiguration(new HashMap<String, Object>());
        }
        config = new FallbackConfiguration();
        final ConfigurationInterpolator _int = config.getInterpolator();
        _int.registerLookup("pattern.quote", new StrLookup() {
            @Override
            public String lookup(String key) {
                return Pattern.quote(_int.getDefaultLookup().lookup(key));
            }
        });
        _int.registerLookup("urlencode", new StrLookup() {
            @Override
            public String lookup(String key) {
                try {
                    return URLEncoder.encode(_int.getDefaultLookup().lookup(key), "utf8");
                } catch (UnsupportedEncodingException e) {
                    return _int.getDefaultLookup().lookup(key);
                }
            }
        });
        config.addConfiguration(saveConfiguration, true);

        // load all default-config.properties

        try {
            Enumeration<URL> configs = this.getClass().getClassLoader()
                    .getResources("config-defaults.properties");
            while (configs.hasMoreElements()) {
                URL url = configs.nextElement();
                config.addConfiguration(new PropertiesConfiguration(url));
            }

        } catch (IOException e) {
            log.error("I/O error while loading default configurations", e);
        } catch (ConfigurationException e) {
            log.error("configuration error while loading default configurations", e);
        }

        // legacy support (to be removed)
        try {
            Enumeration<URL> configs = this.getClass().getClassLoader()
                    .getResources("default-config.properties");
            while (configs.hasMoreElements()) {
                URL url = configs.nextElement();
                config.addConfiguration(new PropertiesConfiguration(url));
                log.warn(
                        "found legacy configuration file {}; should be replaced with per-module configuration!",
                        url);
            }

        } catch (IOException e) {
            log.error("I/O error while loading default configurations", e);
        } catch (ConfigurationException e) {
            log.error("configuration error while loading default configurations", e);
        }

        // create the configuration that is responsible for getting metadata about configuration keys in the main
        // configuration; since the keys will be different, we store changes also to the main save configuration
        configDescriptions = new FallbackConfiguration();
        configDescriptions.addConfiguration(saveMetadata, true);
        try {
            Enumeration<URL> configs = this.getClass().getClassLoader()
                    .getResources("config-descriptions.properties");
            while (configs.hasMoreElements()) {
                URL url = configs.nextElement();
                configDescriptions.addConfiguration(new PropertiesConfiguration(url));
            }

        } catch (IOException e) {
            log.error("I/O error while loading configuration descriptions", e);
        } catch (ConfigurationException e) {
            log.error("configuration error while loading configuration descriptions", e);
        }

        // setup home if it is given as system property,
        // the bootstrap configuration is overwritten
        if (getHome() != null) {
            config.setProperty("marmotta.home", getHome());
        }

        // in case override configuration is given, change all settings in the configuration accordingly
        if (override != null) {
            for (Iterator<String> it = override.getKeys(); it.hasNext();) {
                String key = it.next();

                config.setProperty(key, override.getProperty(key));
            }
        }

        save();

        // configuration service is now ready to use
        initialised = true;

        loggingStartEvent.fire(new LoggingStartEvent());

        // this should maybe move to the KiWiPreStartupFilter ...
        initDatabaseConfiguration();

        save();

        log.info("Apache Marmotta Configuration Service: initialisation completed");

        configurationInitEvent.fire(new ConfigurationServiceInitEvent());

    } finally {
        lock.writeLock().unlock();
    }

}

From source file:org.eurekastreams.server.action.execution.notification.notifier.NotificationMessageBuilderHelper.java

/**
 * Returns a variable-substituted version of the activity's body.
 * /*from  w ww . ja v a  2s  .c o  m*/
 * @param activity
 *            Activity.
 * @param context
 *            Velocity context.
 * @return Activity body text.
 */
public String resolveActivityBody(final ActivityDTO activity, final Context context) {
    StrSubstitutor transform = new StrSubstitutor(new StrLookup() {
        @Override
        public String lookup(final String variableName) {
            if ("ACTORNAME".equals(variableName)) {
                return activity.getActor().getDisplayName();
            } else {
                return null;
            }
        }
    }, VARIABLE_START_MARKER, VARIABLE_END_MARKER, StrSubstitutor.DEFAULT_ESCAPE);
    String result = transform.replace(activity.getBaseObjectProperties().get("content"));
    return result;
}