groovy.lang.GString Java Examples

The following examples show how to use groovy.lang.GString. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: BodyParser.java    From spring-cloud-contract with Apache License 2.0 6 votes vote down vote up
/**
 * Converts the passed body into ints server side representation. All
 * {@link DslProperty} will return their server side values
 */
default Object extractServerValueFromBody(ContentType contentType, Object bodyValue) {
	if (bodyValue instanceof GString) {
		return extractValue((GString) bodyValue, contentType,
				ContentUtils.GET_TEST_SIDE);
	}
	else if (bodyValue instanceof FromFileProperty) {
		return MapConverter.transformValues(bodyValue, ContentUtils.GET_TEST_SIDE);
	}
	else if (TEXT != contentType && FORM != contentType && DEFINED != contentType) {
		boolean dontParseStrings = contentType == JSON && bodyValue instanceof Map;
		Closure parsingClosure = dontParseStrings ? Closure.IDENTITY
				: MapConverter.JSON_PARSING_CLOSURE;
		return MapConverter.getTestSideValues(bodyValue, parsingClosure);
	}
	return bodyValue;
}
 
Example #2
Source File: InlineParser.java    From sharding-jdbc-1.5.1 with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
private Set<List<String>> getCartesianValues(final GString segment) {
    List<Set<String>> result = new ArrayList<>(segment.getValues().length);
    for (Object each : segment.getValues()) {
        if (null == each) {
            continue;
        }
        if (each instanceof Collection) {
            result.add(Sets.newHashSet(Collections2.transform((Collection<Object>) each, new Function<Object, String>() {
                
                @Override
                public String apply(final Object input) {
                    return input.toString();
                }
            })));
        } else {
            result.add(Sets.newHashSet(each.toString()));
        }
    }
    return Sets.cartesianProduct(result);
}
 
Example #3
Source File: ChainingTransformer.java    From pushfish-android with BSD 2-Clause "Simplified" License 6 votes vote down vote up
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;
        }
    });
}
 
Example #4
Source File: ChainingTransformer.java    From pushfish-android with BSD 2-Clause "Simplified" License 6 votes vote down vote up
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;
        }
    });
}
 
Example #5
Source File: MetaClassHelper.java    From groovy with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #6
Source File: GroovyDslPropertyConverter.java    From spring-cloud-contract with Apache License 2.0 6 votes vote down vote up
@Override
public Object testSide(Object object) {
	if (object instanceof GString) {
		boolean anyPattern = Arrays.stream(((GString) object).getValues())
				.anyMatch(it -> it instanceof RegexProperty);
		if (!anyPattern) {
			return object;
		}
		List<Object> generatedValues = Arrays.stream(((GString) object).getValues())
				.map(it -> it instanceof RegexProperty
						? ((RegexProperty) it).generate() : it)
				.collect(Collectors.toList());
		Object[] arrayOfObjects = generatedValues.toArray();
		String[] strings = Arrays.copyOf(((GString) object).getStrings(),
				((GString) object).getStrings().length, String[].class);
		String newUrl = new GStringImpl(arrayOfObjects, strings).toString();
		return new Url(newUrl);
	}
	return object;
}
 
Example #7
Source File: UriBuilder.java    From http-builder-ng with Apache License 2.0 6 votes vote down vote up
/**
 * 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);
    }
}
 
Example #8
Source File: ImportCustomizerFactory.java    From groovy with Apache License 2.0 6 votes vote down vote up
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+"]");
    }
}
 
Example #9
Source File: ArrayCachedClass.java    From groovy with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #10
Source File: GroovyMarkupTemplateEngine.java    From jbake with MIT License 6 votes vote down vote up
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);
        }
    };
}
 
Example #11
Source File: ObjectArrayPutAtMetaMethod.java    From groovy with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #12
Source File: GroovyTemplateEngine.java    From jbake with MIT License 6 votes vote down vote up
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);
        }
    };
}
 
Example #13
Source File: TypeTransformers.java    From groovy with Apache License 2.0 6 votes vote down vote up
/**
 * 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);
}
 
Example #14
Source File: ChainingTransformer.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 6 votes vote down vote up
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;
        }
    });
}
 
Example #15
Source File: ChainingTransformer.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 6 votes vote down vote up
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;
        }
    });
}
 
Example #16
Source File: InvokeMethodTest.java    From groovy with Apache License 2.0 5 votes vote down vote up
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);
}
 
Example #17
Source File: InvokerTest.java    From groovy with Apache License 2.0 5 votes vote down vote up
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, Integer.valueOf(1234));
    assertAsBoolean(false, Integer.valueOf(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[]{Integer.valueOf(1)}));
}
 
Example #18
Source File: InvokeMethodTest.java    From groovy with Apache License 2.0 5 votes vote down vote up
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());
}
 
Example #19
Source File: InlineParser.java    From sharding-jdbc-1.5.1 with Apache License 2.0 5 votes vote down vote up
private String assemblySegment(final List<String> cartesianValue, final GString segment) {
    StringBuilder result = new StringBuilder();
    for (int i = 0; i < segment.getStrings().length; i++) {
        result.append(segment.getStrings()[i]);
        if (i < cartesianValue.size()) {
            result.append(cartesianValue.get(i));
        }
    }
    return result.toString();
}
 
Example #20
Source File: FloatArrayPutAtMetaMethod.java    From groovy with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example #21
Source File: ShortArrayPutAtMetaMethod.java    From groovy with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example #22
Source File: IntegerArrayPutAtMetaMethod.java    From groovy with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example #23
Source File: LongArrayPutAtMetaMethod.java    From groovy with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example #24
Source File: GroovyBeanDefinitionReader.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
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);
}
 
Example #25
Source File: DefaultTypeTransformation.java    From groovy with Apache License 2.0 5 votes vote down vote up
@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 s.charAt(0);
    } else {
        return ((Character) value);
    }
}
 
Example #26
Source File: DefaultTypeTransformation.java    From groovy with Apache License 2.0 5 votes vote down vote up
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);
    }
}
 
Example #27
Source File: GroovyBeanDefinitionReader.java    From java-technology-stack with MIT License 5 votes vote down vote up
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);
}
 
Example #28
Source File: InlineParser.java    From sharding-jdbc-1.5.1 with Apache License 2.0 5 votes vote down vote up
private List<String> flattenSegments(final List<Object> segments) {
    List<String> result = new ArrayList<>();
    for (Object each : segments) {
        if (each instanceof GString) {
            result.addAll(assemblyCartesianSegments((GString) each));
        } else {
            result.add(each.toString());
        }
    }
    return result;
}
 
Example #29
Source File: GroovyBeanDefinitionReader.java    From java-technology-stack with MIT License 5 votes vote down vote up
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);
}
 
Example #30
Source File: GroovyJavaMethods.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public static <T> T fix(Object o) {
    try {
        if (safeGroovyIsCase(o, GString.class)) {
            return (T)ScriptBytecodeAdapter.asType(o, String.class);
        } else {
            return (T)o;
        }
    } catch (Throwable e) {
        throw Exceptions.propagate(e);
    }
}