public void add(final Closure transformer) { transformers.add(new Transformer<T, T>() { public T transform(T original) { transformer.setDelegate(original); transformer.setResolveStrategy(Closure.DELEGATE_FIRST); Object value = transformer.call(original); if (type.isInstance(value)) { return type.cast(value); } if (type == String.class && value instanceof GString) { return type.cast(value.toString()); } return original; } }); }
private Map<String, Object> wrap(final Map<String, Object> model) { return new HashMap<String, Object>(model) { @Override public Object get(final Object property) { if (property instanceof String || property instanceof GString) { String key = property.toString(); if ("include".equals(key)) { return new MethodClosure(GroovyTemplateEngine.this, "doInclude").curry(this); } try { return extractors.extractAndTransform(db, key, model, new TemplateEngineAdapter.NoopAdapter()); } catch(NoModelExtractorException e) { // fallback to parent model } } return super.get(property); } }; }
private Map<String, Object> wrap(final Map<String, Object> model) { return new HashMap<String, Object>(model) { @Override public Object get(final Object property) { if (property instanceof String || property instanceof GString) { String key = property.toString(); try { put(key, extractors.extractAndTransform(db, key, model, new TemplateEngineAdapter.NoopAdapter())); } catch (NoModelExtractorException e) { // should never happen, as we iterate over existing extractors } } return super.get(property); } }; }
public static <T> GroovyValue<T> asGroovyValue(Class<T> expectedType, Object value) { if (value instanceof Closure) { return new ClosureBasedGroovyValue<>((Closure) value, expectedType); } if (value == null || expectedType.isInstance(value)) { return new SimpleGroovyValue<>((T) value); } if (value instanceof GString && expectedType.equals(String.class)) { return (GroovyValue<T>) new GStringGroovyValue((GString) value); } throw new IllegalArgumentException("I don't know what to do with " + value.getClass().getCanonicalName() + ". Expecting " + expectedType.getCanonicalName() + " or Closure"); }
/** * Converts the parts of the `UriBuilder` to the `URI` object instance. * * @return the generated `URI` representing the parts contained in the builder */ public URI toURI() throws URISyntaxException { final String scheme = traverse(this, UriBuilder::getParent, UriBuilder::getScheme, Traverser::notNull); final Integer port = traverse(this, UriBuilder::getParent, UriBuilder::getPort, notValue(DEFAULT_PORT)); final String host = traverse(this, UriBuilder::getParent, UriBuilder::getHost, Traverser::notNull); final GString path = traverse(this, UriBuilder::getParent, UriBuilder::getPath, Traverser::notNull); final String query = populateQueryString(traverse(this, UriBuilder::getParent, UriBuilder::getQuery, Traverser::nonEmptyMap)); final String fragment = traverse(this, UriBuilder::getParent, UriBuilder::getFragment, Traverser::notNull); final String userInfo = traverse(this, UriBuilder::getParent, UriBuilder::getUserInfo, Traverser::notNull); final Boolean useRaw = traverse(this, UriBuilder::getParent, UriBuilder::getUseRawValues, Traverser::notNull); if (useRaw != null && useRaw) { return toRawURI(scheme, port, host, path, query, fragment, userInfo); } else { return new URI(scheme, userInfo, host, (port == null ? -1 : port), ((path == null) ? null : path.toString()), query, fragment); } }
private void addImport(final ImportCustomizer customizer, final Object value) { if (value==null) return; if (value instanceof Collection) { for (Object e : (Collection)value) { addImport(customizer, e); } } else if (value instanceof String) { customizer.addImports((String)value); } else if (value instanceof Class) { customizer.addImports(((Class) value).getName()); } else if (value instanceof GString) { customizer.addImports(value.toString()); } else { throw new RuntimeException("Unsupported import value type ["+value+"]"); } }
public Object coerceArgument(Object argument) { Class argumentClass = argument.getClass(); if (argumentClass.getName().charAt(0) != '[') return argument; Class argumentComponent = argumentClass.getComponentType(); Class paramComponent = getTheClass().getComponentType(); if (paramComponent.isPrimitive()) { argument = DefaultTypeTransformation.convertToPrimitiveArray(argument, paramComponent); } else if (paramComponent == String.class && argument instanceof GString[]) { GString[] strings = (GString[]) argument; String[] ret = new String[strings.length]; for (int i = 0; i < strings.length; i++) { ret[i] = strings[i].toString(); } argument = ret; } else if (paramComponent==Object.class && argumentComponent.isPrimitive()){ argument = DefaultTypeTransformation.primitiveArrayBox(argument); } return argument; }
public static Class[] wrap(Class[] classes) { Class[] wrappedArguments = new Class[classes.length]; for (int i = 0; i < wrappedArguments.length; i++) { Class c = classes[i]; if (c == null) continue; if (c.isPrimitive()) { if (c == Integer.TYPE) { c = Integer.class; } else if (c == Byte.TYPE) { c = Byte.class; } else if (c == Long.TYPE) { c = Long.class; } else if (c == Double.TYPE) { c = Double.class; } else if (c == Float.TYPE) { c = Float.class; } } else if (isSuperclass(c, GString.class)) { c = String.class; } wrappedArguments[i] = c; } return wrappedArguments; }
private static Object adjustNewValue(Object[] objects, Object newValue) { Class arrayComponentClass = objects.getClass().getComponentType(); Object adjustedNewVal = newValue; if (newValue instanceof Number) { if (!arrayComponentClass.equals(newValue.getClass())) { adjustedNewVal = DefaultTypeTransformation.castToType(newValue, arrayComponentClass); } } else if (Character.class.isAssignableFrom(arrayComponentClass)) { adjustedNewVal = DefaultTypeTransformation.getCharFromSizeOneString(newValue); } else if (Number.class.isAssignableFrom(arrayComponentClass)) { if (newValue instanceof Character || newValue instanceof String || newValue instanceof GString) { Character ch = DefaultTypeTransformation.getCharFromSizeOneString(newValue); adjustedNewVal = DefaultTypeTransformation.castToType(ch, arrayComponentClass); } } else if (arrayComponentClass.isArray()) { adjustedNewVal = DefaultTypeTransformation.castToType(newValue, arrayComponentClass); } return adjustedNewVal; }
/** * Checks if the given attributes Map has the correct types. This handles the GString case since that is a Groovy * special class that is converted to String dynamically. * * @param attributes The attributes map. * @param types The types. * @return True if the map contains the correct types, false otherwise. */ @SuppressWarnings("unchecked") public static boolean hasAttributeTypes(Map<String, Object> attributes, Map<String, Class<?>> types) { if (attributes == null) { return false; } for (String key : types.keySet()) { Object value = attributes.get(key); if (value == null) { continue; } Class type = types.get(key); if (type == String.class && !(value instanceof String || value instanceof GString)) { return false; } else if (type != String.class && !type.isAssignableFrom(value.getClass())) { return false; } } return true; }
@Override public T getValue() { if (value.get() == null) { T newValue = closure.call(); if (newValue instanceof GString && expectedType.equals(String.class)) { newValue = (T) newValue.toString(); } if (newValue != null && !expectedType.isInstance(newValue)) { throw new IllegalArgumentException("Expected value of type " + expectedType.getCanonicalName() + ". Got " + newValue.getClass().getCanonicalName() + " instead."); } value.compareAndSet(null, new ValueContainer(newValue)); } return value.get().value; }
protected List<Object> resolveConstructorArguments(Object[] args, int start, int end) { Object[] constructorArgs = Arrays.copyOfRange(args, start, end); for (int i = 0; i < constructorArgs.length; i++) { if (constructorArgs[i] instanceof GString) { constructorArgs[i] = constructorArgs[i].toString(); } else if (constructorArgs[i] instanceof List) { constructorArgs[i] = manageListIfNecessary((List) constructorArgs[i]); } else if (constructorArgs[i] instanceof Map){ constructorArgs[i] = manageMapIfNecessary((Map) constructorArgs[i]); } } return Arrays.asList(constructorArgs); }
protected void applyPropertyToBeanDefinition(String name, Object value) { if (value instanceof GString) { value = value.toString(); } if (addDeferredProperty(name, value)) { return; } else if (value instanceof Closure) { GroovyBeanDefinitionWrapper current = this.currentBeanDefinition; try { Closure callable = (Closure) value; Class<?> parameterType = callable.getParameterTypes()[0]; if (parameterType.equals(Object.class)) { this.currentBeanDefinition = new GroovyBeanDefinitionWrapper(""); callable.call(this.currentBeanDefinition); } else { this.currentBeanDefinition = new GroovyBeanDefinitionWrapper(null, parameterType); callable.call((Object) null); } value = this.currentBeanDefinition.getBeanDefinition(); } finally { this.currentBeanDefinition = current; } } this.currentBeanDefinition.addProperty(name, value); }
protected void applyPropertyToBeanDefinition(String name, Object value) { if (value instanceof GString) { value = value.toString(); } if (addDeferredProperty(name, value)) { return; } else if (value instanceof Closure) { GroovyBeanDefinitionWrapper current = this.currentBeanDefinition; try { Closure callable = (Closure) value; Class<?> parameterType = callable.getParameterTypes()[0]; if (Object.class == parameterType) { this.currentBeanDefinition = new GroovyBeanDefinitionWrapper(""); callable.call(this.currentBeanDefinition); } else { this.currentBeanDefinition = new GroovyBeanDefinitionWrapper(null, parameterType); callable.call((Object) null); } value = this.currentBeanDefinition.getBeanDefinition(); } finally { this.currentBeanDefinition = current; } } this.currentBeanDefinition.addProperty(name, value); }
private URI toRawURI(final String scheme, final Integer port, final String host, final GString path, final String query, final String fragment, final String userInfo) throws URISyntaxException { return new URI(format("%s%s%s%s%s%s%s", scheme == null ? "" : (scheme.endsWith("://") ? scheme : scheme + "://"), userInfo == null ? "" : (userInfo.endsWith("@") ? userInfo : userInfo + "@"), host == null ? "" : host, port == null ? "" : ":" + port.toString(), path == null ? "" : (!path.toString().startsWith("/") && !path.toString().isEmpty() ? "/" + path : path), query != null ? "?" + query : "", fragment == null ? "" : (!fragment.startsWith("#") ? "#" + fragment : fragment) )); }
/** * Writes the given Writable as the value of the given attribute name * * @param name The attribute name * @param json The writable value * @throws IOException */ public void call(String name, Writable json) throws IOException { writeName(name); verifyValue(); if(json instanceof GString) { writer.write(generator.toJson(json.toString())); } else { json.writeTo(writer); } }
/** * 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); } } } }
/** * this class requires that the supplied enum is not fitting a * Collection case for casting */ public static Enum castToEnum(Object object, Class<? extends Enum> type) { if (object==null) return null; if (type.isInstance(object)) return (Enum) object; if (object instanceof String || object instanceof GString) { return Enum.valueOf(type, object.toString()); } throw new GroovyCastException(object, type); }
public static Collection asCollection(Object value) { if (value == null) { return Collections.EMPTY_LIST; } else if (value instanceof Collection) { return (Collection) value; } else if (value instanceof Map) { Map map = (Map) value; return map.entrySet(); } else if (value.getClass().isArray()) { return arrayAsCollection(value); } else if (value instanceof MethodClosure) { MethodClosure method = (MethodClosure) value; IteratorClosureAdapter adapter = new IteratorClosureAdapter(method.getDelegate()); method.call(adapter); return adapter.asList(); } else if (value instanceof String || value instanceof GString) { return StringGroovyMethods.toList((CharSequence) value); } else if (value instanceof File) { try { return ResourceGroovyMethods.readLines((File) value); } catch (IOException e) { throw new GroovyRuntimeException("Error reading file: " + value, e); } } else if (value instanceof Class && ((Class) value).isEnum()) { Object[] values = (Object[]) InvokerHelper.invokeMethod(value, "values", EMPTY_OBJECT_ARRAY); return Arrays.asList(values); } else { // let's assume it's a collection of 1 return Collections.singletonList(value); } }
@Deprecated public static Character getCharFromSizeOneString(Object value) { if (value instanceof GString) value = value.toString(); if (value instanceof String) { String s = (String) value; if (s.length() != 1) throw new IllegalArgumentException("String of length 1 expected but got a bigger one"); return Character.valueOf(s.charAt(0)); } else { return ((Character) value); } }
public Object invoke(Object object, Object[] args) { final long[] objects = (long[]) object; final int index = normaliseIndex((Integer) args[0], objects.length); Object newValue = args[1]; if (!(newValue instanceof Long)) { if (newValue instanceof Character || newValue instanceof String || newValue instanceof GString) { Character ch = DefaultTypeTransformation.getCharFromSizeOneString(newValue); objects[index] = (Long) DefaultTypeTransformation.castToType(ch, Long.class); } else { objects[index] = ((Number) newValue).longValue(); } } else objects[index] = (Long) args[1]; return null; }
public Object invoke(Object object, Object[] args) { final int[] objects = (int[]) object; final int index = normaliseIndex((Integer) args[0], objects.length); Object newValue = args[1]; if (!(newValue instanceof Integer)) { if (newValue instanceof Character || newValue instanceof String || newValue instanceof GString) { Character ch = DefaultTypeTransformation.getCharFromSizeOneString(newValue); objects[index] = (Integer) DefaultTypeTransformation.castToType(ch, Integer.class); } else { objects[index] = ((Number) newValue).intValue(); } } else objects[index] = (Integer) args[1]; return null; }
public Object invoke(Object object, Object[] args) { final short[] objects = (short[]) object; final int index = normaliseIndex((Integer) args[0], objects.length); Object newValue = args[1]; if (!(newValue instanceof Short)) { if (newValue instanceof Character || newValue instanceof String || newValue instanceof GString) { Character ch = DefaultTypeTransformation.getCharFromSizeOneString(newValue); objects[index] = (Short) DefaultTypeTransformation.castToType(ch, Short.class); } else { objects[index] = ((Number) newValue).shortValue(); } } else objects[index] = (Short) args[1]; return null; }
public Object invoke(Object object, Object[] args) { final float[] objects = (float[]) object; final int index = normaliseIndex((Integer) args[0], objects.length); Object newValue = args[1]; if (!(newValue instanceof Float)) { if (newValue instanceof Character || newValue instanceof String || newValue instanceof GString) { Character ch = DefaultTypeTransformation.getCharFromSizeOneString(newValue); objects[index] = (Float) DefaultTypeTransformation.castToType(ch, Float.class); } else { objects[index] = ((Number) newValue).floatValue(); } } else objects[index] = (Float) args[1]; return null; }
public Object invoke(Object object, Object[] args) { final double[] objects = (double[]) object; final int index = normaliseIndex((Integer) args[0], objects.length); Object newValue = args[1]; if (!(newValue instanceof Double)) { if (newValue instanceof Character || newValue instanceof String || newValue instanceof GString) { Character ch = DefaultTypeTransformation.getCharFromSizeOneString(newValue); objects[index] = (Double) DefaultTypeTransformation.castToType(ch, Double.class); } else { objects[index] = ((Number) newValue).doubleValue(); } } else objects[index] = (Double) args[1]; return null; }
/** * Converts the GString to a File, or delegates to the default * {@link org.codehaus.groovy.runtime.DefaultGroovyMethods#asType(Object, Class)} * * @param self a GString * @param c the desired class * @return the converted object * @since 1.5.0 */ @SuppressWarnings("unchecked") public static <T> T asType(GString self, Class<T> c) { if (c == File.class) { return (T) new File(self.toString()); } else if (Number.class.isAssignableFrom(c) || c.isPrimitive()) { return asType(self.toString(), c); } return DefaultGroovyMethods.asType((Object) self, c); }
/** * Adds a type transformer applied at runtime. * This method handles transformations to String from GString, * array transformations and number based transformations */ protected static MethodHandle addTransformer(MethodHandle handle, int pos, Object arg, Class parameter) { MethodHandle transformer=null; if (arg instanceof GString) { transformer = TO_STRING; } else if (arg instanceof Closure) { transformer = createSAMTransform(arg, parameter); } else if (Number.class.isAssignableFrom(parameter)) { transformer = selectNumberTransformer(parameter, arg); } else if (parameter.isArray()) { transformer = MethodHandles.insertArguments(AS_ARRAY, 1, parameter); } if (transformer==null) throw new GroovyBugError("Unknown transformation for argument "+arg+" at position "+pos+" with "+arg.getClass()+" for parameter of type "+parameter); return applyUnsharpFilter(handle, pos, transformer); }
public Object newInstance(FactoryBuilderSupport builder, Object name, Object value, Map properties) throws InstantiationException, IllegalAccessException { if(value == null) return super.newInstance(builder, name, value, properties); Object bean = null; Class klass = null; Map context = builder.getContext(); if(value instanceof String || value instanceof GString) { /* String classname = value.toString(); klass = resolveClass(builder, classname, name, value, properties); bean = resolveInstance(builder, name, value, klass, properties); */ throw new IllegalArgumentException("ObjectGraphBuilder."+((ObjectGraphBuilder)builder).getBeanFactoryName()+"() does not accept String nor GString as value."); } else if(value instanceof Class) { klass = (Class) value; bean = resolveInstance(builder, name, value, klass, properties); } else { klass = value.getClass(); bean = value; } String nodename = klass.getSimpleName(); if(nodename.length() > 1) { nodename = nodename.substring(0, 1).toLowerCase() + nodename.substring(1); } else { nodename = nodename.toLowerCase(); } context.put(ObjectGraphBuilder.NODE_NAME, nodename); context.put(ObjectGraphBuilder.NODE_CLASS, klass); return bean; }
public void testConstructorWithGStringCoercion() throws Throwable { GString gstring = new GString(new Object[]{new Integer(123)}) { public String[] getStrings() { return new String[]{""}; } }; Object expected = new Long(gstring.toString()); assertConstructor(expected, new Object[]{gstring}); }
public void testCoerceGStringToString() throws Throwable { GString param = new GString(new Object[]{"James"}) { public String[] getStrings() { return new String[]{"Hello "}; } }; Object value = invoke(this, "methodTakesString", new Object[]{param}); assertEquals("converted GString to string", param.toString(), value); }
public void testCoerceGStringToStringOnGetBytes() throws Throwable { GString param = new GString(new Object[]{CompilerConfiguration.DEFAULT_SOURCE_ENCODING}) { public String[] getStrings() { return new String[]{""}; } }; Object value = invoke("test", "getBytes", new Object[]{param}); assertEquals("converted GString to string", "test".getBytes(CompilerConfiguration.DEFAULT_SOURCE_ENCODING).getClass(), value.getClass()); }
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)})); }
/** * Checks for an execute call on List, String, String[] and GString. * * @param receiver the receiver object * @param method the method name */ private void checkExecute(Object receiver, String method) { if ("execute".equals(method)) { if (receiver instanceof List || receiver instanceof String || receiver.getClass().isArray() || receiver instanceof String[] || receiver instanceof GString) { throw new GroovyRestrictionException( "Possible access of method execute on List, String, String[] and GString is not allowed in Groovy transformations!"); } } }