Search in sources :

Example 56 with GString

use of groovy.lang.GString in project groovy-core by groovy.

the class GPathResult method setProperty.

/**
 * Replaces the specified property of this GPathResult with a new value.
 *
 * @param property the property of this GPathResult to replace
 * @param newValue the new value of the property
 */
public void setProperty(final String property, final Object newValue) {
    if (property.startsWith("@")) {
        if (newValue instanceof String || newValue instanceof GString) {
            final Iterator iter = iterator();
            while (iter.hasNext()) {
                final NodeChild child = (NodeChild) iter.next();
                child.attributes().put(property.substring(1), newValue);
            }
        }
    } else {
        final GPathResult result = new NodeChildren(this, property, this.namespaceTagHints);
        if (newValue instanceof Map) {
            for (Object o : ((Map) newValue).entrySet()) {
                final Map.Entry entry = (Map.Entry) o;
                result.setProperty("@" + entry.getKey(), entry.getValue());
            }
        } else {
            if (newValue instanceof Closure) {
                result.replaceNode((Closure) newValue);
            } else {
                result.replaceBody(newValue);
            }
        }
    }
}
Also used : Closure(groovy.lang.Closure) Iterator(java.util.Iterator) GroovyObject(groovy.lang.GroovyObject) GString(groovy.lang.GString) GString(groovy.lang.GString) HashMap(java.util.HashMap) Map(java.util.Map)

Example 57 with GString

use of groovy.lang.GString in project groovy-core by groovy.

the class InvokerTest method testAsBoolean.

public void testAsBoolean() {
    assertAsBoolean(true, Boolean.TRUE);
    assertAsBoolean(true, "true");
    assertAsBoolean(true, "TRUE");
    assertAsBoolean(true, "false");
    assertAsBoolean(false, Boolean.FALSE);
    assertAsBoolean(false, (String) null);
    assertAsBoolean(false, "");
    GString emptyGString = new GString(new Object[] { "" }) {

        public String[] getStrings() {
            return new String[] { "" };
        }
    };
    assertAsBoolean(false, emptyGString);
    GString nonEmptyGString = new GString(new Object[] { "x" }) {

        public String[] getStrings() {
            return new String[] { "x" };
        }
    };
    assertAsBoolean(true, nonEmptyGString);
    assertAsBoolean(true, new Integer(1234));
    assertAsBoolean(false, new Integer(0));
    assertAsBoolean(true, new Float(0.3f));
    assertAsBoolean(true, new Double(3.0f));
    assertAsBoolean(false, new Float(0.0f));
    assertAsBoolean(true, new Character((char) 1));
    assertAsBoolean(false, new Character((char) 0));
    assertAsBoolean(false, Collections.EMPTY_LIST);
    assertAsBoolean(true, Arrays.asList(new Integer[] { new Integer(1) }));
}
Also used : GString(groovy.lang.GString) GString(groovy.lang.GString)

Example 58 with GString

use of groovy.lang.GString in project ontrack by nemerosa.

the class ExpressionEngineImpl method resolve.

public String resolve(final String expression, Map<String, ?> parameters) {
    SandboxTransformer sandboxTransformer = new SandboxTransformer();
    SecureASTCustomizer secure = new SecureASTCustomizer();
    secure.setClosuresAllowed(false);
    secure.setMethodDefinitionAllowed(false);
    CompilerConfiguration compilerConfiguration = new CompilerConfiguration();
    compilerConfiguration.addCompilationCustomizers(sandboxTransformer, secure);
    Binding binding = new Binding(parameters);
    GroovyShell shell = new GroovyShell(binding, compilerConfiguration);
    // Sandbox registration (thread level)
    GroovyValueFilter sandboxFilter = new GroovyValueFilter() {

        @Override
        public Object filter(Object o) {
            if (o == null || o instanceof String || o instanceof GString || o.getClass().getName().equals("Script1")) {
                return o;
            } else if (o instanceof Class) {
                throw new ExpressionCompilationException(expression, String.format("%n- %s class cannot be accessed.", ((Class) o).getName()));
            } else {
                throw new ExpressionCompilationException(expression, String.format("%n- %s class cannot be accessed.", o.getClass().getName()));
            }
        }
    };
    try {
        sandboxFilter.register();
        Object result = shell.evaluate(expression);
        if (result == null) {
            return null;
        } else if (!(result instanceof String)) {
            throw new ExpressionNotStringException(expression);
        } else {
            return (String) result;
        }
    } catch (MissingPropertyException e) {
        throw new ExpressionCompilationException(expression, "No such property: " + e.getProperty());
    } catch (MultipleCompilationErrorsException e) {
        StringWriter s = new StringWriter();
        PrintWriter p = new PrintWriter(s);
        @SuppressWarnings("unchecked") List<Message> errors = e.getErrorCollector().getErrors();
        errors.forEach((Message message) -> writeErrorMessage(p, message));
        throw new ExpressionCompilationException(expression, s.toString());
    } finally {
        sandboxFilter.unregister();
    }
}
Also used : Binding(groovy.lang.Binding) ExpressionNotStringException(net.nemerosa.ontrack.model.exceptions.ExpressionNotStringException) SecureASTCustomizer(org.codehaus.groovy.control.customizers.SecureASTCustomizer) Message(org.codehaus.groovy.control.messages.Message) ExceptionMessage(org.codehaus.groovy.control.messages.ExceptionMessage) MissingPropertyException(groovy.lang.MissingPropertyException) GString(groovy.lang.GString) GString(groovy.lang.GString) ExpressionCompilationException(net.nemerosa.ontrack.model.exceptions.ExpressionCompilationException) GroovyShell(groovy.lang.GroovyShell) SandboxTransformer(org.kohsuke.groovy.sandbox.SandboxTransformer) StringWriter(java.io.StringWriter) GroovyValueFilter(org.kohsuke.groovy.sandbox.GroovyValueFilter) CompilerConfiguration(org.codehaus.groovy.control.CompilerConfiguration) List(java.util.List) MultipleCompilationErrorsException(org.codehaus.groovy.control.MultipleCompilationErrorsException) PrintWriter(java.io.PrintWriter)

