Return-Path: X-Original-To: archive-asf-public-internal@cust-asf2.ponee.io Delivered-To: archive-asf-public-internal@cust-asf2.ponee.io Received: from cust-asf.ponee.io (cust-asf.ponee.io [163.172.22.183]) by cust-asf2.ponee.io (Postfix) with ESMTP id 67B33200B98 for ; Sun, 18 Sep 2016 19:16:37 +0200 (CEST) Received: by cust-asf.ponee.io (Postfix) id 64ED6160AC3; Sun, 18 Sep 2016 17:16:37 +0000 (UTC) Delivered-To: archive-asf-public@cust-asf.ponee.io Received: from mail.apache.org (hermes.apache.org [140.211.11.3]) by cust-asf.ponee.io (Postfix) with SMTP id 0D6C8160A8C for ; Sun, 18 Sep 2016 19:16:34 +0200 (CEST) Received: (qmail 9577 invoked by uid 500); 18 Sep 2016 17:16:34 -0000 Mailing-List: contact commits-help@groovy.apache.org; run by ezmlm Precedence: bulk List-Help: List-Unsubscribe: List-Post: List-Id: Reply-To: dev@groovy.apache.org Delivered-To: mailing list commits@groovy.apache.org Received: (qmail 9557 invoked by uid 99); 18 Sep 2016 17:16:34 -0000 Received: from git1-us-west.apache.org (HELO git1-us-west.apache.org) (140.211.11.23) by apache.org (qpsmtpd/0.29) with ESMTP; Sun, 18 Sep 2016 17:16:34 +0000 Received: by git1-us-west.apache.org (ASF Mail Server at git1-us-west.apache.org, from userid 33) id 01C04DFBA0; Sun, 18 Sep 2016 17:16:33 +0000 (UTC) Content-Type: text/plain; charset="us-ascii" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit From: jwagenleitner@apache.org To: commits@groovy.apache.org Date: Sun, 18 Sep 2016 17:16:34 -0000 Message-Id: <5cbd4427911e40b5a082b8ece78e13ca@git.apache.org> In-Reply-To: References: X-Mailer: ASF-Git Admin Mailer Subject: [2/2] groovy git commit: cleanup examples: convert EOL from crlf to lf archived-at: Sun, 18 Sep 2016 17:16:37 -0000 cleanup examples: convert EOL from crlf to lf Project: http://git-wip-us.apache.org/repos/asf/groovy/repo Commit: http://git-wip-us.apache.org/repos/asf/groovy/commit/0a6135b5 Tree: http://git-wip-us.apache.org/repos/asf/groovy/tree/0a6135b5 Diff: http://git-wip-us.apache.org/repos/asf/groovy/diff/0a6135b5 Branch: refs/heads/GROOVY_2_4_X Commit: 0a6135b54f4de351768a354f597b77f19742d2bb Parents: 0afacb4 Author: John Wagenleitner Authored: Sun Sep 18 09:47:00 2016 -0700 Committer: John Wagenleitner Committed: Sun Sep 18 10:15:05 2016 -0700 ---------------------------------------------------------------------- src/examples/astbuilder/build.xml | 88 ++-- src/examples/astbuilder/readme.txt | 53 +- .../DefaultGrailsDomainClassInjector.java | 528 +++++++++---------- .../grails/compiler/injection/DomainClass.java | 76 +-- src/examples/swing/BindingExample.groovy | 124 ++--- src/examples/swing/ModelNodeExample.groovy | 174 +++--- src/examples/swing/RegexCoachController.groovy | 210 ++++---- src/examples/swing/RegexCoachView.groovy | 104 ++-- .../swing/binding/caricature/JCaricature.java | 440 ++++++++-------- src/examples/swing/greet/Greet.groovy | 304 +++++------ src/examples/swing/greet/TwitterAPI.groovy | 322 +++++------ src/examples/swing/greet/View.groovy | 350 ++++++------ src/examples/swing/timelog/TimeLogMain.groovy | 92 ++-- src/examples/swing/timelog/TimeLogModel.groovy | 122 ++--- src/examples/swing/timelog/TimeLogView.groovy | 132 ++--- .../global/CompiledAtASTTransformation.groovy | 132 ++--- .../transforms/global/CompiledAtExample.groovy | 66 +-- .../global/LoggingASTTransformation.groovy | 146 ++--- .../transforms/global/LoggingExample.groovy | 96 ++-- src/examples/transforms/global/build.xml | 104 ++-- src/examples/transforms/global/readme.txt | 77 ++- .../local/LoggingASTTransformation.groovy | 146 ++--- .../transforms/local/LoggingExample.groovy | 128 ++--- .../transforms/local/WithLogging.groovy | 72 +-- src/examples/transforms/local/build.xml | 88 ++-- src/examples/transforms/local/readme.txt | 61 ++- 26 files changed, 2146 insertions(+), 2089 deletions(-) ---------------------------------------------------------------------- http://git-wip-us.apache.org/repos/asf/groovy/blob/0a6135b5/src/examples/astbuilder/build.xml ---------------------------------------------------------------------- diff --git a/src/examples/astbuilder/build.xml b/src/examples/astbuilder/build.xml index 7129e28..a8cd1ec 100644 --- a/src/examples/astbuilder/build.xml +++ b/src/examples/astbuilder/build.xml @@ -1,44 +1,44 @@ - - - - - - - - - - - - - - - - - - You can now run "groovy MainExample.groovy", "groovyc MainExample.groovy", or "groovy MainIntegrationTest.groovy" to see that the transformation worked. - - - - + + + + + + + + + + + + + + + + + + You can now run "groovy MainExample.groovy", "groovyc MainExample.groovy", or "groovy MainIntegrationTest.groovy" to see that the transformation worked. + + + + http://git-wip-us.apache.org/repos/asf/groovy/blob/0a6135b5/src/examples/astbuilder/readme.txt ---------------------------------------------------------------------- diff --git a/src/examples/astbuilder/readme.txt b/src/examples/astbuilder/readme.txt index 345f48a..25f7f99 100644 --- a/src/examples/astbuilder/readme.txt +++ b/src/examples/astbuilder/readme.txt @@ -1,22 +1,41 @@ -AstBuilder and AST Transformation Example - +==== + Licensed to the Apache Software Foundation (ASF) under one + or more contributor license agreements. See the NOTICE file + distributed with this work for additional information + regarding copyright ownership. The ASF licenses this file + to you 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. +==== + +AstBuilder and AST Transformation Example + This example shows how to use the AstBuilder to add a public static void main(String[]) -method to a class. - -The example requires ant in your path and the Groovy 1.7 (or greater) -Jar in your classpath. - -To build the example run "ant" from the current directory. The default -target will compile the classes needed. The last step of the build -script prints out the command needed to run the example. - -To run the example perform either of the following from the command lines: - groovy MainExample.groovy +method to a class. + +The example requires ant in your path and the Groovy 1.7 (or greater) +Jar in your classpath. + +To build the example run "ant" from the current directory. The default +target will compile the classes needed. The last step of the build +script prints out the command needed to run the example. + +To run the example perform either of the following from the command lines: + groovy MainExample.groovy groovyc MainExample.groovy (and then invoke with java or view with javap) - -The example should print: - Hello from the greet() method! - + +The example should print: + Hello from the greet() method! + No exceptions should occur. The MainIntegrationTest.groovy file shows how to invoke an ASTTransformation http://git-wip-us.apache.org/repos/asf/groovy/blob/0a6135b5/src/examples/org/codehaus/groovy/grails/compiler/injection/DefaultGrailsDomainClassInjector.java ---------------------------------------------------------------------- diff --git a/src/examples/org/codehaus/groovy/grails/compiler/injection/DefaultGrailsDomainClassInjector.java b/src/examples/org/codehaus/groovy/grails/compiler/injection/DefaultGrailsDomainClassInjector.java index ed855a0..848ebf3 100644 --- a/src/examples/org/codehaus/groovy/grails/compiler/injection/DefaultGrailsDomainClassInjector.java +++ b/src/examples/org/codehaus/groovy/grails/compiler/injection/DefaultGrailsDomainClassInjector.java @@ -1,264 +1,264 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you 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.grails.compiler.injection; - -//import org.apache.commons.logging.Log; -//import org.apache.commons.logging.LogFactory; - -import org.codehaus.groovy.ast.*; -import org.codehaus.groovy.ast.expr.*; -import org.codehaus.groovy.ast.stmt.ReturnStatement; -import org.codehaus.groovy.ast.stmt.Statement; -import org.codehaus.groovy.control.CompilePhase; -import org.codehaus.groovy.control.SourceUnit; -import org.codehaus.groovy.transform.ASTTransformation; -import org.codehaus.groovy.transform.GroovyASTTransformation; - -import java.lang.reflect.Modifier; -import java.net.URL; -import java.util.*; - -/** - * This is substantially the same code from Grails, except some references de-referenced - * and the macro class added. - * - * Default implementation of domain class injector interface that adds the 'id' - * and 'version' properties and other previously boilerplate code - * - * @author Graeme Rocher - * - * @since 0.2 - * - * Created: 20th June 2006 - */ -@GroovyASTTransformation(phase= CompilePhase.CANONICALIZATION) -public class DefaultGrailsDomainClassInjector implements ASTTransformation { - //GrailsDomainClassInjector { - - //private static final Log LOG = LogFactory.getLog(DefaultGrailsDomainClassInjector.class); - - - public void visit(ASTNode[] nodes, SourceUnit source) { - performInjection((ClassNode) nodes[1]); - } - - public void performInjection(ClassNode classNode) { - if(shouldInject(classNode)) { - injectIdProperty(classNode); - - injectVersionProperty(classNode); - - injectToStringMethod(classNode); - - injectAssociations(classNode); - - } - } - - public boolean shouldInject(URL url) { - return true; //return GrailsResourceUtils.isDomainClass(url); - } - - private boolean shouldInject(ClassNode classNode) { - //String fullName = GrailsASTUtils.getFullName(classNode); - //String mappingFile = GrailsDomainConfigurationUtil.getMappingFileName(fullName); - - //if(getClass().getResource(mappingFile)!=null) { - //if(LOG.isDebugEnabled()) { - //LOG.debug("[GrailsDomainInjector] Mapping file ["+mappingFile+"] found. Skipping property injection."); - //} - //return false; - //} - return true; - } - - private void injectAssociations(ClassNode classNode) { - - List properties = classNode.getProperties(); - List propertiesToAdd = new ArrayList(); - for (Iterator p = properties.iterator(); p.hasNext();) { - PropertyNode pn = (PropertyNode) p.next(); - final boolean isHasManyProperty = pn.getName().equals(/*GrailsDomainClassProperty.*/RELATES_TO_MANY) || pn.getName().equals(/*GrailsDomainClassProperty.*/HAS_MANY); - if(isHasManyProperty) { - Expression e = pn.getInitialExpression(); - propertiesToAdd.addAll(createPropertiesForHasManyExpression(e,classNode)); - } - final boolean isBelongsTo = pn.getName().equals(/*GrailsDomainClassProperty.*/BELONGS_TO); - if(isBelongsTo) { - Expression e = pn.getInitialExpression(); - propertiesToAdd.addAll(createPropertiesForBelongsToExpression(e,classNode)); - } - } - injectAssociationProperties(classNode,propertiesToAdd); - } - - private Collection createPropertiesForBelongsToExpression(Expression e, ClassNode classNode) - { - List properties = new ArrayList(); - if(e instanceof MapExpression) { - MapExpression me = (MapExpression)e; - List mapEntries = me.getMapEntryExpressions(); - for (Iterator i = mapEntries.iterator(); i.hasNext();) { - MapEntryExpression mme = (MapEntryExpression) i.next(); - String key = mme.getKeyExpression().getText(); - - String type = mme.getValueExpression().getText(); - - properties.add(new PropertyNode(key,Modifier.PUBLIC, ClassHelper.make(type) , classNode, null,null,null)); - } - } - - return properties; - } - - private void injectAssociationProperties(ClassNode classNode, List propertiesToAdd) { - for (Iterator i = propertiesToAdd.iterator(); i.hasNext();) { - PropertyNode pn = (PropertyNode) i.next(); - if(!/*GrailsASTUtils.*/hasProperty(classNode, pn.getName())) { - //if(LOG.isDebugEnabled()) { - // LOG.debug("[GrailsDomainInjector] Adding property [" + pn.getName() + "] to class [" + classNode.getName() + "]"); - //} - classNode.addProperty(pn); - } - } - } - - private List createPropertiesForHasManyExpression(Expression e, ClassNode classNode) { - List properties = new ArrayList(); - if(e instanceof MapExpression) { - MapExpression me = (MapExpression)e; - List mapEntries = me.getMapEntryExpressions(); - for (Iterator j = mapEntries.iterator(); j.hasNext();) { - MapEntryExpression mee = (MapEntryExpression) j.next(); - Expression keyExpression = mee.getKeyExpression(); - String key = keyExpression.getText(); - addAssociationForKey(key,properties,classNode); - } - } - return properties; - } - - private void addAssociationForKey(String key, List properties, ClassNode classNode) { - properties.add(new PropertyNode(key, Modifier.PUBLIC, new ClassNode(Set.class), classNode,null, null, null)); - } - - private void injectToStringMethod(ClassNode classNode) { - final boolean hasToString = /*GrailsASTUtils.*/implementsZeroArgMethod(classNode, "toString"); - - if(!hasToString) { - GStringExpression ge = new GStringExpression(classNode.getName() + " : ${id}"); - ge.addString(new ConstantExpression(classNode.getName()+" : ")); - ge.addValue(new VariableExpression("id")); - Statement s = new ReturnStatement(ge); - MethodNode mn = new MethodNode("toString",Modifier.PUBLIC,new ClassNode(String.class), new Parameter[0],new ClassNode[0],s); - //if(LOG.isDebugEnabled()) { - // LOG.debug("[GrailsDomainInjector] Adding method [toString()] to class [" + classNode.getName() + "]"); - //} - classNode.addMethod(mn); - } - } - - private void injectVersionProperty(ClassNode classNode) { - final boolean hasVersion = /*GrailsASTUtils.*/hasProperty(classNode, /*GrailsDomainClassProperty.*/VERSION); - - if(!hasVersion) { - //if(LOG.isDebugEnabled()) { - // LOG.debug("[GrailsDomainInjector] Adding property [" + GrailsDomainClassProperty.VERSION + "] to class [" + classNode.getName() + "]"); - //} - classNode.addProperty( /*GrailsDomainClassProperty.*/VERSION, Modifier.PUBLIC, new ClassNode(Long.class), null, null, null); - } - } - - private void injectIdProperty(ClassNode classNode) { - final boolean hasId = /*GrailsASTUtils.*/hasProperty(classNode,/*GrailsDomainClassProperty.*/IDENTITY); - - if(!hasId) { - //if(LOG.isDebugEnabled()) { - // LOG.debug("[GrailsDomainInjector] Adding property [" + GrailsDomainClassProperty.IDENTITY + "] to class [" + classNode.getName() + "]"); - //} - classNode.addProperty( /*GrailsDomainClassProperty.*/IDENTITY, Modifier.PUBLIC, new ClassNode(Long.class), null, null, null); - } - } - - - //*************************************************************** - // from GrailsASTUtils - //*************************************************************** - /** - * Returns whether a classNode has the specified property or not - * - * @param classNode The ClassNode - * @param propertyName The name of the property - * @return True if the property exists in the ClassNode - */ - public static boolean hasProperty(ClassNode classNode, String propertyName) { - if(classNode == null || propertyName == null || "".equals(propertyName.trim())) - return false; - - List properties = classNode.getProperties(); - for (Iterator i = properties.iterator(); i.hasNext();) { - PropertyNode pn = (PropertyNode) i.next(); - if(pn.getName().equals(propertyName)) - return true; - } - return false; - } - - /** - * Tests whether the ClasNode implements the specified method name - * - * @param classNode The ClassNode - * @param methodName The method name - * @return True if it does implement the method - */ - public static boolean implementsZeroArgMethod(ClassNode classNode, String methodName) { - return implementsMethod(classNode, methodName, new Class[0]); - } - - - /** - * Tests whether the ClassNode implements the specified method name - * - * @param classNode The ClassNode - * @param methodName The method name - * @param argTypes - * @return True if it implements the method - */ - private static boolean implementsMethod(ClassNode classNode, String methodName, Class[] argTypes) { - List methods = classNode.getMethods(); - if (argTypes == null || argTypes.length ==0) { - for (Iterator i = methods.iterator(); i.hasNext();) { - MethodNode mn = (MethodNode) i.next(); - boolean methodMatch = mn.getName().equals(methodName); - if(methodMatch)return true; - // TODO Implement further parameter analysis - } - } - return false; - } - - //*************************************************************** - // from GrailsDomainClassProperty - //*************************************************************** - private static final String RELATES_TO_MANY = "relatesToMany"; - private static final String BELONGS_TO = "belongsTo"; - private static final String HAS_MANY = "hasMany"; - private static final String IDENTITY = "id"; - private static final String VERSION = "version"; -} +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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.grails.compiler.injection; + +//import org.apache.commons.logging.Log; +//import org.apache.commons.logging.LogFactory; + +import org.codehaus.groovy.ast.*; +import org.codehaus.groovy.ast.expr.*; +import org.codehaus.groovy.ast.stmt.ReturnStatement; +import org.codehaus.groovy.ast.stmt.Statement; +import org.codehaus.groovy.control.CompilePhase; +import org.codehaus.groovy.control.SourceUnit; +import org.codehaus.groovy.transform.ASTTransformation; +import org.codehaus.groovy.transform.GroovyASTTransformation; + +import java.lang.reflect.Modifier; +import java.net.URL; +import java.util.*; + +/** + * This is substantially the same code from Grails, except some references de-referenced + * and the macro class added. + * + * Default implementation of domain class injector interface that adds the 'id' + * and 'version' properties and other previously boilerplate code + * + * @author Graeme Rocher + * + * @since 0.2 + * + * Created: 20th June 2006 + */ +@GroovyASTTransformation(phase= CompilePhase.CANONICALIZATION) +public class DefaultGrailsDomainClassInjector implements ASTTransformation { + //GrailsDomainClassInjector { + + //private static final Log LOG = LogFactory.getLog(DefaultGrailsDomainClassInjector.class); + + + public void visit(ASTNode[] nodes, SourceUnit source) { + performInjection((ClassNode) nodes[1]); + } + + public void performInjection(ClassNode classNode) { + if(shouldInject(classNode)) { + injectIdProperty(classNode); + + injectVersionProperty(classNode); + + injectToStringMethod(classNode); + + injectAssociations(classNode); + + } + } + + public boolean shouldInject(URL url) { + return true; //return GrailsResourceUtils.isDomainClass(url); + } + + private boolean shouldInject(ClassNode classNode) { + //String fullName = GrailsASTUtils.getFullName(classNode); + //String mappingFile = GrailsDomainConfigurationUtil.getMappingFileName(fullName); + + //if(getClass().getResource(mappingFile)!=null) { + //if(LOG.isDebugEnabled()) { + //LOG.debug("[GrailsDomainInjector] Mapping file ["+mappingFile+"] found. Skipping property injection."); + //} + //return false; + //} + return true; + } + + private void injectAssociations(ClassNode classNode) { + + List properties = classNode.getProperties(); + List propertiesToAdd = new ArrayList(); + for (Iterator p = properties.iterator(); p.hasNext();) { + PropertyNode pn = (PropertyNode) p.next(); + final boolean isHasManyProperty = pn.getName().equals(/*GrailsDomainClassProperty.*/RELATES_TO_MANY) || pn.getName().equals(/*GrailsDomainClassProperty.*/HAS_MANY); + if(isHasManyProperty) { + Expression e = pn.getInitialExpression(); + propertiesToAdd.addAll(createPropertiesForHasManyExpression(e,classNode)); + } + final boolean isBelongsTo = pn.getName().equals(/*GrailsDomainClassProperty.*/BELONGS_TO); + if(isBelongsTo) { + Expression e = pn.getInitialExpression(); + propertiesToAdd.addAll(createPropertiesForBelongsToExpression(e,classNode)); + } + } + injectAssociationProperties(classNode,propertiesToAdd); + } + + private Collection createPropertiesForBelongsToExpression(Expression e, ClassNode classNode) + { + List properties = new ArrayList(); + if(e instanceof MapExpression) { + MapExpression me = (MapExpression)e; + List mapEntries = me.getMapEntryExpressions(); + for (Iterator i = mapEntries.iterator(); i.hasNext();) { + MapEntryExpression mme = (MapEntryExpression) i.next(); + String key = mme.getKeyExpression().getText(); + + String type = mme.getValueExpression().getText(); + + properties.add(new PropertyNode(key,Modifier.PUBLIC, ClassHelper.make(type) , classNode, null,null,null)); + } + } + + return properties; + } + + private void injectAssociationProperties(ClassNode classNode, List propertiesToAdd) { + for (Iterator i = propertiesToAdd.iterator(); i.hasNext();) { + PropertyNode pn = (PropertyNode) i.next(); + if(!/*GrailsASTUtils.*/hasProperty(classNode, pn.getName())) { + //if(LOG.isDebugEnabled()) { + // LOG.debug("[GrailsDomainInjector] Adding property [" + pn.getName() + "] to class [" + classNode.getName() + "]"); + //} + classNode.addProperty(pn); + } + } + } + + private List createPropertiesForHasManyExpression(Expression e, ClassNode classNode) { + List properties = new ArrayList(); + if(e instanceof MapExpression) { + MapExpression me = (MapExpression)e; + List mapEntries = me.getMapEntryExpressions(); + for (Iterator j = mapEntries.iterator(); j.hasNext();) { + MapEntryExpression mee = (MapEntryExpression) j.next(); + Expression keyExpression = mee.getKeyExpression(); + String key = keyExpression.getText(); + addAssociationForKey(key,properties,classNode); + } + } + return properties; + } + + private void addAssociationForKey(String key, List properties, ClassNode classNode) { + properties.add(new PropertyNode(key, Modifier.PUBLIC, new ClassNode(Set.class), classNode,null, null, null)); + } + + private void injectToStringMethod(ClassNode classNode) { + final boolean hasToString = /*GrailsASTUtils.*/implementsZeroArgMethod(classNode, "toString"); + + if(!hasToString) { + GStringExpression ge = new GStringExpression(classNode.getName() + " : ${id}"); + ge.addString(new ConstantExpression(classNode.getName()+" : ")); + ge.addValue(new VariableExpression("id")); + Statement s = new ReturnStatement(ge); + MethodNode mn = new MethodNode("toString",Modifier.PUBLIC,new ClassNode(String.class), new Parameter[0],new ClassNode[0],s); + //if(LOG.isDebugEnabled()) { + // LOG.debug("[GrailsDomainInjector] Adding method [toString()] to class [" + classNode.getName() + "]"); + //} + classNode.addMethod(mn); + } + } + + private void injectVersionProperty(ClassNode classNode) { + final boolean hasVersion = /*GrailsASTUtils.*/hasProperty(classNode, /*GrailsDomainClassProperty.*/VERSION); + + if(!hasVersion) { + //if(LOG.isDebugEnabled()) { + // LOG.debug("[GrailsDomainInjector] Adding property [" + GrailsDomainClassProperty.VERSION + "] to class [" + classNode.getName() + "]"); + //} + classNode.addProperty( /*GrailsDomainClassProperty.*/VERSION, Modifier.PUBLIC, new ClassNode(Long.class), null, null, null); + } + } + + private void injectIdProperty(ClassNode classNode) { + final boolean hasId = /*GrailsASTUtils.*/hasProperty(classNode,/*GrailsDomainClassProperty.*/IDENTITY); + + if(!hasId) { + //if(LOG.isDebugEnabled()) { + // LOG.debug("[GrailsDomainInjector] Adding property [" + GrailsDomainClassProperty.IDENTITY + "] to class [" + classNode.getName() + "]"); + //} + classNode.addProperty( /*GrailsDomainClassProperty.*/IDENTITY, Modifier.PUBLIC, new ClassNode(Long.class), null, null, null); + } + } + + + //*************************************************************** + // from GrailsASTUtils + //*************************************************************** + /** + * Returns whether a classNode has the specified property or not + * + * @param classNode The ClassNode + * @param propertyName The name of the property + * @return True if the property exists in the ClassNode + */ + public static boolean hasProperty(ClassNode classNode, String propertyName) { + if(classNode == null || propertyName == null || "".equals(propertyName.trim())) + return false; + + List properties = classNode.getProperties(); + for (Iterator i = properties.iterator(); i.hasNext();) { + PropertyNode pn = (PropertyNode) i.next(); + if(pn.getName().equals(propertyName)) + return true; + } + return false; + } + + /** + * Tests whether the ClasNode implements the specified method name + * + * @param classNode The ClassNode + * @param methodName The method name + * @return True if it does implement the method + */ + public static boolean implementsZeroArgMethod(ClassNode classNode, String methodName) { + return implementsMethod(classNode, methodName, new Class[0]); + } + + + /** + * Tests whether the ClassNode implements the specified method name + * + * @param classNode The ClassNode + * @param methodName The method name + * @param argTypes + * @return True if it implements the method + */ + private static boolean implementsMethod(ClassNode classNode, String methodName, Class[] argTypes) { + List methods = classNode.getMethods(); + if (argTypes == null || argTypes.length ==0) { + for (Iterator i = methods.iterator(); i.hasNext();) { + MethodNode mn = (MethodNode) i.next(); + boolean methodMatch = mn.getName().equals(methodName); + if(methodMatch)return true; + // TODO Implement further parameter analysis + } + } + return false; + } + + //*************************************************************** + // from GrailsDomainClassProperty + //*************************************************************** + private static final String RELATES_TO_MANY = "relatesToMany"; + private static final String BELONGS_TO = "belongsTo"; + private static final String HAS_MANY = "hasMany"; + private static final String IDENTITY = "id"; + private static final String VERSION = "version"; +} http://git-wip-us.apache.org/repos/asf/groovy/blob/0a6135b5/src/examples/org/codehaus/groovy/grails/compiler/injection/DomainClass.java ---------------------------------------------------------------------- diff --git a/src/examples/org/codehaus/groovy/grails/compiler/injection/DomainClass.java b/src/examples/org/codehaus/groovy/grails/compiler/injection/DomainClass.java index f1eb0c7..3494ede 100644 --- a/src/examples/org/codehaus/groovy/grails/compiler/injection/DomainClass.java +++ b/src/examples/org/codehaus/groovy/grails/compiler/injection/DomainClass.java @@ -1,38 +1,38 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you 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.grails.compiler.injection; - -import org.codehaus.groovy.transform.GroovyASTTransformationClass; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * Created by IntelliJ IDEA. - * User: Danno - * Date: Jan 30, 2008 - * Time: 8:11:08 PM - */ -@Retention(RetentionPolicy.SOURCE) -@Target(ElementType.TYPE) -@GroovyASTTransformationClass("org.codehaus.groovy.grails.compiler.injection.DefaultGrailsDomainClassInjector") -public @interface DomainClass { -} +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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.grails.compiler.injection; + +import org.codehaus.groovy.transform.GroovyASTTransformationClass; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * Created by IntelliJ IDEA. + * User: Danno + * Date: Jan 30, 2008 + * Time: 8:11:08 PM + */ +@Retention(RetentionPolicy.SOURCE) +@Target(ElementType.TYPE) +@GroovyASTTransformationClass("org.codehaus.groovy.grails.compiler.injection.DefaultGrailsDomainClassInjector") +public @interface DomainClass { +} http://git-wip-us.apache.org/repos/asf/groovy/blob/0a6135b5/src/examples/swing/BindingExample.groovy ---------------------------------------------------------------------- diff --git a/src/examples/swing/BindingExample.groovy b/src/examples/swing/BindingExample.groovy index 14ec7b6..f3c370b 100644 --- a/src/examples/swing/BindingExample.groovy +++ b/src/examples/swing/BindingExample.groovy @@ -1,62 +1,62 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you 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. - */ -/** - * @author Danno Ferrin - * @since Groovy 1.1 - * - * The real interesting part of this example are in the three properties of button: - * - * text: bind(source:textField, sourceProperty:'text'), - * margin: bind(source:slider, sourceProperty:'value', converter:{[it, it, it, it] as Insets}), - * enabled: bind(source:checkBox, sourceProperty:'selected') - * - * This is where the real magic goes on, causing the button to react to the changes - * in the source widgets values. - */ - -import groovy.swing.SwingBuilder -import java.awt.GridBagConstraints as gb -import java.awt.Insets - -sb = SwingBuilder.build() { - frame = frame(defaultCloseOperation:javax.swing.JFrame.DISPOSE_ON_CLOSE) { - gridBagLayout() - - label("Text:", anchor:gb.WEST, insets:[6,6,3,3] as Insets) - textField = textField("Change Me!", fill:gb.HORIZONTAL, gridwidth:gb.REMAINDER, insets:[6,3,3,6] as Insets) - - label("Margin:", anchor:gb.WEST, insets:[3,6,3,3] as Insets) - slider = slider(value:5, fill:gb.HORIZONTAL, gridwidth:gb.REMAINDER, insets:[3,3,3,6] as Insets) - - panel() - checkBox = checkBox("Enbled", anchor:gb.WEST, gridwidth:gb.REMAINDER, insets:[3,3,3,6] as Insets) - - separator(fill:gb.HORIZONTAL, gridwidth:gb.REMAINDER) - - button(anchor:gb.CENTER, gridwidth:gb.REMAINDER, gridheight:gb.REMAINDER, weightx:1.0, weighty:1.0, insets:[3,6,6,6] as Insets, - text: bind(source:textField, sourceProperty:'text'), - margin: bind(source:slider, sourceProperty:'value', converter:{[it, it, it, it] as Insets}), - enabled: bind(source:checkBox, sourceProperty:'selected') - ) - } -} - -frame.pack() -frame.setSize(frame.width + 100, frame.height + 200) -frame.show() +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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. + */ +/** + * @author Danno Ferrin + * @since Groovy 1.1 + * + * The real interesting part of this example are in the three properties of button: + * + * text: bind(source:textField, sourceProperty:'text'), + * margin: bind(source:slider, sourceProperty:'value', converter:{[it, it, it, it] as Insets}), + * enabled: bind(source:checkBox, sourceProperty:'selected') + * + * This is where the real magic goes on, causing the button to react to the changes + * in the source widgets values. + */ + +import groovy.swing.SwingBuilder +import java.awt.GridBagConstraints as gb +import java.awt.Insets + +sb = SwingBuilder.build() { + frame = frame(defaultCloseOperation:javax.swing.JFrame.DISPOSE_ON_CLOSE) { + gridBagLayout() + + label("Text:", anchor:gb.WEST, insets:[6,6,3,3] as Insets) + textField = textField("Change Me!", fill:gb.HORIZONTAL, gridwidth:gb.REMAINDER, insets:[6,3,3,6] as Insets) + + label("Margin:", anchor:gb.WEST, insets:[3,6,3,3] as Insets) + slider = slider(value:5, fill:gb.HORIZONTAL, gridwidth:gb.REMAINDER, insets:[3,3,3,6] as Insets) + + panel() + checkBox = checkBox("Enbled", anchor:gb.WEST, gridwidth:gb.REMAINDER, insets:[3,3,3,6] as Insets) + + separator(fill:gb.HORIZONTAL, gridwidth:gb.REMAINDER) + + button(anchor:gb.CENTER, gridwidth:gb.REMAINDER, gridheight:gb.REMAINDER, weightx:1.0, weighty:1.0, insets:[3,6,6,6] as Insets, + text: bind(source:textField, sourceProperty:'text'), + margin: bind(source:slider, sourceProperty:'value', converter:{[it, it, it, it] as Insets}), + enabled: bind(source:checkBox, sourceProperty:'selected') + ) + } +} + +frame.pack() +frame.setSize(frame.width + 100, frame.height + 200) +frame.show() http://git-wip-us.apache.org/repos/asf/groovy/blob/0a6135b5/src/examples/swing/ModelNodeExample.groovy ---------------------------------------------------------------------- diff --git a/src/examples/swing/ModelNodeExample.groovy b/src/examples/swing/ModelNodeExample.groovy index 61fc880..d402f65 100644 --- a/src/examples/swing/ModelNodeExample.groovy +++ b/src/examples/swing/ModelNodeExample.groovy @@ -1,87 +1,87 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you 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. - */ -import groovy.swing.SwingBuilder -import static javax.swing.WindowConstants.* -import static java.awt.GridBagConstraints.* - -def bean = new ObservableMap([name:'Alice', phone:'719-555-1212', addr:'42 Other Way']) - -SwingBuilder.build { - frame = frame( - pack:true, - show:true, - defaultCloseOperation:DISPOSE_ON_CLOSE) - { - beanModel = model(bean, bind:false) - - gridBagLayout() - - label('Name:', constraints:gbc(insets:[6,6,3,3])) - textField(text:beanModel.name, - columns:20, - gridwidth:REMAINDER, - fill:HORIZONTAL, - weightx:1, - insets:[6,3,3,6]) - - label('Phone:', constraints:gbc(insets:[3,6,3,3])) - textField(text:beanModel.phone, - columns:20, - gridwidth:REMAINDER, - fill:HORIZONTAL, - weightx:1, - insets:[3,3,3,6]) - - label('Address:', constraints:gbc(insets:[3,6,3,3])) - textField(text:beanModel.addr, - columns:20, - gridwidth:REMAINDER, - fill:HORIZONTAL, - weightx:1, - insets:[3,3,3,6]) - - button('Reset', actionPerformed:{beanModel.update()}, - constraints:gbc(gridwidth:2, - anchor:EAST, - weightx:1, - insets:[9,0,0,6])) - button('Submit', - insets:[9,0,0,0], - actionPerformed: { - beanModel.reverseUpdate() - output.text = ("name = '$bean.name'\nphone = '$bean.phone'\naddr = '$bean.addr'\n\n") - }) - - separator(gridwidth:REMAINDER, - fill:HORIZONTAL, - insets:[3,6,3,6]) - label('Output:', - gridwidth:REMAINDER, - anchor:WEST, - insets:[3,6,3,6]) - scrollPane(preferredSize:[100, 100], - gridwidth:REMAINDER, - fill:BOTH, - weighty:1, - insets:[3,6,6,6]) - { - output = textArea() - } - } -} +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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. + */ +import groovy.swing.SwingBuilder +import static javax.swing.WindowConstants.* +import static java.awt.GridBagConstraints.* + +def bean = new ObservableMap([name:'Alice', phone:'719-555-1212', addr:'42 Other Way']) + +SwingBuilder.build { + frame = frame( + pack:true, + show:true, + defaultCloseOperation:DISPOSE_ON_CLOSE) + { + beanModel = model(bean, bind:false) + + gridBagLayout() + + label('Name:', constraints:gbc(insets:[6,6,3,3])) + textField(text:beanModel.name, + columns:20, + gridwidth:REMAINDER, + fill:HORIZONTAL, + weightx:1, + insets:[6,3,3,6]) + + label('Phone:', constraints:gbc(insets:[3,6,3,3])) + textField(text:beanModel.phone, + columns:20, + gridwidth:REMAINDER, + fill:HORIZONTAL, + weightx:1, + insets:[3,3,3,6]) + + label('Address:', constraints:gbc(insets:[3,6,3,3])) + textField(text:beanModel.addr, + columns:20, + gridwidth:REMAINDER, + fill:HORIZONTAL, + weightx:1, + insets:[3,3,3,6]) + + button('Reset', actionPerformed:{beanModel.update()}, + constraints:gbc(gridwidth:2, + anchor:EAST, + weightx:1, + insets:[9,0,0,6])) + button('Submit', + insets:[9,0,0,0], + actionPerformed: { + beanModel.reverseUpdate() + output.text = ("name = '$bean.name'\nphone = '$bean.phone'\naddr = '$bean.addr'\n\n") + }) + + separator(gridwidth:REMAINDER, + fill:HORIZONTAL, + insets:[3,6,3,6]) + label('Output:', + gridwidth:REMAINDER, + anchor:WEST, + insets:[3,6,3,6]) + scrollPane(preferredSize:[100, 100], + gridwidth:REMAINDER, + fill:BOTH, + weighty:1, + insets:[3,6,6,6]) + { + output = textArea() + } + } +} http://git-wip-us.apache.org/repos/asf/groovy/blob/0a6135b5/src/examples/swing/RegexCoachController.groovy ---------------------------------------------------------------------- diff --git a/src/examples/swing/RegexCoachController.groovy b/src/examples/swing/RegexCoachController.groovy index cb241e2..7fa97fd 100644 --- a/src/examples/swing/RegexCoachController.groovy +++ b/src/examples/swing/RegexCoachController.groovy @@ -1,105 +1,105 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you 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. - */ -import groovy.swing.SwingBuilder -import java.awt.Color -import java.awt.event.ActionEvent -import java.awt.event.ActionListener -import java.awt.event.KeyAdapter -import java.awt.event.KeyEvent -import java.util.regex.PatternSyntaxException -import javax.swing.text.DefaultHighlighter.DefaultHighlightPainter - -// inspired by http://weitz.de/regex-coach/ - -// define the view -def swing = new SwingBuilder() - -def gui = swing.build(RegexCoachView) - -def highlighter = new RegexHighliter(swing: swing) -swing.regexPane.addKeyListener(highlighter) -swing.targetPane.addKeyListener(highlighter) -swing.scanLeft.addActionListener(highlighter) -swing.scanRight.addActionListener(highlighter) -gui.show() - -class RegexHighliter extends KeyAdapter implements ActionListener { - def swing // reference to the view - int scanIndex // how many times to execute matcher.find() - def orange = new DefaultHighlightPainter(Color.ORANGE) - def yellow = new DefaultHighlightPainter(Color.YELLOW) - def red = new DefaultHighlightPainter(Color.RED) - - // react to user actions - public void actionPerformed(ActionEvent event) { - if (event.actionCommand == '<<-') {scanIndex = Math.max(scanIndex - 1, 0)} - if (event.actionCommand == '->>') {scanIndex++} - doHighlights() - } - public void keyReleased(KeyEvent event) { - scanIndex = 0 - doHighlights() - } - - private resetView() { - swing.regexPane.highlighter.removeAllHighlights() - swing.targetPane.highlighter.removeAllHighlights() - swing.regexStatus.text = ' ' - swing.targetStatus.text = ' ' - } - - // the main regex logic - private doHighlights() { - try { - resetView() - // note: get the text from the underlying document, - // otherwise carriage return/line feeds different when using the JTextPane text - def regex = swing.regexPane.document.getText(0, swing.regexPane.document.length) - def target = swing.targetPane.document.getText(0, swing.targetPane.document.length) - - def matcher = (target =~ regex) - - // scan past the matches before the match we want - int scan = 0 - while (scan < scanIndex) { - matcher.find() - scan++ - } - if (matcher.find()) { - // highlight any captured groups - int i = 0 - while (i++ < matcher.groupCount()) { - swing.targetPane.highlighter.addHighlight(matcher.start(i), matcher.end(i), orange) - } - // highlight whole match - swing.targetPane.highlighter.addHighlight(matcher.start(), matcher.end(), yellow) - if (regex.length() != 0) { - swing.targetStatus.text = "Match #${scanIndex + 1} from ${matcher.start()} to ${matcher.end()}." - } - } else {// not found - scanIndex = Math.max(scan - 1, 0) - if (scanIndex > 0) {doHighlights()} - swing.targetStatus.text = "No match." - } - } catch (PatternSyntaxException e) { - swing.regexPane.highlighter.addHighlight(e.index, e.index + 2, red) - swing.regexStatus.text = e.description - } - } -} +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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. + */ +import groovy.swing.SwingBuilder +import java.awt.Color +import java.awt.event.ActionEvent +import java.awt.event.ActionListener +import java.awt.event.KeyAdapter +import java.awt.event.KeyEvent +import java.util.regex.PatternSyntaxException +import javax.swing.text.DefaultHighlighter.DefaultHighlightPainter + +// inspired by http://weitz.de/regex-coach/ + +// define the view +def swing = new SwingBuilder() + +def gui = swing.build(RegexCoachView) + +def highlighter = new RegexHighliter(swing: swing) +swing.regexPane.addKeyListener(highlighter) +swing.targetPane.addKeyListener(highlighter) +swing.scanLeft.addActionListener(highlighter) +swing.scanRight.addActionListener(highlighter) +gui.show() + +class RegexHighliter extends KeyAdapter implements ActionListener { + def swing // reference to the view + int scanIndex // how many times to execute matcher.find() + def orange = new DefaultHighlightPainter(Color.ORANGE) + def yellow = new DefaultHighlightPainter(Color.YELLOW) + def red = new DefaultHighlightPainter(Color.RED) + + // react to user actions + public void actionPerformed(ActionEvent event) { + if (event.actionCommand == '<<-') {scanIndex = Math.max(scanIndex - 1, 0)} + if (event.actionCommand == '->>') {scanIndex++} + doHighlights() + } + public void keyReleased(KeyEvent event) { + scanIndex = 0 + doHighlights() + } + + private resetView() { + swing.regexPane.highlighter.removeAllHighlights() + swing.targetPane.highlighter.removeAllHighlights() + swing.regexStatus.text = ' ' + swing.targetStatus.text = ' ' + } + + // the main regex logic + private doHighlights() { + try { + resetView() + // note: get the text from the underlying document, + // otherwise carriage return/line feeds different when using the JTextPane text + def regex = swing.regexPane.document.getText(0, swing.regexPane.document.length) + def target = swing.targetPane.document.getText(0, swing.targetPane.document.length) + + def matcher = (target =~ regex) + + // scan past the matches before the match we want + int scan = 0 + while (scan < scanIndex) { + matcher.find() + scan++ + } + if (matcher.find()) { + // highlight any captured groups + int i = 0 + while (i++ < matcher.groupCount()) { + swing.targetPane.highlighter.addHighlight(matcher.start(i), matcher.end(i), orange) + } + // highlight whole match + swing.targetPane.highlighter.addHighlight(matcher.start(), matcher.end(), yellow) + if (regex.length() != 0) { + swing.targetStatus.text = "Match #${scanIndex + 1} from ${matcher.start()} to ${matcher.end()}." + } + } else {// not found + scanIndex = Math.max(scan - 1, 0) + if (scanIndex > 0) {doHighlights()} + swing.targetStatus.text = "No match." + } + } catch (PatternSyntaxException e) { + swing.regexPane.highlighter.addHighlight(e.index, e.index + 2, red) + swing.regexStatus.text = e.description + } + } +} http://git-wip-us.apache.org/repos/asf/groovy/blob/0a6135b5/src/examples/swing/RegexCoachView.groovy ---------------------------------------------------------------------- diff --git a/src/examples/swing/RegexCoachView.groovy b/src/examples/swing/RegexCoachView.groovy index 64e6ea5..c4b4664 100644 --- a/src/examples/swing/RegexCoachView.groovy +++ b/src/examples/swing/RegexCoachView.groovy @@ -1,53 +1,53 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you 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. - */ -import static java.awt.BorderLayout.* -import static javax.swing.JSplitPane.VERTICAL_SPLIT -import static javax.swing.WindowConstants.EXIT_ON_CLOSE - -frame(title: 'The Groovy Regex Coach', location: [20, 40], size: [600, 500], defaultCloseOperation: EXIT_ON_CLOSE) { - panel { - borderLayout() - splitPane(orientation: VERTICAL_SPLIT, dividerLocation: 150) { - panel { - borderLayout() - label(constraints: NORTH, text: 'Regular expression:') - scrollPane(constraints: CENTER) { - textPane(id: 'regexPane') - } - label(constraints: SOUTH, id: 'regexStatus', text: ' ') - } - panel { - borderLayout() - label(constraints: NORTH, text: 'Target string:') - scrollPane(constraints: CENTER) { - textPane(id: 'targetPane') - } - panel(constraints: SOUTH) { - borderLayout() - label(constraints: NORTH, id: 'targetStatus', text: ' ') - panel(constraints: SOUTH) { - flowLayout() - button('<<-', id: 'scanLeft') - button('->>', id: 'scanRight') - } - } - } - } - } +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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. + */ +import static java.awt.BorderLayout.* +import static javax.swing.JSplitPane.VERTICAL_SPLIT +import static javax.swing.WindowConstants.EXIT_ON_CLOSE + +frame(title: 'The Groovy Regex Coach', location: [20, 40], size: [600, 500], defaultCloseOperation: EXIT_ON_CLOSE) { + panel { + borderLayout() + splitPane(orientation: VERTICAL_SPLIT, dividerLocation: 150) { + panel { + borderLayout() + label(constraints: NORTH, text: 'Regular expression:') + scrollPane(constraints: CENTER) { + textPane(id: 'regexPane') + } + label(constraints: SOUTH, id: 'regexStatus', text: ' ') + } + panel { + borderLayout() + label(constraints: NORTH, text: 'Target string:') + scrollPane(constraints: CENTER) { + textPane(id: 'targetPane') + } + panel(constraints: SOUTH) { + borderLayout() + label(constraints: NORTH, id: 'targetStatus', text: ' ') + panel(constraints: SOUTH) { + flowLayout() + button('<<-', id: 'scanLeft') + button('->>', id: 'scanRight') + } + } + } + } + } } \ No newline at end of file http://git-wip-us.apache.org/repos/asf/groovy/blob/0a6135b5/src/examples/swing/binding/caricature/JCaricature.java ---------------------------------------------------------------------- diff --git a/src/examples/swing/binding/caricature/JCaricature.java b/src/examples/swing/binding/caricature/JCaricature.java index 67b557c..5fdce3d 100644 --- a/src/examples/swing/binding/caricature/JCaricature.java +++ b/src/examples/swing/binding/caricature/JCaricature.java @@ -1,220 +1,220 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you 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. - */ -/* - * Caricature.java - * - * Created on April 8, 2006, 4:09 PM - * - * To change this template, choose Tools | Template Manager - * and open the template in the editor. - */ - -package groovy.swing.binding.caricature; - -import java.awt.Dimension; -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.Image; -import java.net.URL; -import java.util.HashMap; -import java.util.Map; -import javax.swing.ImageIcon; -import javax.swing.JPanel; - -/** - * - * @author sky - */ -public class JCaricature extends JPanel { - private Map/**/ imageMap; - - private boolean empty; - private int mouthStyle; - private int faceStyle; - private int hairStyle; - private int eyeStyle; - private int noseStyle; - private int rotation; - private float scale = 1.0f; - - public JCaricature() { - if (imageMap == null) { - imageMap = new HashMap/**/(1); - for (int i = 0; i < 5; i++) { - getImage("face", i); - getImage("hair", i); - getImage("eyes", i); - getImage("nose", i); - getImage("mouth", i); - } - } - } - - public void setEmpty(boolean empty) { - if (this.empty != empty) { - this.empty = empty; - firePropertyChange("empty", !empty, empty); - repaint(); - } - } - - public boolean isEmpty() { - return empty; - } - - public void setRotation(int rotation) { - int oldRotation = this.rotation; - this.rotation = rotation; - repaint(); - firePropertyChange("rotation", oldRotation, rotation); - } - - public int getRotation() { - return rotation; - } - - public void setScale(float scale) { - float oldScale = this.scale; - this.scale = scale; - repaint(); - firePropertyChange("scale", oldScale, scale); - } - - public float getScale() { - return scale; - } - - public void setMouthStyle(int style) { - int oldStyle = mouthStyle; - mouthStyle = style; - firePropertyChange("mouthStyle", oldStyle, style); - repaint(); - } - - public int getMouthStyle() { - return mouthStyle; - } - - public void setFaceStyle(int style) { - int oldStyle = faceStyle; - faceStyle = style; - firePropertyChange("faceStyle", oldStyle, style); - repaint(); - } - - public int getFaceStyle() { - return faceStyle; - } - - public void setHairStyle(int style) { - int oldStyle = hairStyle; - hairStyle = style; - firePropertyChange("hairStyle", oldStyle, style); - repaint(); - } - - public int getHairStyle() { - return hairStyle; - } - - public void setEyeStyle(int style) { - int oldStyle = eyeStyle; - eyeStyle = style; - firePropertyChange("eyeStyle", oldStyle, style); - repaint(); - } - - public int getEyeStyle() { - return eyeStyle; - } - - public void setNoseStyle(int style) { - int oldStyle = noseStyle; - noseStyle = style; - firePropertyChange("noseStyle", oldStyle, style); - repaint(); - } - - public int getNoseStyle() { - return noseStyle; - } - - public Dimension getPreferredSize() { - if (!isPreferredSizeSet()) { - Image image = getImage("mouth", 0); - return new Dimension(image.getWidth(null), image.getHeight(null)); - } - return super.getPreferredSize(); - } - - public Dimension getMaximumSize() { - if (!isMaximumSizeSet()) { - return getPreferredSize(); - } - return super.getMaximumSize(); - } - - protected void paintComponent(Graphics g) { - super.paintComponent(g); - if (empty) { - return; - } - Graphics2D g2 = (Graphics2D)g.create(); - Image image = getImage("face", getFaceStyle()); - int iw = image.getWidth(null); - int ih = image.getHeight(null); -// g2.translate(iw / 2, ih / 2); - g2.translate(getWidth() / 2, getHeight() / 2); - if (iw != getWidth()) { - float forcedScale = (float)getWidth() / (float)iw; - g2.scale(forcedScale, forcedScale); - } - float scale = getScale(); - if (scale != 1) { - g2.scale((double)scale, (double)scale); - } - int rotation = getRotation(); - if (rotation != 0) { - g2.rotate(Math.toRadians(rotation)); - } - drawImage(g2, "face", getFaceStyle()); - drawImage(g2, "hair", getHairStyle()); - drawImage(g2, "eyes", getEyeStyle()); - drawImage(g2, "nose", getNoseStyle()); - drawImage(g2, "mouth", getMouthStyle()); - g2.dispose(); - } - - private void drawImage(Graphics g, String string, int i) { - Image image = getImage(string, i); - g.drawImage(image, -image.getWidth(null) / 2, -image.getHeight(null) / 2, null); - } - - private Image getImage(String key, int style) { - String imageName = key + (style + 1) + ".gif"; - Image image = (Image) imageMap.get(imageName); - if (image == null) { - System.err.println("name=" + imageName); - URL imageLoc = getClass().getResource("resources/" + imageName); - image = new ImageIcon(imageLoc).getImage(); - imageMap.put(imageName, image); - } - return image; - } -} +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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. + */ +/* + * Caricature.java + * + * Created on April 8, 2006, 4:09 PM + * + * To change this template, choose Tools | Template Manager + * and open the template in the editor. + */ + +package groovy.swing.binding.caricature; + +import java.awt.Dimension; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.Image; +import java.net.URL; +import java.util.HashMap; +import java.util.Map; +import javax.swing.ImageIcon; +import javax.swing.JPanel; + +/** + * + * @author sky + */ +public class JCaricature extends JPanel { + private Map/**/ imageMap; + + private boolean empty; + private int mouthStyle; + private int faceStyle; + private int hairStyle; + private int eyeStyle; + private int noseStyle; + private int rotation; + private float scale = 1.0f; + + public JCaricature() { + if (imageMap == null) { + imageMap = new HashMap/**/(1); + for (int i = 0; i < 5; i++) { + getImage("face", i); + getImage("hair", i); + getImage("eyes", i); + getImage("nose", i); + getImage("mouth", i); + } + } + } + + public void setEmpty(boolean empty) { + if (this.empty != empty) { + this.empty = empty; + firePropertyChange("empty", !empty, empty); + repaint(); + } + } + + public boolean isEmpty() { + return empty; + } + + public void setRotation(int rotation) { + int oldRotation = this.rotation; + this.rotation = rotation; + repaint(); + firePropertyChange("rotation", oldRotation, rotation); + } + + public int getRotation() { + return rotation; + } + + public void setScale(float scale) { + float oldScale = this.scale; + this.scale = scale; + repaint(); + firePropertyChange("scale", oldScale, scale); + } + + public float getScale() { + return scale; + } + + public void setMouthStyle(int style) { + int oldStyle = mouthStyle; + mouthStyle = style; + firePropertyChange("mouthStyle", oldStyle, style); + repaint(); + } + + public int getMouthStyle() { + return mouthStyle; + } + + public void setFaceStyle(int style) { + int oldStyle = faceStyle; + faceStyle = style; + firePropertyChange("faceStyle", oldStyle, style); + repaint(); + } + + public int getFaceStyle() { + return faceStyle; + } + + public void setHairStyle(int style) { + int oldStyle = hairStyle; + hairStyle = style; + firePropertyChange("hairStyle", oldStyle, style); + repaint(); + } + + public int getHairStyle() { + return hairStyle; + } + + public void setEyeStyle(int style) { + int oldStyle = eyeStyle; + eyeStyle = style; + firePropertyChange("eyeStyle", oldStyle, style); + repaint(); + } + + public int getEyeStyle() { + return eyeStyle; + } + + public void setNoseStyle(int style) { + int oldStyle = noseStyle; + noseStyle = style; + firePropertyChange("noseStyle", oldStyle, style); + repaint(); + } + + public int getNoseStyle() { + return noseStyle; + } + + public Dimension getPreferredSize() { + if (!isPreferredSizeSet()) { + Image image = getImage("mouth", 0); + return new Dimension(image.getWidth(null), image.getHeight(null)); + } + return super.getPreferredSize(); + } + + public Dimension getMaximumSize() { + if (!isMaximumSizeSet()) { + return getPreferredSize(); + } + return super.getMaximumSize(); + } + + protected void paintComponent(Graphics g) { + super.paintComponent(g); + if (empty) { + return; + } + Graphics2D g2 = (Graphics2D)g.create(); + Image image = getImage("face", getFaceStyle()); + int iw = image.getWidth(null); + int ih = image.getHeight(null); +// g2.translate(iw / 2, ih / 2); + g2.translate(getWidth() / 2, getHeight() / 2); + if (iw != getWidth()) { + float forcedScale = (float)getWidth() / (float)iw; + g2.scale(forcedScale, forcedScale); + } + float scale = getScale(); + if (scale != 1) { + g2.scale((double)scale, (double)scale); + } + int rotation = getRotation(); + if (rotation != 0) { + g2.rotate(Math.toRadians(rotation)); + } + drawImage(g2, "face", getFaceStyle()); + drawImage(g2, "hair", getHairStyle()); + drawImage(g2, "eyes", getEyeStyle()); + drawImage(g2, "nose", getNoseStyle()); + drawImage(g2, "mouth", getMouthStyle()); + g2.dispose(); + } + + private void drawImage(Graphics g, String string, int i) { + Image image = getImage(string, i); + g.drawImage(image, -image.getWidth(null) / 2, -image.getHeight(null) / 2, null); + } + + private Image getImage(String key, int style) { + String imageName = key + (style + 1) + ".gif"; + Image image = (Image) imageMap.get(imageName); + if (image == null) { + System.err.println("name=" + imageName); + URL imageLoc = getClass().getResource("resources/" + imageName); + image = new ImageIcon(imageLoc).getImage(); + imageMap.put(imageName, image); + } + return image; + } +} http://git-wip-us.apache.org/repos/asf/groovy/blob/0a6135b5/src/examples/swing/greet/Greet.groovy ---------------------------------------------------------------------- diff --git a/src/examples/swing/greet/Greet.groovy b/src/examples/swing/greet/Greet.groovy index 73b8f96..ca93900 100644 --- a/src/examples/swing/greet/Greet.groovy +++ b/src/examples/swing/greet/Greet.groovy @@ -1,153 +1,153 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you 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. - */ -/* - * Created by IntelliJ IDEA. - * User: Danno.Ferrin - * Date: Apr 26, 2008 - * Time: 8:32:03 AM - */ -package groovy.swing.greet - -import groovy.beans.Bindable -import groovy.swing.SwingBuilder -import javax.swing.JOptionPane - -class Greet { - - TwitterAPI api - Binding view - - @Bindable boolean allowLogin = true - @Bindable boolean allowSelection = true - @Bindable boolean allowTweet = true - @Bindable def focusedUser = "" - @Bindable def friends = [] - @Bindable def tweets = [] - @Bindable def timeline = [] - @Bindable def statuses = [] - - void startUp() { - setAllowSelection(false) - setAllowTweet(false) - view.greetFrame.show() - view.loginDialog.show() - } - - void login(evt) { - setAllowLogin(false) - view.doOutside { - try { - if (api.login(view.twitterNameField.text, view.twitterPasswordField.password)) { - setFriends(api.getFriends(api.authenticatedUser)) - friends.each {it.status.user = [screen_name:it.screen_name, profile_image_url:it.profile_image_url] } - setStatuses(friends.collect {it.status}) - selectUser(api.authenticatedUser) - view.greetFrame.show() - view.loginDialog.dispose() - } else { - JOptionPane.showMessageDialog(view.loginDialog, "Login failed") - } - } catch (Exception e) { - e.printStackTrace() - } finally { - view.edt { - setAllowLogin(true) - setAllowSelection(true) - setAllowTweet(true) - } - } - } - } - - void filterTweets(evt = null) { - setAllowSelection(false) - setAllowTweet(false) - view.doOutside { - try { - setStatuses( - friends.collect {it.status}.findAll {it.text =~ view.searchField.text} - ) - setTimeline( - api.getFriendsTimeline(focusedUser).findAll {it.text =~ view.searchField.text} - ) - setTweets( - api.getTweets(focusedUser).findAll {it.text =~ view.searchField.text} - ) - } catch (Exception e) { - e.printStackTrace() - } finally { - view.edt { - setAllowSelection(true) - setAllowTweet(true) - } - } - } - } - - def userSelected(evt) { - view.doOutside { - selectUser(view.users.selectedItem) - } - } - - def selectUser(user) { - setAllowSelection(false) - setAllowTweet(false) - try { - setFocusedUser(api.getUser(user.screen_name as String)) - setTweets(api.getTweets(focusedUser).findAll {it.text =~ view.searchField.text}) - setTimeline(api.getFriendsTimeline(focusedUser).findAll {it.text =~ view.searchField.text}) - } finally { - view.edt { - setAllowSelection(true) - setAllowTweet(true) - } - } - } - - def tweet(evt = null) { - setAllowTweet(false) - view.doOutside { - try { - api.tweet(view.tweetBox.text) - // true story: it froze w/o the EDT call here - view.edt {tweetBox.text = ""} - filterTweets() - } finally { - setAllowTweet(true) - } - } - } - - public static void main(String[] args) { - def model = new TwitterAPI() - def controller = new Greet() - def view = new SwingBuilder() - - controller.api = model - controller.view = view - - view.controller = controller - - view.build(View) - view.view = view - - controller.startUp() - } +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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. + */ +/* + * Created by IntelliJ IDEA. + * User: Danno.Ferrin + * Date: Apr 26, 2008 + * Time: 8:32:03 AM + */ +package groovy.swing.greet + +import groovy.beans.Bindable +import groovy.swing.SwingBuilder +import javax.swing.JOptionPane + +class Greet { + + TwitterAPI api + Binding view + + @Bindable boolean allowLogin = true + @Bindable boolean allowSelection = true + @Bindable boolean allowTweet = true + @Bindable def focusedUser = "" + @Bindable def friends = [] + @Bindable def tweets = [] + @Bindable def timeline = [] + @Bindable def statuses = [] + + void startUp() { + setAllowSelection(false) + setAllowTweet(false) + view.greetFrame.show() + view.loginDialog.show() + } + + void login(evt) { + setAllowLogin(false) + view.doOutside { + try { + if (api.login(view.twitterNameField.text, view.twitterPasswordField.password)) { + setFriends(api.getFriends(api.authenticatedUser)) + friends.each {it.status.user = [screen_name:it.screen_name, profile_image_url:it.profile_image_url] } + setStatuses(friends.collect {it.status}) + selectUser(api.authenticatedUser) + view.greetFrame.show() + view.loginDialog.dispose() + } else { + JOptionPane.showMessageDialog(view.loginDialog, "Login failed") + } + } catch (Exception e) { + e.printStackTrace() + } finally { + view.edt { + setAllowLogin(true) + setAllowSelection(true) + setAllowTweet(true) + } + } + } + } + + void filterTweets(evt = null) { + setAllowSelection(false) + setAllowTweet(false) + view.doOutside { + try { + setStatuses( + friends.collect {it.status}.findAll {it.text =~ view.searchField.text} + ) + setTimeline( + api.getFriendsTimeline(focusedUser).findAll {it.text =~ view.searchField.text} + ) + setTweets( + api.getTweets(focusedUser).findAll {it.text =~ view.searchField.text} + ) + } catch (Exception e) { + e.printStackTrace() + } finally { + view.edt { + setAllowSelection(true) + setAllowTweet(true) + } + } + } + } + + def userSelected(evt) { + view.doOutside { + selectUser(view.users.selectedItem) + } + } + + def selectUser(user) { + setAllowSelection(false) + setAllowTweet(false) + try { + setFocusedUser(api.getUser(user.screen_name as String)) + setTweets(api.getTweets(focusedUser).findAll {it.text =~ view.searchField.text}) + setTimeline(api.getFriendsTimeline(focusedUser).findAll {it.text =~ view.searchField.text}) + } finally { + view.edt { + setAllowSelection(true) + setAllowTweet(true) + } + } + } + + def tweet(evt = null) { + setAllowTweet(false) + view.doOutside { + try { + api.tweet(view.tweetBox.text) + // true story: it froze w/o the EDT call here + view.edt {tweetBox.text = ""} + filterTweets() + } finally { + setAllowTweet(true) + } + } + } + + public static void main(String[] args) { + def model = new TwitterAPI() + def controller = new Greet() + def view = new SwingBuilder() + + controller.api = model + controller.view = view + + view.controller = controller + + view.build(View) + view.view = view + + controller.startUp() + } } \ No newline at end of file