use of groovy.lang.GString in project groovy by apache.
the class DefaultTypeTransformation method asCollection.
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);
}
}
use of groovy.lang.GString in project groovy by apache.
the class StringGroovyMethods method denormalize.
/**
* Return a CharSequence with lines (separated by LF, CR/LF, or CR)
* terminated by the platform specific line separator.
*
* @param self a CharSequence object
* @return the denormalized toString() of this CharSequence
* @see #denormalize(String)
* @since 1.8.2
*/
public static String denormalize(final CharSequence self) {
// TODO: Put this lineSeparator property somewhere everyone can use it.
if (lineSeparator == null) {
final StringWriter sw = new StringWriter(2);
try {
// We use BufferedWriter rather than System.getProperty because
// it has the security manager rigamarole to deal with the possible exception.
final BufferedWriter bw = new BufferedWriter(sw);
bw.newLine();
bw.flush();
lineSeparator = sw.toString();
} catch (IOException ioe) {
// This shouldn't happen, but this is the same default used by
// BufferedWriter on a security exception.
lineSeparator = "\n";
}
}
final int len = self.length();
if (len < 1) {
return self.toString();
}
final StringBuilder sb = new StringBuilder((110 * len) / 100);
int i = 0;
// GROOVY-7873: GString calls toString() on each invocation of CharSequence methods such
// as charAt which is very expensive for large GStrings.
CharSequence cs = (self instanceof GString) ? self.toString() : self;
while (i < len) {
final char ch = cs.charAt(i++);
switch(ch) {
case '\r':
sb.append(lineSeparator);
// Eat the following LF if any.
if ((i < len) && (cs.charAt(i) == '\n')) {
++i;
}
break;
case '\n':
sb.append(lineSeparator);
break;
default:
sb.append(ch);
break;
}
}
return sb.toString();
}
Aggregations