Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

first pr of Groovy-Optional #420

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions settings.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,10 @@ def subprojects = ['groovy-ant',
if(JavaVersion.current().isJava7Compatible()) {
subprojects << 'groovy-nio'
}

if(JavaVersion.current().isJava8Compatible()) {
subprojects << 'groovy-optional'
}

include(subprojects as String[])

Expand Down
22 changes: 22 additions & 0 deletions subprojects/groovy-optional/build.gradle
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
dependencies {
compile rootProject
testCompile project(':groovy-test')
testCompile ('org.spockframework:spock-core:0.7-groovy-2.0') {
exclude module: 'groovy-all'
}
}

task moduleDescriptor(type: org.codehaus.groovy.gradle.WriteExtensionDescriptorTask) {
extensionClasses = 'org.codehaus.groovy.runtime.OptionalGroovyMethods'
}

compileJava.dependsOn moduleDescriptor

tasks.withType(Compile) {
sourceCompatibility = 1.7
targetCompatibility = 1.7
}
tasks.withType(Javadoc) {
options.source = "1.7"
}

Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
/*
* Copyright 2003-2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.codehaus.groovy.runtime;
import groovy.transform.CompileStatic;
import org.codehaus.groovy.runtime.InvokerHelper;
import java.util.Optional;
import java.lang.reflect.Method;
import java.lang.reflect.InvocationTargetException;
import org.codehaus.groovy.runtime.InvokerHelper;

/**
* @author Uehara Junji(@uehaj)
*/
public class OptionalGroovyMethods {

public static Object methodMissing(Optional self, String name, Object args0) {
Object[] args = (Object[])args0;
for (int i=0; i<args.length; i++) {
if (args[i] instanceof Optional) {
if (((Optional)args[i]).isPresent()) {
args[i] = ((Optional)args[i]).get();
}
else {
return Optional.empty();
}
}
}
if (self.isPresent()) {
Object result = InvokerHelper.invokeMethod(self.get(), name, args);
return Optional.ofNullable(result);
}
else {
return Optional.empty();
}
}

}

Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
/*
* Copyright 2003-2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package org.codehaus.groovy.runtime;

import static java.nio.file.StandardOpenOption.APPEND;
import static java.nio.file.StandardOpenOption.CREATE;
import static org.codehaus.groovy.runtime.DefaultGroovyMethods.get;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Reader;
import java.io.Writer;
import java.io.Closeable;
import java.net.URI;
import java.nio.charset.Charset;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

import groovy.io.FileType;
import groovy.io.FileVisitResult;
import groovy.io.GroovyPrintWriter;
import groovy.lang.Closure;
import groovy.lang.MetaClass;
import groovy.lang.Writable;
import groovy.transform.stc.ClosureParams;
import groovy.transform.stc.FromString;
import groovy.transform.stc.SimpleType;
import org.codehaus.groovy.runtime.callsite.BooleanReturningMethodInvoker;
import org.codehaus.groovy.runtime.typehandling.DefaultTypeTransformation;

/**
* This class defines new groovy methods for Readers, Writers, InputStreams and
* OutputStreams which appear on normal JDK classes inside the Groovy environment.
* Static methods are used with the first parameter being the destination class,
* i.e. <code>public static T eachLine(InputStream self, Closure c)</code>
* provides a <code>eachLine(Closure c)</code> method for <code>InputStream</code>.
* <p/>
* NOTE: While this class contains many 'public' static methods, it is
* primarily regarded as an internal class (its internal package name
* suggests this also). We value backwards compatibility of these
* methods when used within Groovy but value less backwards compatibility
* at the Java method call level. I.e. future versions of Groovy may
* remove or move a method call in this file but would normally
* aim to keep the method available from within Groovy.
*
* @author <a href="mailto:[email protected]">James Strachan</a>
* @author Jeremy Rayner
* @author Sam Pullara
* @author Rod Cope
* @author Guillaume Laforge
* @author John Wilson
* @author Hein Meling
* @author Dierk Koenig
* @author Pilho Kim
* @author Marc Guillemot
* @author Russel Winder
* @author bing ran
* @author Jochen Theodorou
* @author Paul King
* @author Michael Baehr
* @author Joachim Baumann
* @author Alex Tkachman
* @author Ted Naleid
* @author Brad Long
* @author Jim Jagielski
* @author Rodolfo Velasco
* @author jeremi Joslin
* @author Hamlet D'Arcy
* @author Cedric Champeau
* @author Tim Yates
* @author Dinko Srkoc
* @author Paolo Di Tommaso <[email protected]>
*/

public class OptionalGroovyMethods extends DefaultGroovyMethodsSupport {
public static void hello(String self) {
System.out.println("hello"+self);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
package org.codehaus.groovy.runtime;

import java.util.Optional;
import groovy.io.FileType
import spock.lang.Specification

class OptionalGroovyMethodsTest extends Specification {

Optional<String> s1 = Optional.<String>of("Abc")
Optional<String> s2 = Optional.<String>of("Def")
Optional<Integer> i1 = Optional.<Integer>of(3)
Optional<Integer> i2 = Optional.<Integer>of(4)
Optional<Integer> e = Optional.empty()

void testStringPlus1() {
expect:
s1+s2 == Optional.of("AbcDef")
s1+e == Optional.empty()
e+s2 == Optional.empty()
e+e == Optional.empty()
}

void testIntegerPlus1() {
expect:
i1+i2 == Optional.of(7)
i1+e == Optional.empty()
e+i2 == Optional.empty()
e+e == Optional.empty()
}

def toUpperAndToLower1(a,b) {
a.toUpperCase()+b.toLowerCase()
}

void testToUpperAndToLower() {
expect:
toUpperAndToLower1(s1, s2) == Optional.of("ABCdef")
toUpperAndToLower1(s1, e) == e
toUpperAndToLower1(e, s2) == e
toUpperAndToLower1(e, e) == e
}

def mult1(a, b) {
a * 3 + b * 2
}

void testMult1() {
expect:
mult1(s1, s2) == Optional.of("AbcAbcAbcDefDef")
mult1(e, s2) == e
mult1(s1, e) == e
mult1(s1, e) == e
mult1(s1, Optional.of(3)) == Optional.of("AbcAbcAbc6")
}

// @groovy.transform.TypeChecked
Optional<Integer> mult2(Optional<Integer>a, Optional<Integer>b) {
a * 3 + b * 2
}

@groovy.transform.TypeChecked
void testMult2() {
expect:
mult2(i1, i2) == Optional.of(9+8)
mult2(e, i2) == e
mult2(i1, e) == e
mult2(e, e) == e
}

// Optional.methodMissing() never worked with static method.
// Because static method is not the method of Optional. To apply
// static method to Optional-embedded-value, you can embed a
// closure into Opional and call the Opitonal like
// closure. Optional.call is defined to delagate to Closure.call()
// on the embedded Closure, so you can apply static method to
// Optional embedded value transparently.
void testStatic() {
expect:
Optional.of({fmt,...args->String.format(fmt,*args)})("%02d", i1) == Optional.of("03")
Optional.of(String.&format)("%02d", i1) == Optional.of("03")
Optional.of(String.&format)(Optional.of("%02d"), i1) == Optional.of("03")
}

// Optional.toString() is not delegated to the toString() on the
// embeded value. Because of compatibility to Java's originaln
// Original behavior.
void testToString() {
def a = Optional.of(3.3)
expect:
a.toString() == "Optional[3.3]" // != "3.3"
a.get().toString() == "3.3"
a.map{"<"+it.toString()+">"}.get() == "<3.3>"
}

// Optional.toString() is not delegated to the toString() on the
// embeded value. Because of compatibility to Java's originaln
// Original behavior.
void testToString() {
def a = Optional.of(3.3)
expect:
a.toString() == "Optional[3.3]" // != "3.3"
a.get().toString() == "3.3"
a.map{"<"+it.toString()+">"}.get() == "<3.3>"
}

void testMap() {
expect:
Optional.of("abc").map{it.toUpperCase()} == Optional.of("ABC")
}

void testFlatMap() {
def divide = {it == 0 ? Optional.empty() : Optional.of(3.0/it) }
expect:
Optional.of(3.0).flatMap(divide) != Optional.of(1.0) // equals i not dispatched to target.
Optional.of(3.0).flatMap(divide).get() == Optional.of(1.0).get()
Optional.of(0).flatMap(divide) == Optional.empty()
}

void testFilter() {
expect:
Optional.of(3).filter { it % 2 == 0 } == Optional.empty()
Optional.of(3).filter { it % 2 == 1 } == Optional.of(3)
}

}