Example 59 with GString

use of groovy.lang.GString in project midpoint by Evolveum.

the class GroovyScriptEvaluator method evaluateScript.

@Override
protected Object evaluateScript(Class<?> compiledScriptClass, ScriptExpressionEvaluationContext context) throws Exception {
    if (!Script.class.isAssignableFrom(compiledScriptClass)) {
        throw new ExpressionEvaluationException("Expected groovy script class, but got " + compiledScriptClass);
    }
    Binding binding = new Binding(prepareScriptVariablesValueMap(context));
    Script scriptResultObject = InvokerHelper.createScript(compiledScriptClass, binding);
    try {
        Object resultObject = scriptResultObject.run();
        if (resultObject == null) {
            return null;
        }
        if (resultObject instanceof GString) {
            resultObject = ((GString) resultObject).toString();
        }
        return resultObject;
    } catch (GroovyRuntimeException e) {
        // Seems also other groovy runtime exceptions are not serializable.
        throw new ExpressionEvaluationException("Groovy Evaluation Failed: " + e.getMessage(), serializationSafeThrowable(e));
    }
}
Also used : Binding(groovy.lang.Binding) Script(groovy.lang.Script) ExpressionEvaluationException(com.evolveum.midpoint.util.exception.ExpressionEvaluationException) GroovyRuntimeException(groovy.lang.GroovyRuntimeException) GString(groovy.lang.GString)

Example 60 with GString

use of groovy.lang.GString in project workflow-cps-plugin by jenkinsci.

the class DSL method flattenGString.

/**
 * Coerce {@link GString}, to save {@link StepDescriptor#newInstance(Map)} from being made aware of that.
 * This is not the only type coercion that Groovy does, so this is not very kosher, but
 * doing a proper coercion like Groovy does require us to know the type that the receiver
 * expects.
 * For reference, Groovy does {@linkplain ReflectionCache#getCachedClass ReflectionCache.getCachedClass(types[i]).}{@linkplain CachedClass#coerceArgument coerceArgument(a)}.
 * Note that {@link DescribableModel#instantiate} would also handle {@link GString} in {@code coerce},
 * but better to do it here in the Groovy-specific code so we do not need to rely on that.
 * Record all instances of interpolated Groovy strings. We can check this collection later to see if sensitive variables were used.
 * @return {@code v} or an equivalent with all {@link GString}s flattened, including in nested {@link List}s or {@link Map}s
 */
private static Object flattenGString(Object v, @NonNull Set<String> interpolatedStrings) {
    if (v instanceof GString) {
        String flattened = v.toString();
        interpolatedStrings.add(flattened);
        return flattened;
    } else if (v instanceof List) {
        boolean mutated = false;
        List<Object> r = new ArrayList<>();
        for (Object o : ((List<?>) v)) {
            Object o2 = flattenGString(o, interpolatedStrings);
            mutated |= o != o2;
            r.add(o2);
        }
        return mutated ? r : v;
    } else if (v instanceof Map) {
        boolean mutated = false;
        Map<Object, Object> r = new LinkedHashMap<>(preallocatedHashmapCapacity(((Map) v).size()));
        for (Map.Entry<?, ?> e : ((Map<?, ?>) v).entrySet()) {
            Object k = e.getKey();
            Object k2 = flattenGString(k, interpolatedStrings);
            Object o = e.getValue();
            Object o2 = flattenGString(o, interpolatedStrings);
            mutated |= k != k2 || o != o2;
            r.put(k2, o2);
        }
        return mutated ? r : v;
    } else {
        return v;
    }
}
Also used : List(java.util.List) ArrayList(java.util.ArrayList) ExtensionList(hudson.ExtensionList) GroovyObject(groovy.lang.GroovyObject) GString(groovy.lang.GString) GString(groovy.lang.GString) Map(java.util.Map) LinkedHashMap(java.util.LinkedHashMap) TreeMap(java.util.TreeMap) LinkedHashMap(java.util.LinkedHashMap)

Aggregations

GString (groovy.lang.GString)60 FromString (groovy.transform.stc.FromString)16 GroovyObject (groovy.lang.GroovyObject)6 Map (java.util.Map)6 Closure (groovy.lang.Closure)5 CachedClass (org.codehaus.groovy.reflection.CachedClass)5 GroovyRuntimeException (groovy.lang.GroovyRuntimeException)3 IOException (java.io.IOException)3 HashMap (java.util.HashMap)3 List (java.util.List)3 Binding (groovy.lang.Binding)2 ArrayList (java.util.ArrayList)2 Iterator (java.util.Iterator)2 LinkedHashMap (java.util.LinkedHashMap)2 TreeMap (java.util.TreeMap)2 MethodClosure (org.codehaus.groovy.runtime.MethodClosure)2 ExpressionEvaluationException (com.evolveum.midpoint.util.exception.ExpressionEvaluationException)1 JsonBuilder (groovy.json.JsonBuilder)1 GroovyShell (groovy.lang.GroovyShell)1 MissingPropertyException (groovy.lang.MissingPropertyException)1