Search in sources :

Example 1 with TransformationVariableScope

use of eu.esdihumboldt.hale.common.align.transformation.function.TransformationVariableScope in project hale by halestudio.

the class DefaultTransformationVariables method replaceVariables.

@Override
public String replaceVariables(String input, boolean failUnresolved) {
    if (input == null) {
        return null;
    }
    String result = input;
    try {
        String re = "\\{\\{([^}]+)\\}\\}";
        Pattern p = Pattern.compile(re);
        Matcher m = p.matcher(input);
        // Iterate over identifiers and determine values.
        while (m.find()) {
            String reference = m.group(1);
            if (reference != null) {
                try {
                    String varName;
                    TransformationVariableScope scope = TransformationVariableScope.transformation;
                    int sepIndex = reference.indexOf(':');
                    if (sepIndex > 0) {
                        String scopeName = reference.substring(0, sepIndex);
                        scope = TransformationVariableScope.valueOf(scopeName);
                        varName = reference.substring(sepIndex + 1);
                    } else {
                        // default scope
                        varName = reference;
                    }
                    Value value = getVariable(scope, varName);
                    String strValue = value.as(String.class);
                    if (strValue != null) {
                        // only replace if there is a value
                        String rx = "\\{\\{" + Pattern.quote(reference) + "\\}\\}";
                        result = result.replaceAll(rx, strValue);
                    } else if (failUnresolved) {
                        throw new IllegalStateException("Cannot resolve variable reference " + reference);
                    }
                } catch (IllegalStateException e) {
                    throw e;
                } catch (Exception e) {
                    if (failUnresolved) {
                        throw new IllegalStateException("Cannot resolve variable reference " + reference);
                    }
                    log.warn("Cannot resolve variable reference " + reference);
                }
            }
        }
    } catch (IllegalStateException e) {
        throw e;
    } catch (Exception e) {
        log.error("Error replacing transformation variables", e);
    }
    return result;
}
Also used : Pattern(java.util.regex.Pattern) Matcher(java.util.regex.Matcher) Value(eu.esdihumboldt.hale.common.core.io.Value) TransformationVariableScope(eu.esdihumboldt.hale.common.align.transformation.function.TransformationVariableScope)

Aggregations

TransformationVariableScope (eu.esdihumboldt.hale.common.align.transformation.function.TransformationVariableScope)1 Value (eu.esdihumboldt.hale.common.core.io.Value)1 Matcher (java.util.regex.Matcher)1 Pattern (java.util.regex.Pattern)1