diff --git a/BUILDING.txt b/BUILDING.txt deleted file mode 100644 index 1149cf3..0000000 --- a/BUILDING.txt +++ /dev/null @@ -1,177 +0,0 @@ - -Welcome to Beehive -================== - -To build Beehive, you will first need to check the source out from -Apache SVN and then install / configure required external software and -your shell environment. - -Checkout Beehive from SVN -========================= - -To do this, run the command: - - svn checkout https://svn.apache.org/repos/asf/beehive/trunk - -After running this command, you should have a directory "trunk/" which -contains the current Beehive source. If you ran this command in: - - d:\java\beehive - -you should have the directory: - - d:\java\beehive\trunk - -In the following steps, we'll refer to this as ${beehive.home}. - -Install / configure external software and setup your shell -========================================================== - -1) Java 5 - - Download: http://java.sun.com/j2se/1.5.0/download.jsp - - Install Java 5 and set the JAVA_HOME environment variable to -refernce the JDK install directory. Ensure that $JAVA_HOME/bin is -available in your $PATH. - -2) Ant 1.6.2+ - - Download: http://ant.apache.org/bindownload.cgi - - Ant 1.6.2 is the minimum version required to build Beehive. Install -Ant 1.6.2 and set the ANT_HOME environment variable to reference the -Ant install directory. Ensure that $ANT_HOME/bin is available in your -$PATH. Copy junit.jar (in external/junit/) to $ANT_HOME/lib. This step is -required in order for the Ant tasks to work correctly. - -3) Tomcat 5.0.x - - Download: http://jakarta.apache.org/site/binindex.cgi#tomcat - - Tomcat is used as the default test environment for Beehive. Install -Tomcat and set the CATALINA_HOME environment variable to reference the -Tomcat install directory. If you're installing Tomcat on Linux, -be sure to set the execute bit on the shell scripts in $CATALINA_HOME/bin. - - If you installed these into d:\java, your environment variables -might look something like: - - JAVA_HOME=d:\java\jdk1.5.0 - CATALINA_HOME=d:\java\jakarta-tomcat-5.0.25 - ANT_HOME=d:\java\apache-ant-1.6.2 - -Configure installed products - -In order to run the Beehive tests, ensure that Tomcat has the the -"manager" role is defined in ${CATALINA_HOME}/conf/tomcat-users.xml -with a "manager" role and manager username/password of manager/manager. -This step is required in order to use the Tomcat Ant tasks to deploy -applications to Tomcat. An example of this file is available here: - - ${beehive.home}/test/conf/tomcat-users.xml - -In the following examples, '$>' is your propmpt at $BEEHIVE_HOME, so if -you see '$>ant', type 'ant' (without the quotes) and press [enter]. - -In addition to the external software installed above, Beehive requires -one additional JAR to provide JSR 173 support for StAX, which is -required by XMLBeans. This JAR is downloaded from the network when -running Beehive's "bootstrap" target, so be sure to have a network -connection for your first build. A network connection is not required -for any subsequent builds. To install the JSR 173 API, run: - - $>ant bootstrap - -To check your Beehive build setup, run: - - $>ant check.setup - -This should end with "BUILD SUCCESSFUL" if you see any failures, be -sure to re-check your setup steps above. - -To build Beehive, run: - - $>ant clean deploy - -To run the Beehive tests, run: - - $>ant drt - -Using Proxies With a Beehive Build -==================================== - -If you need to use proxies you can setup additional environment variables -so that the Ant "bootstrap" target is successful in downloading the -JSR 173 API JAR file. - -PROXYHOST= -PROXYPORT= -PROXYUSER= -PROXYPASSWORD= -NONPROXYHOSTS= -SOCKSPROXYHOST= -SOCKSPROXYPORT= - -At a minimum, you will need to set PROXYHOST and PROXYPORT if your -network environment requires a proxy connection. To set these -environment variables in your shell, run: - - set PROXYHOST= - -in a Windows shell and - - export PROXYHOST= - -in a UNIX shell. - -For information on proxy support using the task, please -visit http://ant.apache.org/manual/OptionalTasks/setproxy.html - -Building Beehive documentation -============================= -The following documentation-related targets in -beehive/trunk/build.xml require that you have -Apache Forrest installed locally: - - $>ant docs - $>ant build.dist - -Before running these targets, complete the following steps. - -1) Download and install Forrest 0.7 on your machine. -A list of available download locations is available at: - - http://forrest.apache.org/mirrors.cgi - - -2) Copy the JAR file - - apache-forrest-0.7/lib/core/xml-commons-resolver-1.1.jar - -into - - $ANT_HOME/lib - -(This allows the Ant targets to call Forrest tasks.) - -3) Ensure that FORREST_HOME is set to the following path. - - On Windows machines: - set FORREST_HOME=C:\MyApacheStuff\apache-forrest-0.7 - - On Unix machines: - export FORREST_HOME=/MyApacheStuff/apache-forrest-0.7 - -4) Set the PATH as follows: - - On Windows machines: - set PATH=%FORREST_HOME%\bin;%PATH% - - On Unix machines: - export PATH=$FORREST_HOME/bin:$PATH - -You are now ready to run these targets: - - $>ant docs - $>ant build.dist diff --git a/DEVELOPING.txt b/DEVELOPING.txt deleted file mode 100644 index 5305f28..0000000 --- a/DEVELOPING.txt +++ /dev/null @@ -1,83 +0,0 @@ - -Developing in Beehive -===================== - -Hey; we're glad you're here! If you're interested in developing Beehive, the -information below is for you. First, make sure you've read the introduction -for Beehive contributors here: - - http://wiki.apache.org/beehive/For_Beehive_Developers - -This should help you get started setting up Beehive in your IDE and navigating -what code is where. - -You'll also need to configure your Subversion client to handle end-of-line styles -correctly. To do this, follow the directions below. - -Configuring your Subversion client -================================== - -Every text file must have the svn:eol-style property set to 'native'. This -causes ends-of-line to be translated to the correct format for the local -operating system when files are checked out (e.g., LF on linux, CR/LF on -Windows). You can do this on a per-file basis using the 'svn propset' command: - - svn propset svn:eol-style native - -An easier way to ensure that all added files have the right properties set is -to use the "auto-props" feature in the SVN client configuration file. The -location of this file varies depending on the operating system (see -http://svnbook.red-bean.com/svnbook/book.html#svn-ch-7-sect-1). -On Linux/UNIX it is located: - - ~/.subversion/config - -On Windows, it is typically located in a hidden directory: - - %SYSROOT%\Documents and Settings\\Application Data\Subversion -If you have problems locating this, make sure you can view hidden directory -contents. - -Confirm the "header" named [miscellany] is uncommented. - -Then, add (uncomment) the following line under the "[miscellany]" section: - - enable-auto-props = yes - -Then, add (uncomment) an "[auto-props]" section (include the [auto-props] -header as well) with a list of file extensions that will automatically -trigger the svn:eol-style=native property: - -[auto-props] -*.txt = svn:eol-style=native -*.java = svn:eol-style=native -*.jj = svn:eol-style=native -*.xml = svn:eol-style=native -*.xsd = svn:eol-style=native -*.xsdconfig = svn:eol-style=native -*.dtd = svn:eol-style=native -*.properties = svn:eol-style=native -*.jcs = svn:eol-style=native -*.jcx = svn:eol-style=native -*.jpf = svn:eol-style=native -*.jpfs = svn:eol-style=native -Global.app = svn:eol-style=native -*.jsp* = svn:eol-style=native -*.jspx = svn:eol-style=native -*.jspf = svn:eol-style=native -*.jsf = svn:eol-style=native -*.jsfb = svn:eol-style=native -*.faces = svn:eol-style=native -*.tld = svn:eol-style=native -*.tldx = svn:eol-style=native -*.tag = svn:eol-style=native -*.tagf = svn:eol-style=native -*.html = svn:eol-style=native -*.css = svn:eol-style=native -*.js = svn:eol-style=native -*.inc = svn:eol-style=native -*.sh = svn:eol-style=native;svn:executable -*.cmd = svn:eol-style=native -*.pl = svn:eol-style=native -*.py = svn:eol-style=native -*.beaninfo = svn:eol-style=native \ No newline at end of file diff --git a/LICENSE.txt b/LICENSE.txt index 5adf2ca..d645695 100644 --- a/LICENSE.txt +++ b/LICENSE.txt @@ -200,53 +200,3 @@ 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. - -============================================ - Licenses for Included Dependencies -============================================ - -The exceptions are as follows: - -============================================ - org/apache/beehive/netui/util/internal/concurrent/** -============================================ - - "Sun hereby grants you a non-exclusive, worldwide, non-transferrable - license to use and distribute the Java Software technologies as part - of a larger work in source and binary forms, with or without - modification, provided that the following conditions are met: - - -Neither the name of or trademarks of Sun may be used to endorse or - promote products derived from the Java Software technology without - specific prior written permission. - - -Redistributions of source or binary code must be accompanied by the - following notice and disclaimers: - - Portions copyright Sun Microsystems, Inc. Used with kind permission. - - This software is provided AS IS, without a warranty of any kind. ALL - EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND - WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF - MERCHANTABILITY, FITNESS FOR A PARTICULAR PUPOSE OR - NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN - MICROSYSTEMS, INC. AND ITS LICENSORS SHALL NOT BE LIABLE - FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF - USING, MODIFYING OR DISTRIBUTING THE SOFTWARE OR ITS - DERIVATIVES. IN NO EVENT WILL SUN MICROSYSTEMS, INC. OR - ITS LICENSORS BE LIABLE FOR ANY LOST REVENUE, PROFIT OR - DATA, OR FOR DIRECT, INDIRECT,CONSQUENTIAL, INCIDENTAL - OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF - THE THEORY OR LIABILITY, ARISING OUT OF THE USE OF OR - INABILITY TO USE SOFTWARE, EVEN IF SUN MICROSYSTEMS, INC. - HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. - - You acknowledge that Software is not designed, licensed or intended for - use in the design, construction, operation or maintenance of any nuclear - facility." - -============================================ - Spring Framework 1.1.5 -============================================ - - Licensed under terms of the Apache Software License (ASL) 2.0, provided above. \ No newline at end of file diff --git a/NOTICE.txt b/NOTICE.txt deleted file mode 100644 index 0469c6f..0000000 --- a/NOTICE.txt +++ /dev/null @@ -1,34 +0,0 @@ -========================================================================= -== NOTICE file corresponding to section 4(d) of the Apache License, == -== Version 2.0, in this case for the Apache Beehive distribution. == -========================================================================= - -This product includes software developed by -The Apache Software Foundation (http://www.apache.org/). - -Portions of this software were originally based on the following: - - * software copyright (c) 2000-2003, BEA Systems, . -and are licensed to the Apache Software Foundation under the -"Software Grant and Corporate Contribution License Agreement" - -Aside from contributions to the Apache Beehive project, this -software also includes: - - * One or more JARs from the Jakarta Commons, Jakarta ORO, Log4J, - Struts, and Velocity Apache projects, Copyright (c) 1999-2006 - Apache Software Foundation - - * One or more JARs from the Spring Framework Project - -See the LICENSE.txt file for information on all licenses associated with -this software. - -COPYRIGHT NOTICES: - -* Apache Beehive is bundled with source and binaries from the JSR-166 - implementation licensed under the relevant license in LICENSE.txt. - The source code and license are avaialble at: - http://gee.cs.oswego.edu/cgi-bin/viewcvs.cgi/jsr166/src/main/readme - -* Apache Beehive is bundled with binaries from The Spring Framework Project \ No newline at end of file diff --git a/README.txt b/README.txt deleted file mode 100644 index c3b3960..0000000 --- a/README.txt +++ /dev/null @@ -1,21 +0,0 @@ -Welcome to Beehive! - -If you've come here to learn more about Beehive, here are a few -starting points: - -BUILDING.txt: How to build Beehive on your machine. -DEVELOPING.txt Technical notes on contributing/committing files. -LICENSE.txt: The Apache License and any other relevant licenses for this software. -NOTICE.txt: Attribution notices required by various contributions. - -The Apache Beehive website is located at: - - http://beehive.apache.org - -And, the Beehive wiki is located at: - - http://wiki.apache.org/beehive - -Both of these contain additionl resources for getting started -with developing or using Beehive. - diff --git a/beehive-controls/README.txt b/beehive-controls/README.txt deleted file mode 100644 index f80e123..0000000 --- a/beehive-controls/README.txt +++ /dev/null @@ -1,98 +0,0 @@ -This directory contains the Beehive Controls source and test files. This -README provides an overview of the basic directory structure, and describes -some of the useful ant targets for building, generating javadoc, and running -tests for the Controls runtime. - -SOURCE DIRECTORY STRUCTURE: - -./src: - -Contains all of the source files for the Beehive Controls runtime. When the -runtime is built, all of the generated classes end up in -build/jars/controls.jar. - -./src/api: - -Contains all of the source files for Controls public APIs used by Control -authors or clients. All annotation type, interfaces, and classes in the public -API set live within the org.apache.beehive.controls.api.* package space. - -./src/spi: - -Contains a small set of service provider interfaces used to adapt or -extend the Controls runtime for a specific environment. The audience for -the SPI set is primary system developers who want to integrate the runtime -into a specific container or application server environment, implement a -specific type of interceptor or instantiation factory, etc. All of the -classes in the SPI set live within the org.apache.beehive.controls.spi.* -package space. - -./src/runtime: - -Contains the Control runtime implementation classes. There are several -base classes used for code-generated ControlBeans as well as supporting -runtime classes for properties, contextual services, container integration, -etc. Control authors or clients should never reference any of these -runtime classes directly. All of the runtime classes live within the -org.apache.beehive.controls.runtime.* package space. - -SOURCE DEPENDENCIES: - -The dependencies across the various types of Control sources are: - -api -> spi : API public factory classes depend upon some SPI interfaces -spi -> api : the SPI classes often consume public classes -runtime -> api, spi : the runtime classes reference both API and SPI types - -Note: there are *no* dependencies from public interfaces to runtime classes. -This relationship is enforced by actually having them compile separately -(api + spi first, then runtime). - -SOURCE ANT TARGETS - -This section describes some of the available ant targets from the Controls -root directory. - -ant build: - -Compiles all annotation type, interface, and class files in the API, SPI, and -runtime directory and creates build/jars/controls.jar to contain them. - -ant docs: - -Generates javadoc documention for all API, SPI, and runtime classes and puts -them in build/docs. After running this target, you can browse to -file:build/docs/apidocs/classref_controls/index.html to view them. - -ant clean: - -Removes all generated output files from any of the build targets in the top -level or test directories. - -TEST INFRASTRUCTURE: - -The Controls runtime test infrastructure lives under the test subdirectory. It -includes a variety of test for Controls running in different context, from -vanilla Junit/java tests to running Controls inside of the various containers -that are part of the Beehive programming model: JWS, JPF, and nesting inside -of other controls. More details about the Controls runtime test tools -can be found at http://wiki.apache.org/beehive/Controls/TestingControls. - -CONTROLS TEST TARGETS: - -There are two main test targets for running Controls tests. These should be run -from within the controls/test directory: - -ant checkin.tests: - -These are a set of checkin tests that do shallow testing of a broad range of -functionality. These should be run and pass 100% before a committer submits -any Controls runtime changes. - -ant detailed.tests: - -This runs all control tests. Since some of them are test cases that are the -basis of open JIRA issues, THESE TESTS ARE NOT EXPECTED TO PASS 100%. Currently, -there is no good filter for running the detailed tests that are expected to -pass, but it has been suggested that this would be a good thing (to enable -deeper testing of larger changes). diff --git a/beehive-controls/pom.xml b/beehive-controls/pom.xml deleted file mode 100644 index d5737dc..0000000 --- a/beehive-controls/pom.xml +++ /dev/null @@ -1,71 +0,0 @@ - - - - - - 4.0.0 - - com.moparisthebest.beehive - beehive - 1.0.5-SNAPSHOT - - beehive-controls - beehive-controls - - - velocity - velocity-dep - - - commons-discovery - commons-discovery - - - commons-logging - commons-logging - - - junit - junit - provided - - - org.apache.ant - ant - - - org.apache.ant - ant-launcher - - - javax.servlet.jsp - jsp-api - - - javax.servlet - servlet-api - - - com.moparisthebest.aptIn16 - apt-mirror-api - provided - - - \ No newline at end of file diff --git a/beehive-controls/src/main/java/org/apache/beehive/controls/api/ControlException.java b/beehive-controls/src/main/java/org/apache/beehive/controls/api/ControlException.java deleted file mode 100644 index ad62d73..0000000 --- a/beehive-controls/src/main/java/org/apache/beehive/controls/api/ControlException.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.api; - -/** - * The ControlException class declares an unchecked exception that is thrown by the Controls - * runtime under certain failure conditions. - */ -public class ControlException extends RuntimeException -{ - /** - * Default constructor. - */ - public ControlException() { - super(); - } - - /** - * Constructs a ControlException object with the specified String as a message. - * - * @param message The message to use. - */ - public ControlException(String message) - { - super(message); - } - - /** - * Constructs a ControlException with the specified cause. - * @param t the cause - */ - public ControlException(Throwable t) { - super(t); - } - - /** - * Constructs a ControlException object using the specified String as a message, and the - * specified Throwable as a nested exception. - * - * @param message The message to use. - * @param t The exception to nest within this exception. - */ - public ControlException(String message, Throwable t) - { - super(message + "[" + t + "]", t); - } -} diff --git a/beehive-controls/src/main/java/org/apache/beehive/controls/api/assembly/ControlAssembler.java b/beehive-controls/src/main/java/org/apache/beehive/controls/api/assembly/ControlAssembler.java deleted file mode 100644 index 64163c1..0000000 --- a/beehive-controls/src/main/java/org/apache/beehive/controls/api/assembly/ControlAssembler.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.api.assembly; - -/** - * Control implementations may need to do build-time work on or impacted by - * their control client(s), such as side-effecting their client's deployment - * descriptors, or generating additional files that are implementation- - * specific. - * - * The build phase where this work is done is called assembly, and occurs - * at the granularity level of the J2EE module. - * The control author participates in this phase by authoring classes that - * implement the ControlAssembler interface, and associating such classes - * with control implementations. Instances of ControlAssembler are then - * called at assembly-time by build tools. - */ -public interface ControlAssembler -{ - /** - * A ControlAssembler implementation's assemble method is called once - * per control assembler per module per assembly-time pass. The call - * passes a ControlAssemblyContext, from which information such as the - * list of client classes in the module that use the control can be - * obtained. - */ - void assemble(ControlAssemblyContext cac) throws ControlAssemblyException; -} - diff --git a/beehive-controls/src/main/java/org/apache/beehive/controls/api/assembly/ControlAssemblyContext.java b/beehive-controls/src/main/java/org/apache/beehive/controls/api/assembly/ControlAssemblyContext.java deleted file mode 100644 index a1c3198..0000000 --- a/beehive-controls/src/main/java/org/apache/beehive/controls/api/assembly/ControlAssemblyContext.java +++ /dev/null @@ -1,171 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.api.assembly; - -import java.io.File; -import java.lang.annotation.Annotation; -import java.lang.reflect.Method; -import java.util.Map; -import java.util.Set; - -import com.sun.mirror.apt.Messager; - -/** - * Control assemblers are passed a ControlAssemblyContext at the time they are - * invoked; the context allows the assemblers to interact with their external - * environment (checking files, side-effecting deployment descriptors, emitting - * code parameterized by the specifics of the control extension, etc). - * - * Beehive provides ControlAssemblyContext implementations that expose the - * standard environments of J2EE applications and modules. Vendor-specific - * implementations may provide access to their specific environment information, - * such as vendor-specific descriptors, via definition and implementation - * of additional interfaces. ControlAssemblers should use reflection to - * determine if the ControlAssemblyContext implementation they are passed - * supports a particular set of environment features. - */ -public interface ControlAssemblyContext -{ - /** - * Providers of ControlAssemblyContext implementations MUST implement - * Factory and newInstance to return their implementation. - */ - interface Factory - { - /** - * Creates a new instance of a ControlAssemblyContext implementation. - * - * @param controlIntfOrExt public interface/extension of the control - * type being assembled - * @param bindings map of control implementation bindings, null - * means use defaults. - * @param clients set of clients that use this control type. - * @param moduleRoot file root of the J2EE module containing the - * control clients to be assembled - * @param moduleName name of the J2EE module containing the - * control clients to be assembled - * @param srcOutputRoot file root of a location where assemblers - * should output any sources they create that - * may need further processing before use. - * @return a new instance of a ControlAssemblyContext implementation - */ - ControlAssemblyContext newInstance( Class controlIntfOrExt, - Map bindings, - Set clients, - File moduleRoot, - String moduleName, - File srcOutputRoot ) - throws ControlAssemblyException; - } - - /** - * Providers of ControlAssemblyContext implementations may implement - * EJBModule to provide access to an EJB module environment. - */ - interface EJBModule - { - // TODO: Provide more abstract helpers for common tasks. - // E.g. addResourceRef(). - - File getEjbJarXml(); - } - - /** - * Providers of ControlAssemblyContext implementations may implement - * WebAppModule to provide access to a webapp module environment. - */ - interface WebAppModule - { - File getWebXml(); - } - - /** - * Providers of ControlAssemblyContext implementations may implement - * EntAppModule to provide access to an enterprise application module - * environment. - */ - interface EntAppModule - { - File getApplicationXml(); - } - - /** - * @return the interface type of the control being assembled (annotated - * w/ ControlExtension or ControlInterface) - */ - Class getControlType(); - - /** - * @return the most derived interface of the control being assembled that - * is annotated with ControlInterface (may return the same as - * getControlType() if the control type is non-extended) - */ - Class getMostDerivedControlInterface(); - - /** - * @return an annotation on the interface returned by - * getControlType() - */ - T - getControlAnnotation(Class annotationClass); - - /** - * @return an annotation on a method on the interface - * returned by getControlType() - */ - T - getControlMethodAnnotation(Class annotationClass, Method m) - throws NoSuchMethodException; - - /** - * @return the defaultBinding member of the ControlInterface - */ - String getDefaultImplClassName(); - - /** - * @return the output directory into which "compilable" source should be output. - */ - File getSrcOutputDir(); - - /** - * @return the root of the module for which assembly is taking place. - */ - File getModuleDir(); - - /** - * @return the name of the module for which assembly is taking place. - */ - String getModuleName(); - - /** - * @return the set of clients (by class name) which use the control type - */ - Set getClients(); - - /** - * @return a Messager implementation that can be used to emit diagnostics during the - * assembly process. - */ - Messager getMessager(); - - /** - * @return true if the assembly process reported errors via the Messager - */ - boolean hasErrors(); -} diff --git a/beehive-controls/src/main/java/org/apache/beehive/controls/api/assembly/ControlAssemblyException.java b/beehive-controls/src/main/java/org/apache/beehive/controls/api/assembly/ControlAssemblyException.java deleted file mode 100644 index b5b5f83..0000000 --- a/beehive-controls/src/main/java/org/apache/beehive/controls/api/assembly/ControlAssemblyException.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.api.assembly; - -/** - * Checked exceptions thrown during the assembly process. ControlAssembler - * implementations may throw this exception in their assemble() method, which - * will halt the assembly process. - */ -public class ControlAssemblyException extends Exception -{ - public ControlAssemblyException(String msg) - { - super(msg); - } - - public ControlAssemblyException(String msg, Throwable cause) - { - super(msg, cause); - } -} diff --git a/beehive-controls/src/main/java/org/apache/beehive/controls/api/assembly/DefaultControlAssembler.java b/beehive-controls/src/main/java/org/apache/beehive/controls/api/assembly/DefaultControlAssembler.java deleted file mode 100644 index 4fa9817..0000000 --- a/beehive-controls/src/main/java/org/apache/beehive/controls/api/assembly/DefaultControlAssembler.java +++ /dev/null @@ -1,28 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.api.assembly; - -/** - * The default or "empty" control assembler that's assigned to an @ControlImplementation's - * assembler attribute if none is provided. - */ -public final class DefaultControlAssembler implements ControlAssembler -{ - public void assemble(ControlAssemblyContext cac) throws ControlAssemblyException { }; -} diff --git a/beehive-controls/src/main/java/org/apache/beehive/controls/api/bean/AnnotationConstraints.java b/beehive-controls/src/main/java/org/apache/beehive/controls/api/bean/AnnotationConstraints.java deleted file mode 100644 index b8b8ec4..0000000 --- a/beehive-controls/src/main/java/org/apache/beehive/controls/api/bean/AnnotationConstraints.java +++ /dev/null @@ -1,90 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.api.bean; - -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Retention; -import java.lang.annotation.ElementType; -import java.lang.annotation.Target; - -/** - * AnnotationConstraints defines meta-annotations that allow - * specification of additional constraints that aren't - * expressible using J2SE 5.0 meta-annotations. - * - * Actual enforcement of these semantics is implementation dependent. - * An apt-based reference implementation is provided by - * {@link org.apache.beehive.controls.runtime.bean.AnnotationConstraintValidator}. - * - * @see org.apache.beehive.controls.runtime.bean.AnnotationConstraintValidator - */ -public interface AnnotationConstraints -{ - /** - * Defines a number of simple constraints on the way annotation members - * can be used together. - * - * @see MembershipRule - */ - public enum MembershipRuleValues - { - AT_LEAST_ONE, - AT_MOST_ONE, - EXACTLY_ONE, - ALL_IF_ANY - } - - /** - * Provides a mechanism for enforcing constraints between members of - * an annotation (such a mechanism is absent from J2SE 5.0; for example, - * given an annotation with members 'a' and 'b' there is no way to say - * that they are mutually exclusive). - * - * @see MembershipRuleValues - */ - @Target({ElementType.ANNOTATION_TYPE}) - @Retention(RetentionPolicy.RUNTIME) - public @interface MembershipRule - { - /** Required, the membership rule.*/ - MembershipRuleValues value(); - /** Optional list of member names to apply rule against. Empty array implies all members. */ - String[] memberNames() default {}; - } - - /** - * Defines whether the annotation decorated by this - * annotation can overriden externally (a marker interface). - */ - @Target({ElementType.ANNOTATION_TYPE}) - @Retention(RetentionPolicy.RUNTIME) - public @interface AllowExternalOverride - { - } - - /** - * Specifies the version of the control runtime required by this annotation. - */ - @Target({ElementType.ANNOTATION_TYPE, ElementType.METHOD}) - @Retention(RetentionPolicy.RUNTIME) - public @interface RequiredRuntimeVersion - { - String value(); // no default - } -} diff --git a/beehive-controls/src/main/java/org/apache/beehive/controls/api/bean/AnnotationMemberTypes.java b/beehive-controls/src/main/java/org/apache/beehive/controls/api/bean/AnnotationMemberTypes.java deleted file mode 100644 index 994343e..0000000 --- a/beehive-controls/src/main/java/org/apache/beehive/controls/api/bean/AnnotationMemberTypes.java +++ /dev/null @@ -1,214 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.api.bean; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - *

AnnotationMemberTypes defines a set of annotations meant to used on - * annotation members to specify additional syntatic and semantic behaviour - * or constraints.

- * - *

J2SE 5 annotation members provide a very weak level of syntactic and - * semantic enforcement. Annotation members may only be a certain type - * (mostly primitives, arrays, plus java.lang.String and a few other classes); - * it is often useful to be more specific than those types permit.

- * - *

Consider the following example:

- * - *
- * public @interface LastChanged
- * {
- *     @AnnotationMemberTypes.Date()
- *     public String date();
- * }
- * 
- * - *

The use of @AnnotationMemberTypes.Date means that the - * value of the date string must be a date in some standard - * form.

- * - *

AnnotationMemberTypes defines a set of annotations and their semantics, - * but actual enforcement of those semantics is implementation dependent. - * An apt-based reference implementation is provided by - * {@link org.apache.beehive.controls.runtime.bean.AnnotationConstraintValidator}.

- * - * @see org.apache.beehive.controls.runtime.bean.AnnotationConstraintValidator - */ -public interface AnnotationMemberTypes -{ - public final static String OPTIONAL_STRING = ""; - public final static double OPTIONAL_DOUBLE = Double.MIN_VALUE; - public final static float OPTIONAL_FLOAT = Float.MIN_VALUE; - public final static int OPTIONAL_INT = Integer.MIN_VALUE; - public final static long OPTIONAL_LONG = Long.MIN_VALUE; - public final static short OPTIONAL_SHORT = Short.MIN_VALUE; - public final static char OPTIONAL_CHAR = Character.MIN_VALUE; - public final static byte OPTIONAL_BYTE = Byte.MIN_VALUE; - public final static int UNLIMITED_PLACES = -1; - - /** - * Marks a member as optional. Member must have - * a default value. - */ - @Target({ElementType.METHOD}) - @Retention(RetentionPolicy.RUNTIME) - public @interface Optional - { - } - - /** - * Member must be a String value. - */ - @Target({ElementType.METHOD}) - @Retention(RetentionPolicy.RUNTIME) - public @interface Text - { - boolean isLong() default false; - int maxLength() default Integer.MAX_VALUE; - } - - /** - * Member is a Decimal Value. - * Can be applied to a member that returns float, double or String. - */ - @Target({ElementType.METHOD}) - @Retention(RetentionPolicy.RUNTIME) - public @interface Decimal - { - int places() default UNLIMITED_PLACES; - double minValue() default Double.MIN_VALUE; - double maxValue() default Double.MAX_VALUE; - } - - /** - * Member is an Integer value. - * Can be applied to a member that returns String or int. - */ - @Target({ElementType.METHOD}) - @Retention(RetentionPolicy.RUNTIME) - public @interface Int - { - int minValue() default Integer.MIN_VALUE; - int maxValue() default Integer.MAX_VALUE; - } - - /** - * Member is a Date in the format specified (default is YYYY/MM/DD) - * Only valid on a member that returns String - * @see java.text.SimpleDateFormat when selecting another date format. - * Note: JSR175 does not allow java.util.Date as - * a member type. - */ - @Target({ElementType.METHOD}) - @Retention(RetentionPolicy.RUNTIME) - public @interface Date - { - String format() default "yyyy/MM/dd"; - String minValue() default ""; - String maxValue() default ""; - } - - /** - * Member is a URI - * Only valid on a member that returns String - */ - @Target({ElementType.METHOD}) - @Retention(RetentionPolicy.RUNTIME) - public @interface URI - { - } - - /** - * Member is a URN - * Only valid on a member that returns String - */ - @Target({ElementType.METHOD}) - @Retention(RetentionPolicy.RUNTIME) - public @interface URN - { - } - - /** - * Member is a URL - * Only valid on a member that returns String - */ - @Target({ElementType.METHOD}) - @Retention(RetentionPolicy.RUNTIME) - public @interface URL - { - } - - /** - * Member is a QName - * Only valid on a member that returns String - */ - @Target({ElementType.METHOD}) - @Retention(RetentionPolicy.RUNTIME) - public @interface QName - { - } - - /** - * Member contains well formed XML - * Only valid on a member that returns String - */ - @Target({ElementType.METHOD}) - @Retention(RetentionPolicy.RUNTIME) - public @interface XML - { - } - - /** - * Member is a File Path - * Compiler MUST validate that value points - * to a readable file. - * Only valid on a member that returns String. - */ - @Target({ElementType.METHOD}) - @Retention(RetentionPolicy.RUNTIME) - public @interface FilePath - { - } - - /** - * Member is a JNDI name. - */ - @Target({ElementType.METHOD}) - @Retention(RetentionPolicy.RUNTIME) - public @interface JndiName - { - /** - * Defines the type of JNDI resource reference by a member. - */ - public enum ResourceType - { - DATASOURCE, - EJB, - JMS_TOPIC, - JMS_QUEUE , - OTHER - } - - ResourceType resourceType(); - } -} diff --git a/beehive-controls/src/main/java/org/apache/beehive/controls/api/bean/Control.java b/beehive-controls/src/main/java/org/apache/beehive/controls/api/bean/Control.java deleted file mode 100644 index 5c16dc6..0000000 --- a/beehive-controls/src/main/java/org/apache/beehive/controls/api/bean/Control.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.api.bean; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * The Control annotation type is used to annotate a field within a control - * client source file that is a control reference. It is the declarative - * mechanism for instantiating controls in Java clients. Java Controls - * runtime implementations will automatically initialize such annotated field - * references to an appropriate Java Control Bean of the requested type, - * and perform event listener hookup etc. - */ -@Retention(RetentionPolicy.RUNTIME) -@Target({ElementType.FIELD}) -public @interface Control -{ - /** - * Optional member used to specify the control interface class. - * Typically only necessary to resolve ambiguities when multiple - * control interfaces with same name but different packages are present. - */ - Class interfaceHint() default Object.class; -} diff --git a/beehive-controls/src/main/java/org/apache/beehive/controls/api/bean/ControlBean.java b/beehive-controls/src/main/java/org/apache/beehive/controls/api/bean/ControlBean.java deleted file mode 100644 index 8239f54..0000000 --- a/beehive-controls/src/main/java/org/apache/beehive/controls/api/bean/ControlBean.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.api.bean; - -import java.beans.beancontext.BeanContext; -import java.beans.beancontext.BeanContextProxy; - -import org.apache.beehive.controls.api.context.ControlBeanContext; - -/** - * The ControlBean interface defines a base set of methods that are implemented by all - * JavaBeans that host Java Controls. - *

- * A ControlBean will implement the java.beans.beancontext.BeanContextProxy - * interface to provide a way to get the BeanContext directly associated - * with the Java Control. The getBeanContext() API on the interface will - * return the parent (containing) context. - * - * @see java.beans.beancontext.BeanContextProxy - */ -public interface ControlBean extends BeanContextProxy, java.io.Serializable -{ - /** - * The IDSeparator character is used to separated individual control IDs in nesting - * scenarios whether the identifier is actually a composite path that represents - * a nesting relationship. - */ - public static final char IDSeparator = '/'; - - /** - * Returns the java.beans.beancontext.BeanContext that provides the parent - * context for the Java Control. - * @return the containing BeanContext for the Java ControlBean. - * - * @see java.beans.beancontext.BeanContext - */ - BeanContext getBeanContext(); - - /** - * Returns the org.apache.beehive.controls.api.context.ControlBeanContext instance - * that provides the local context for this control bean. This is not the parent - * context for the control. It is the context that would be the parent context for - * any nested controls hosted by this control. - */ - ControlBeanContext getControlBeanContext(); - - /** - * Returns the unique control ID associated with the Java ControlBean. This control ID - * is guaranteed to be unique within the containing BeanContext - * @return the control ID - */ - String getControlID(); - - /** - * Returns the Java Control public interface for the ControlBean. This interface defines - * the operations and events exposed by the Java Control to its clients. - * @return the control public interface - */ - Class getControlInterface(); -} diff --git a/beehive-controls/src/main/java/org/apache/beehive/controls/api/bean/ControlChecker.java b/beehive-controls/src/main/java/org/apache/beehive/controls/api/bean/ControlChecker.java deleted file mode 100644 index a5fc91a..0000000 --- a/beehive-controls/src/main/java/org/apache/beehive/controls/api/bean/ControlChecker.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.api.bean; - -import com.sun.mirror.apt.AnnotationProcessorEnvironment; -import com.sun.mirror.declaration.Declaration; - -/** - * The ControlChecker interface is implemented by control authors wishing to - * enforce rich semantic validation on extension and field instance declarations of - * their controls. By supplying a ControlChecker implementation (a "checker") - * and associating it with your control's public interface, when an extension (.jcx) - * of your control is processed at build-time, the checker will be invoked and - * can do rich validation of the jcx type and field instances via introspection and - * analysis of the jcx's type structure, signatures and annotations. - *

- * Checkers are instantiated by, and required to implement, a no-arg constructor. - * They are provided with type information and context via the Sun mirror API. - */ -public interface ControlChecker -{ - /** - * Invoked by the control build-time infrastructure to process a declaration of - * a control extension (ie, an interface annotated with @ControlExtension), or - * a field instance of a control type. - */ - public void check(Declaration decl, AnnotationProcessorEnvironment env); -} diff --git a/beehive-controls/src/main/java/org/apache/beehive/controls/api/bean/ControlExtension.java b/beehive-controls/src/main/java/org/apache/beehive/controls/api/bean/ControlExtension.java deleted file mode 100644 index 114f19e..0000000 --- a/beehive-controls/src/main/java/org/apache/beehive/controls/api/bean/ControlExtension.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.api.bean; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * The ControlExtension annotation type is used to annotate a control extension interface. - */ -@Retention(RetentionPolicy.RUNTIME) -@Target({ElementType.TYPE}) -public @interface ControlExtension -{ - // Members parameterizing the control extension will be added here -} diff --git a/beehive-controls/src/main/java/org/apache/beehive/controls/api/bean/ControlImplementation.java b/beehive-controls/src/main/java/org/apache/beehive/controls/api/bean/ControlImplementation.java deleted file mode 100644 index 0e92f82..0000000 --- a/beehive-controls/src/main/java/org/apache/beehive/controls/api/bean/ControlImplementation.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.api.bean; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -import org.apache.beehive.controls.api.assembly.ControlAssembler; -import org.apache.beehive.controls.api.assembly.DefaultControlAssembler; - -/** - * The ControlImplementation annotation type is used to annotate the implementation class for a - * Java Control. It marks the class as a control implementation and (in the future) parameterizes - * it. - */ -@Retention(RetentionPolicy.RUNTIME) -@Target({ElementType.TYPE}) -public @interface ControlImplementation -{ - /** class name for the Class (which implements - * com.bea.control.assembly.ControlAssembler) whose assemble() - * method is called at assembly time - if left Void then no - * special assembly is needed - */ - Class assemblyHelperClass() default java.lang.Void.class; // DEPRECATED - - /** - * Class that implements ControlAssembler, which gets called at assembly time. - * Default implementation does nothing. - */ - Class assembler() default DefaultControlAssembler.class; - - /** - * Specifies whether the control implementation class contains state that should be - * serialized as part of the containing Control/JavaBean or is fully stateless/transient. - */ - boolean isTransient() default false; // default to assuming stateful -} diff --git a/beehive-controls/src/main/java/org/apache/beehive/controls/api/bean/ControlInterface.java b/beehive-controls/src/main/java/org/apache/beehive/controls/api/bean/ControlInterface.java deleted file mode 100644 index 409d19b..0000000 --- a/beehive-controls/src/main/java/org/apache/beehive/controls/api/bean/ControlInterface.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.api.bean; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * The ControlInterface annotation type is used to annotate a control public interface. - */ -@Retention(RetentionPolicy.RUNTIME) -@Target({ElementType.TYPE}) -public @interface ControlInterface -{ - /** - * Placeholder string used in defaultBinding attr. Tools and runtime should replace - * instances of INTERFACE_NAME found in values of defaultBinding with the fully - * qualified name of the interface annotated with @ControlInterface. - */ - static final String INTERFACE_NAME = ""; - - /** - * Specify the fully qualified name of the control implementation for this control interface. - * If no value is specified the implementation will be the name of the interface with 'Impl' appended. - * */ - String defaultBinding() default INTERFACE_NAME + "Impl"; - - /** - * @deprecated Replaced by checker() element. - */ - Class checkerClass() default DefaultControlChecker.class; - - /** - * Used by control authors wishing to enforce rich semantic validation on extension and field - * instance declarations of their controls. By supplying a ControlChecker implementation - * (a "checker") and associating it with your control's public interface, when an - * extension of your control is processed at build-time, the checker will be invoked and - * can do rich validation of the extension type and field instances via introspection and - * analysis of the control extension's type structure, signatures and annotations. - * @see org.apache.beehive.controls.api.bean.ControlChecker - */ - Class checker() default DefaultControlChecker.class; -} diff --git a/beehive-controls/src/main/java/org/apache/beehive/controls/api/bean/ControlReferences.java b/beehive-controls/src/main/java/org/apache/beehive/controls/api/bean/ControlReferences.java deleted file mode 100644 index 3447236..0000000 --- a/beehive-controls/src/main/java/org/apache/beehive/controls/api/bean/ControlReferences.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.api.bean; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * The ControlReferences annotation type is used to annotate a control client - * type, listing any control types that the client uses purely programmatically - * (and not declaratively). Tools will treat the union of the set of types - * annotated w/ @Control and the types listed in @ControlReferences as the - * complete set of controls used by a client. - */ -@Retention(RetentionPolicy.RUNTIME) -@Target({ElementType.TYPE}) -public @interface ControlReferences -{ - Class[] value() default {}; -} diff --git a/beehive-controls/src/main/java/org/apache/beehive/controls/api/bean/Controls.java b/beehive-controls/src/main/java/org/apache/beehive/controls/api/bean/Controls.java deleted file mode 100644 index 21dd7c9..0000000 --- a/beehive-controls/src/main/java/org/apache/beehive/controls/api/bean/Controls.java +++ /dev/null @@ -1,153 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.api.bean; - -import java.lang.reflect.Method; -import java.lang.reflect.InvocationTargetException; - -import org.apache.beehive.controls.api.properties.PropertyMap; -import org.apache.beehive.controls.api.context.ControlBeanContext; -import org.apache.beehive.controls.api.ControlException; -import org.apache.beehive.controls.spi.bean.ControlFactory; -import org.apache.beehive.controls.spi.bean.JavaControlFactory; -import org.apache.commons.discovery.tools.DiscoverClass; - -/** - * Helper class for using controls. Includes static methods to help instantiate controls, and initialize - * declarative control clients. - */ -public class Controls -{ - final private static String DEFAULT_FACTORY_CLASS = JavaControlFactory.class.getName(); - - /** - * Factory method for instantiating controls. Controls instantiated using this method will be associated with the - * current thread-local ControlBeanContext (possibly none), and have an auto-generated ID. - * - * @param cl the classloader used to load the ControlBean. If null, the system classloader will be used. - * @param beanName the fully qualified name of the ControlBean class. - * @param props an optional PropertyMap containing initial property values for the control. May be null. - * @return an instance of the specified ControlBean. - * @throws ClassNotFoundException - */ - public static ControlBean instantiate( ClassLoader cl, - String beanName, - PropertyMap props ) - throws ClassNotFoundException - { - return instantiate( cl, beanName, props, null, null ); - } - - /** - * Factory method for instantiating controls. - * - * @param cl the classloader used to load the ControlBean. If null, the system classloader will be used. - * @param beanName the fully qualified name of the ControlBean class. - * @param props an optional PropertyMap containing initial property values for the control. May be null. - * @param cbc the ControlBeanContext that will nest the created control. If null, the thread-local context - * (possibly none) will be used. - * @param id a unique ID for the created control. If null, an ID will be auto-generated. - * @return an instance of the specified ControlBean. - * @throws ClassNotFoundException - */ - public static ControlBean instantiate( ClassLoader cl, - String beanName, - PropertyMap props, - ControlBeanContext cbc, - String id ) - throws ClassNotFoundException - { - Class beanClass = ( cl == null ) ? Class.forName( beanName ) : cl.loadClass( beanName ); - return instantiate(beanClass, props, cbc, id); - } - - /** - * Factory method for instantiating controls. - * - * @param beanClass the ControlBean class to instantiate - * @param props an optional PropertyMap containing initial property values for the control. - * may be null. - * @param context the ControlBeanContext that will nest the created control. If null, the - * thread-local context (possibly none) will be used. - * @param id a unique ID for the created control. If null, an ID will be auto-generated. - * @return an instance of the specified ControlBean. - */ - public static T instantiate( Class beanClass, - PropertyMap props, - ControlBeanContext context, - String id ) - { - try - { - DiscoverClass discoverer = new DiscoverClass(); - Class factoryClass = discoverer.find( ControlFactory.class, DEFAULT_FACTORY_CLASS ); - ControlFactory factory = (ControlFactory)factoryClass.newInstance(); - return factory.instantiate( beanClass, props, context, id ); - } - catch ( Exception e ) - { - throw new ControlException( "Exception creating ControlBean", e ); - } - } - - /** - * Helper method for initializing instances of declarative control clients (objects that use controls via @Control - * and @EventHandler annotations). This method runs the client-specific generated ClientInitializer class to do - * its initialization work. - * - * @param cl the classloader used to load the ClientInitializer. If null, defaults to the classloader used to - * load the client object being initialized. - * @param client the client object being initialized. - * @param cbc the ControlBeanContext to be associated with the client object (that will nest the controls the client - * defines). If null, the thread-local context (possibly none) will be used. - * @throws ControlException - * @throws ClassNotFoundException - */ - public static void initializeClient( ClassLoader cl, Object client, ControlBeanContext cbc ) - throws ClassNotFoundException - { - Class clientClass = client.getClass(); - String clientName = clientClass.getName(); - - if ( cl == null ) - cl = clientClass.getClassLoader(); - - String initName = clientName + "ClientInitializer"; - Class initClass = cl.loadClass( initName ); - - try - { - Method m = initClass.getMethod( "initialize", ControlBeanContext.class, clientClass ); - m.invoke(null, cbc, client ); - } - catch ( Throwable e ) - { - if ( e instanceof InvocationTargetException ) - { - if ( e.getCause() != null ) - { - e = e.getCause(); - } - } - - throw new ControlException( "Exception trying to run client initializer: " + e.getClass().getName() + ", " + - e.getMessage(), e ); - } - } -} diff --git a/beehive-controls/src/main/java/org/apache/beehive/controls/api/bean/DefaultControlChecker.java b/beehive-controls/src/main/java/org/apache/beehive/controls/api/bean/DefaultControlChecker.java deleted file mode 100644 index 13911d5..0000000 --- a/beehive-controls/src/main/java/org/apache/beehive/controls/api/bean/DefaultControlChecker.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.api.bean; - -import com.sun.mirror.apt.AnnotationProcessorEnvironment; -import com.sun.mirror.declaration.Declaration; - -/** - * The default or "empty" control checker that assigned to an @ControlInterface's - * controlChecker attribute if none is provided. - */ -public final class DefaultControlChecker implements ControlChecker -{ - public void check(Declaration decl, AnnotationProcessorEnvironment env) { }; -} diff --git a/beehive-controls/src/main/java/org/apache/beehive/controls/api/bean/Extensible.java b/beehive-controls/src/main/java/org/apache/beehive/controls/api/bean/Extensible.java deleted file mode 100644 index 43b11a1..0000000 --- a/beehive-controls/src/main/java/org/apache/beehive/controls/api/bean/Extensible.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.api.bean; - -import java.lang.reflect.Method; - -/** - * The Extensible interface is implemented by a Java Control implementation class if the - * control defines an extensibility model that allows extended operations to be declared - * using a JCX interface. - *

- * The interface provides the invoke method, that is called whenever an - * extended operation is called by the client at run time. - */ -public interface Extensible -{ - /** - * Called by the Controls runtime to handle calls to methods of an - * extensible control. - *

- * @param method The extended operation that was called. - * @param args Parameters of the operation. - * @return The value that should be returned by the operation. - * @throws java.lang.Throwable any exception declared on the extended operation may be - * thrown. If a checked exception is thrown from the implementation that is not declared - * on the original interface, it will be wrapped in a ControlException. - */ - public Object invoke(Method method, Object[] args) throws Throwable; -} diff --git a/beehive-controls/src/main/java/org/apache/beehive/controls/api/bean/ExternalPropertySets.java b/beehive-controls/src/main/java/org/apache/beehive/controls/api/bean/ExternalPropertySets.java deleted file mode 100644 index b81cfdf..0000000 --- a/beehive-controls/src/main/java/org/apache/beehive/controls/api/bean/ExternalPropertySets.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.api.bean; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * Used on control interfaces to specify any external property sets that - * the control uses. External property sets are property sets that are - * their own top-level interfaces, i.e. not nested. - */ -@Retention(RetentionPolicy.RUNTIME) -@Target({ElementType.TYPE}) -public @interface ExternalPropertySets -{ - Class[] value(); -} diff --git a/beehive-controls/src/main/java/org/apache/beehive/controls/api/bean/Threading.java b/beehive-controls/src/main/java/org/apache/beehive/controls/api/bean/Threading.java deleted file mode 100644 index ed504f0..0000000 --- a/beehive-controls/src/main/java/org/apache/beehive/controls/api/bean/Threading.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.api.bean; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * Used to specify the desired threading policy to apply to a control - * implementation type. See {@link ThreadingPolicy}. Only permitted - * on classes that are also annotated with {@link ControlImplementation}. - */ -@Retention(RetentionPolicy.RUNTIME) -@Target({ElementType.TYPE}) -public @interface Threading -{ - ThreadingPolicy value() default ThreadingPolicy.SINGLE_THREADED; -} diff --git a/beehive-controls/src/main/java/org/apache/beehive/controls/api/bean/ThreadingPolicy.java b/beehive-controls/src/main/java/org/apache/beehive/controls/api/bean/ThreadingPolicy.java deleted file mode 100644 index 924963a..0000000 --- a/beehive-controls/src/main/java/org/apache/beehive/controls/api/bean/ThreadingPolicy.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.api.bean; - -/** - * Specifies threading policy for control implementations. The constants - * of this enumerated type describe the threading policies that apply - * during execution of controls. They are used in conjunction with the - * {@link Threading} annotation type to specify the responsibilities of - * the runtime infrastructure and control implementation with respect to - * threading. - */ -public enum ThreadingPolicy -{ - /** - * When a control implementation is declared as SINGLE_THREADED, the - * controls infrastructure ensures that only a single thread will be - * executing in a particular instance of that control at any time. - * This is the default policy if no {@link Threading} annotation is - * specified. - */ - SINGLE_THREADED, - /** - * When a control implementation is declared as MULTI_THREADED, the - * controls infrastructure permits multiple threads to concurrently - * execute in instances of that control. It is then the responsibility - * of the implementation to ensure internal thread-safety using - * standard Java concurrency mechanisms. This policy may yield higher - * performance, at the cost of additional work on the implementor's part. - */ - MULTI_THREADED -} diff --git a/beehive-controls/src/main/java/org/apache/beehive/controls/api/context/Context.java b/beehive-controls/src/main/java/org/apache/beehive/controls/api/context/Context.java deleted file mode 100644 index 7042160..0000000 --- a/beehive-controls/src/main/java/org/apache/beehive/controls/api/context/Context.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.api.context; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * The Context annotation type is used to annotate a field within a control implementation - * class that refers to a contextual service. The Java Controls runtime will automatically - * initialize the field value to an appropriate provider of the requested service, or will - * throw a construction or deserialization error if no such provider is available. - * - * The following is a simple example: - * - *

- * @ControlImplementation
- * public class MyControlImpl
- * {
- *     @Context
- *     ControlContext myContext;
- * }
- * 
- * This example declares a field named myContext that will automatically be - * initialized by the Java Controls runtime to refer to a provider of the - * ControlContext contextual service. - */ -@Retention(RetentionPolicy.RUNTIME) -@Target({ElementType.FIELD}) -public @interface Context -{ -} diff --git a/beehive-controls/src/main/java/org/apache/beehive/controls/api/context/ControlBeanContext.java b/beehive-controls/src/main/java/org/apache/beehive/controls/api/context/ControlBeanContext.java deleted file mode 100644 index 00871dc..0000000 --- a/beehive-controls/src/main/java/org/apache/beehive/controls/api/context/ControlBeanContext.java +++ /dev/null @@ -1,238 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.api.context; - -import java.beans.beancontext.BeanContextServices; -import java.beans.PropertyChangeEvent; -import java.beans.PropertyVetoException; -import java.lang.annotation.Annotation; -import java.lang.reflect.AnnotatedElement; -import java.lang.reflect.Method; - -import org.apache.beehive.controls.api.bean.ControlBean; -import org.apache.beehive.controls.api.events.EventSet; -import org.apache.beehive.controls.api.properties.PropertyMap; - -/** - * The ControlBeanContext interface defines the basic set of contextual services and lifecycle - * events for Java ControlBean implementations. - *

- * ControlBeanContext also extends the java.beans.beancontext.BeanContextServices - * interface, so it also provide core Java Beans services for managing contained controls, - * looking up contextual services, and locating the parent {@link java.beans.beancontext.BeanContext} context. - *

- * A Control implementation class can obtain access to the ControlBeanContext associated - * with it by declaring an instance field of this type and annotating it with the - * org.apache.beehive.controls.api.context.Context annotation, as in the following - * example: - * - *

- * import org.apache.beehive.controls.api.context.Context;
- * import org.apache.beehive.controls.api.context.ControlBeanContext;
- *
- * @ControlImplementation
- * public class MyControlImpl
- * {
- *     @Context
- *     ControlBeanContext myContext;
- * }
- * 
- * The Java Control runtime will automatically initialize this field to a reference to the - * ControlBeanContext associated with the implementation instance. - */ -public interface ControlBeanContext extends BeanContextServices -{ - /** - * Returns the public or extension interface associated with the context - */ - public Class getControlInterface(); - - /** - * Returns the current value of PropertySet for the associated control, or - * null if the property set has not been bound. Actual bindings for property - * values may be the result of annotations on the control field or class, - * property setting via factory arguments or setter APIs, or external - * configuration. - * - * @param propertySet the PropertySet to return - * @return the requested PropertySet instance, or null if not bound - * - * @see org.apache.beehive.controls.api.properties.PropertySet - */ - public T getControlPropertySet(Class propertySet); - - /** - * Returns the current value of PropertySet for the provided method, or null - * if the property set has not been bound for this method. - * - * @param m the Method to check for properties. - * @param propertySet the PropertySet to return - * @return the requested PropertySet instance, or null if not bound - * - * @see org.apache.beehive.controls.api.properties.PropertySet - */ - public T getMethodPropertySet(Method m, Class propertySet) - throws IllegalArgumentException; - - /** - * Returns the current value of PropertySet for the selected (by index) method parameter, - * or null if the property set has not been bound for this method. - * - * @param m the Method to check for properties - * @param i the index of the method parameter to check for the request PropertySet - * @param propertySet the PropertySet to return - * @return the request PropertySet instance, or null if not bound - */ - public T getParameterPropertySet(Method m, int i, Class propertySet) - throws IllegalArgumentException, IndexOutOfBoundsException; - - /** - * Returns an array containing the parameter names for the specified method - * - * @param m the Method whose parameter names should be returned. - * @return the array of parameter names (or an empty array if no parameters) - */ - public String [] getParameterNames(Method m) - throws IllegalArgumentException; - - /** - * Returns the value of a named method parameter from the input parameter array. - * - * @param m the Method associated with the input parameter list - * @param parameterName the name of the requested parameter - * @param parameters the array of method parameters - * @return the element in the input parameter array that corresponds to the requested - * parameter - */ - public Object getParameterValue(Method m, String parameterName, Object [] parameters) - throws IllegalArgumentException; - - /** - * Returns the current set of properties (in PropertyMap format) for the control - * associated with the context. The return map will contain the values for all bound - * properties for the control. - * @return the PropertyMap containing properties of the control. This map is read-only; - * any changes to it will not effect the local bean instance. - * - * @see org.apache.beehive.controls.api.properties.PropertyMap - */ - public PropertyMap getControlPropertyMap(); - - /** - * Returns an instance of a contextual service based upon the local context. If - * no provider for this service is available, then null will be returned. - * - * @param serviceClass the class of the requested service - * @param selector the service dependent parameter - * @return an instance of the request service, or null if unavailable - * - * @see java.beans.beancontext.BeanContextServices#getService - */ - public T getService(Class serviceClass, Object selector); - - /** - * Returns a ControlHandle instance that enables operations and events to be dispatched - * to the target control, if it is running inside of a container that supports external - * event dispatch. If the runtime container for the control does not support this - * functionality, a value of null will be returned. - * - * @return a ControlHandle instance for the control, or null. - * - * @see org.apache.beehive.controls.api.context.ControlHandle - */ - public ControlHandle getControlHandle(); - - /** - * Returns the PropertyMap containing default properties for an AnnotatedElement - * in the current context. - */ - public PropertyMap getAnnotationMap(AnnotatedElement annotElem); - - /** - * Returns the ClassLoader used to load the ControlBean class associated with the control - * implementation instance. This is useful for loading other classes or resources that may - * have been packaged with the public interfaces of the Control type (since they may not - * necessarily have been packaged directly with the implementation class). - */ - public java.lang.ClassLoader getClassLoader(); - - /** - * Returns true if this container guarantees single-threaded behaviour. - */ - public boolean isSingleThreadedContainer(); - - /** - * Returns the peer ControlBean associated with this ControlBeanContext. If the context - * represents a top-level container (i.e. not a Control containing other controls), null - * will be returned. - */ - public ControlBean getControlBean(); - - /** - * Returns any child ControlBean that is nested in the ControlBeanContext, or null - * if no matching child is found. The id parameter is relative to - * the current nesting context, not an absolute control id. - */ - public ControlBean getBean(String id); - - /** - * The Lifecycle event interface defines a set of lifecycle events exposed by the - * ControlBeanContext to any registered listener. - */ - @EventSet - public interface LifeCycle - { - /** - * The onCreate event is delivered when the control implementation instance for - * the associated bean has been instantiated and fully initialized. - */ - public void onCreate(); - - /** - * The onPropertyChange event is delivered when a property setter method is - * called for a bound property on the Java Control. - * - * @see org.apache.beehive.controls.api.packaging.PropertyInfo - */ - public void onPropertyChange(PropertyChangeEvent pce); - - /** - * The onVetoableChange event is delivered when a property setter method is - * called for a constrained property on the Java Control. A PropertyVetoException - * may be thrown to veto the change made by the client. - * - * @see org.apache.beehive.controls.api.packaging.PropertyInfo - */ - public void onVetoableChange(PropertyChangeEvent pce) throws PropertyVetoException; - } - - /** - * Registers a new listener for LifeCycle events on the context. - * - * @see org.apache.beehive.controls.api.context.ControlBeanContext.LifeCycle - */ - public void addLifeCycleListener(LifeCycle listener); - - /** - * Removes a currently registered LifeCycle event listener on the context. - * - * @see org.apache.beehive.controls.api.context.ControlBeanContext.LifeCycle - */ - public void removeLifeCycleListener(LifeCycle listener); -} \ No newline at end of file diff --git a/beehive-controls/src/main/java/org/apache/beehive/controls/api/context/ControlContainerContext.java b/beehive-controls/src/main/java/org/apache/beehive/controls/api/context/ControlContainerContext.java deleted file mode 100644 index 97e0d51..0000000 --- a/beehive-controls/src/main/java/org/apache/beehive/controls/api/context/ControlContainerContext.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.api.context; - -import org.apache.beehive.controls.api.bean.ControlBean; -import org.apache.beehive.controls.api.events.EventDispatcher; - -/** - * The ControlContainerContext interface defines the basic contract between an external container - * of controls and the Controls runtime. - */ -public interface ControlContainerContext extends EventDispatcher, ControlBeanContext -{ - /** - * Makes the ControlContainerContext instance the current active context. This is - * called at the beginning of the execution scope for the control container. - */ - public void beginContext(); - - /** - * Ends the active context associated with the ControlContainerContext. This is called - * at the end of the execution scope for the control container. - */ - public void endContext(); - - /** - * Returns a ControlHandle to the component containing the control. This handle can be - * used to dispatch events and operations to a control instance. This method will return - * null if the containing component does not support direct dispatch. - */ - public ControlHandle getControlHandle(ControlBean bean); -} diff --git a/beehive-controls/src/main/java/org/apache/beehive/controls/api/context/ControlHandle.java b/beehive-controls/src/main/java/org/apache/beehive/controls/api/context/ControlHandle.java deleted file mode 100644 index ec93ff6..0000000 --- a/beehive-controls/src/main/java/org/apache/beehive/controls/api/context/ControlHandle.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.api.context; - -import org.apache.beehive.controls.api.events.EventRef; -import java.lang.reflect.InvocationTargetException; - -/** - * The ControlHandle interface defines a reference object to a control instance that enables - * control events to be fired on the control. Control container implementations will provide - * implementation of this interface that use container-specific dispatch mechanisms to locate - * the appropriate control container instance when events are fired. - * - * Classes implementing the ControlHandle interface should also implement the - * java.io.Serializable interface. This will enable handles to be serialized / - * deserialized as part of event queueing or routing. - */ -public interface ControlHandle -{ - /** - * Returns the controlID of the target control referenced by this handle - */ - public String getControlID(); - - /** - * Delivers the specified event to the target control referenced by this handle. - */ - public Object sendEvent(EventRef event, Object [] args) - throws IllegalAccessException,IllegalArgumentException,InvocationTargetException; -} diff --git a/beehive-controls/src/main/java/org/apache/beehive/controls/api/context/ControlThreadContext.java b/beehive-controls/src/main/java/org/apache/beehive/controls/api/context/ControlThreadContext.java deleted file mode 100644 index 92a9c56..0000000 --- a/beehive-controls/src/main/java/org/apache/beehive/controls/api/context/ControlThreadContext.java +++ /dev/null @@ -1,82 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.api.context; - -import java.util.Stack; - -/** - * The ControlThreadContext class manages the association between ControlContainerContexts - * and threads of execution. For a given thread of execution, the beginning and ending of - * contexts will always be nested (never interleaved), so each thread will maintain its own - * stack of currently executing contexts. This can be used to reassociate with the current - * active context. - */ -public class ControlThreadContext -{ - /** - * This thread local maintains a per-thread stack of ControlContainerContext instances. - */ - private static ThreadLocal> _threadContexts = - new ThreadLocal>(); - - /** - * Returns the active ControlContainerContext for the current thread, or null if no - * context is currently active. - * @return the current active ControlContainerContext - */ - public static ControlContainerContext getContext() - { - Stack contextStack = _threadContexts.get(); - if (contextStack == null || contextStack.size() == 0) - return null; - - return contextStack.peek(); - } - - /** - * Defines the beginning of a new control container execution context. - */ - public static void beginContext(ControlContainerContext context) - { - Stack contextStack = _threadContexts.get(); - if (contextStack == null) - { - contextStack = new Stack(); - _threadContexts.set(contextStack); - } - contextStack.push(context); - } - - /** - * Ends the current control container execution context - * @throws IllegalStateException if there is not current active context or it is not - * the requested context. - */ - public static void endContext(ControlContainerContext context) - { - Stack contextStack = _threadContexts.get(); - if (contextStack == null || contextStack.size() == 0) - throw new IllegalStateException("No context started for current thread"); - - if (contextStack.peek() != context) - throw new IllegalStateException("Context is not the current active context"); - - contextStack.pop(); - } -} diff --git a/beehive-controls/src/main/java/org/apache/beehive/controls/api/context/ResourceContext.java b/beehive-controls/src/main/java/org/apache/beehive/controls/api/context/ResourceContext.java deleted file mode 100644 index a0ae1f0..0000000 --- a/beehive-controls/src/main/java/org/apache/beehive/controls/api/context/ResourceContext.java +++ /dev/null @@ -1,167 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.api.context; - -import org.apache.beehive.controls.api.events.EventSet; - -/** - * The ResourceContext interface defines a basic contextual service for coordinating the - * resource utilization of a control implementation within a resource scope defined external - * to the control. This contextual service that provides assistance to a Control in managing - * any external resources (connections, sesssions, etc) that may be relatively expensive to - * obtain and/or can only be held for a relatively short duration. - *

- * A ResourceContext implementation may be provided by an external container of Controls, such - * as a servlet engine or EJB container, that coordinates the resource lifecycle of controls with - * the activities of the external container. For example, the resource scope for a - * ResourceContext provider associated with the web tier might enable control resources to be - * used for the duration of a single http request; for the EJB tier it might mean for the - * lifetime of the current EJB invocation or active transaction. - *

- * A control implementation participates in this resource management contract by declaring a - * ResourceContext instance annotated with the - * @Context annotation, the standard service provider model of the Control runtime will - * associate the control instance with a ResourceControl provider implementation that is - * associated with the current execution context. This is demonstrated by the following - * code excerpt from a ControlImplementation class: - *

- *


- * @org.apache.beehive.controls.api.bean.ControlImplementation
- * public class MyControlImpl
- * {
- *     ...
- *     // Declare need for resource mgmt support via the ResourceContext service
- *     @org.apache.beehive.controls.api.context.Context
- *     ResourceContext resourceContext;
- *     ...
- * 
- *

- * Once the control has been associated with a ResourceContext provider, the provider will - * deliver events to the Control Implementation instance according to the following basic - * contract: - *

- *

    - *
  • the ResourceContext provider notifies a control implementation when it should acquire its - * resources using the onAcquire event. - *
  • the ResourceContext provider notifies a control implementation when it should release its - * resources using the onRelease event. - *
- *

- * The following code fragment shows how to receive resource events from within a Control - * implementation: - *

- *


- * import org.apache.beehive.controls.api.events.EventHandler;
- * 
- * ...
- *
- * @EventHandler(field="resourceContext",
- *                eventSet=ResourceContext.ResourceEvents.class,
- *                eventName="onAcquire")
- * public void onAcquire() 
- * { 
- *      // code to obtain connections/sessions/...
- * }
- * 
- * @EventHandler(field="resourceContext", 
- *                eventSet=ResourceContext.ResourceEvents.class,
- *                eventName="onRelease")
- * public void onRelease() 
- * { 
- *      // code to release connections/sessions/...
- * }
- * 
- *

- * The onAcquire resource event is guaranteed to be delivered once before any operation declared - * on a public or extension interface associated with the control. This event will be delivered - * once, and only once, within a particular resource scope associated with the ResourceContext. - * - * If a control needs to utilize its resources in another context (such as in response to a - * PropertyChange notification), the ResourceContext also provides support for manually - * acquiring and releasing resources. - * - * @see org.apache.beehive.controls.api.context.ResourceContext.ResourceEvents - * @see org.apache.beehive.controls.api.context.Context - * @see org.apache.beehive.controls.api.events.EventHandler - */ -public interface ResourceContext -{ - /** - * The acquire method allows a Control implementation to manually request acquisition. - * This is useful in contexts where the control needs access to associated resources - * from outside the scope of an operation. If invoked when the control has not currently - * acquired resources, the onAcquire event will be delivered to the control and it will - * be registered in the current resource scope as holding resources. If the control has - * previously acquired resources in the current resource scope, then calling acquire() - * will have no effect. - */ - public void acquire(); - - /** - * The release method allows a Control implement to manually release resources immediately, - * instead of waiting until the end of the current resource scope. If invoked when the - * control has currently acquired resources, the onRelease event will be delivered immediately - * and the control will no longer be in the list of controls holding resources in the current - * resource scope. If the control has not previously acquired resources, then calling - * release() will have no effect. - */ - public void release(); - - /** - * The hasResources method returns true if the control has currently acquired resources, - * false otherwise. - */ - public boolean hasResources(); - - /** - * The ResourceEvents interface defines the resource events delivered by a ResourceContext - * provider. - */ - @EventSet - public interface ResourceEvents - { - /** - * The onAcquire event will be delivered by a ResourceContext provider to the - * Control implementation before any operation on the control is invoked within - * the resource scope associated with the provider and its associated container. This - * provides the opportunity for the implementation instance to obtain any resource it - * uses to provide its services. - */ - public void onAcquire(); - - /** - * The onRelease event will be delivered by a ResourceContext provider to the - * Control implementation immediately before before the end of the resource - * scope associated with the provider and its associated container. This provides - * the opportunity for the implementation instance to relinquish any resources it - * obtained during onAcquire event handling. - */ - public void onRelease(); - } - - /** - * Registers a listener that implements the ResourceEvents interface for the ResourceContext. - */ - public void addResourceEventsListener(ResourceEvents resourceListener); - - /** - * Unregisters a listener that implements the ResourceEvents interface for the ResourceContext. - */ - public void removeResourceEventsListener(ResourceEvents resourceListener); -} diff --git a/beehive-controls/src/main/java/org/apache/beehive/controls/api/events/Client.java b/beehive-controls/src/main/java/org/apache/beehive/controls/api/events/Client.java deleted file mode 100644 index 1778181..0000000 --- a/beehive-controls/src/main/java/org/apache/beehive/controls/api/events/Client.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.api.events; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * The Client annotation type is used to mark fields in a Control implementation class - * that define client event proxies. - */ -@Retention(RetentionPolicy.RUNTIME) -@Target({ElementType.FIELD}) -public @interface Client -{ -} diff --git a/beehive-controls/src/main/java/org/apache/beehive/controls/api/events/EventDispatchHelper.java b/beehive-controls/src/main/java/org/apache/beehive/controls/api/events/EventDispatchHelper.java deleted file mode 100644 index c0c1768..0000000 --- a/beehive-controls/src/main/java/org/apache/beehive/controls/api/events/EventDispatchHelper.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.api.events; - -import java.lang.reflect.InvocationTargetException; - -import org.apache.beehive.controls.api.context.ControlContainerContext; -import org.apache.beehive.controls.api.context.ControlHandle; -import org.apache.beehive.controls.api.context.ControlThreadContext; - -/** - * The EventDispatchHelper class is a simple implementation of the EventDispatcher interface - * that is suitable for use inside the execution context of a control container. It - * assumes that you are already running inside the target container instance, and all that is - * required is the correct routing of the event to the correct control. - */ -public class EventDispatchHelper implements EventDispatcher -{ - public Object dispatchEvent(ControlHandle target, EventRef event, Object [] args) - throws IllegalAccessException, IllegalArgumentException, InvocationTargetException - { - // - // Obtain the current active control container context - // - ControlContainerContext context = ControlThreadContext.getContext(); - if (context == null) - throw new IllegalStateException("No active control container context"); - - // - // Dispatch the event using it. - // - return context.dispatchEvent(target, event, args); - } -} diff --git a/beehive-controls/src/main/java/org/apache/beehive/controls/api/events/EventDispatcher.java b/beehive-controls/src/main/java/org/apache/beehive/controls/api/events/EventDispatcher.java deleted file mode 100644 index 11f4c30..0000000 --- a/beehive-controls/src/main/java/org/apache/beehive/controls/api/events/EventDispatcher.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.api.events; - -import java.lang.reflect.InvocationTargetException; - -import org.apache.beehive.controls.api.context.ControlHandle; - -/** - * The EventDispatcher interface defines the method signature that a container supporting - * the external dispatch of Control events would implement. - */ -public interface EventDispatcher -{ - /** - * Dispatches a Control event to a target control. - * @param target the target control - * @param event the event to deliver to the control - * @param args the parameters to the control event - * @throws IllegalAccessException the underlying event method is not accessible due to - * access control. - * @throws IllegalArgumentException the target is not valid, the event is not a valid event - * type for the requested target, or the argument types do not match the event - * signature. - * @throws InvocationTargetException wraps any exception thrown by the underlying event - * handler. - */ - public Object dispatchEvent(ControlHandle target, EventRef event, Object [] args) - throws IllegalAccessException, IllegalArgumentException, - InvocationTargetException; -} diff --git a/beehive-controls/src/main/java/org/apache/beehive/controls/api/events/EventDispatcherRemote.java b/beehive-controls/src/main/java/org/apache/beehive/controls/api/events/EventDispatcherRemote.java deleted file mode 100644 index 0d60258..0000000 --- a/beehive-controls/src/main/java/org/apache/beehive/controls/api/events/EventDispatcherRemote.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.api.events; - -import java.rmi.RemoteException; - -import org.apache.beehive.controls.api.context.ControlHandle; - -/** - * The EventDispatcherRemote interface defines the event dispatch signature when event - * dispatching is happening via RMI. - * - * @see org.apache.beehive.controls.api.events.EventDispatcher - */ -public interface EventDispatcherRemote -{ - /** - * Dispatches a Control event to a target control. - * @param target the target control - * @param event the event to deliver to the control - * @param args the parameters to the control event - * @throws RemoteException wraps any exception thrown during event dispatch - */ - public Object dispatchEvent(ControlHandle target, EventRef event, Object [] args) - throws RemoteException; -} diff --git a/beehive-controls/src/main/java/org/apache/beehive/controls/api/events/EventHandler.java b/beehive-controls/src/main/java/org/apache/beehive/controls/api/events/EventHandler.java deleted file mode 100644 index e4ed3a6..0000000 --- a/beehive-controls/src/main/java/org/apache/beehive/controls/api/events/EventHandler.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.api.events; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * The EventHandler annotation type is used to mark a method that provides the event handler - * implementation for a Control event. - */ -@Retention(RetentionPolicy.RUNTIME) -@Target({ElementType.METHOD}) -public @interface EventHandler -{ - /** - * The field name of the Java control event source. This must be an @Control field declared - * on the class defining the event handler method (or on a superclass if the field is not - * declared to be private). - */ - String field(); - - /** - * The EventSet interface that declares the event. This must be a valid EventSet interface - * associated with the control type of the field member. - */ - Class eventSet(); - - /** - * The name of the handled event. This must be the name of a method declared on the EventSet - * interface referenced by the eventSet member. The annotated method must have - * an event signature that exactly matches one of the event methods with this name. - */ - String eventName(); -} diff --git a/beehive-controls/src/main/java/org/apache/beehive/controls/api/events/EventRef.java b/beehive-controls/src/main/java/org/apache/beehive/controls/api/events/EventRef.java deleted file mode 100644 index 55742ce..0000000 --- a/beehive-controls/src/main/java/org/apache/beehive/controls/api/events/EventRef.java +++ /dev/null @@ -1,255 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.api.events; - -import java.lang.reflect.Method; -import java.util.HashMap; -import java.util.WeakHashMap; - -/** - * The EventRef class represents a reference to a specific Control event. EventRefs can - * be used to fire external events into a Control, in contexts where the event source may - * not share the associated EventSet class instance with the event target, or even have - * access to the EventSet class itself. - *

- * It is roughly equivalent to the java.lang.reflect.Method object that refers to a method - * on an EventSet interface, but has several additional properties: - *

    - *
  • It is serializable, so can be persisted/restored or passed across the wire
  • - *
  • It supports materializing the EventRef back to a Method reference in a way that allows - * EventRefs to be passed across class loaders
  • - *
  • It can be constructed in contexts where a reference to the actual EventSet class might - * not be available (using a String event descriptor format to describe events)
  • - *
- */ -public class EventRef implements java.io.Serializable -{ - // - // Static helper map to go from a primitive type to the type descriptor string - // - static private HashMap _primToType = new HashMap(); - static - { - _primToType.put(Integer.TYPE, "I"); - _primToType.put(Boolean.TYPE, "Z"); - _primToType.put(Byte.TYPE, "B"); - _primToType.put(Character.TYPE, "C"); - _primToType.put(Short.TYPE, "S"); - _primToType.put(Long.TYPE, "J"); - _primToType.put(Float.TYPE, "F"); - _primToType.put(Double.TYPE, "D"); - _primToType.put(Void.TYPE, "V"); - } - - /** - * Constructs a new EventRef based upon a Method reference. The input method must be one - * that is declared within a Control EventSet interface. - * @param eventMethod the Method associated with the event - */ - public EventRef(Method eventMethod) - { - _method = eventMethod; - _descriptor = computeEventDescriptor(eventMethod); - } - - /** - * Constructs a new EventRef using an event descriptor string. The format of this string - * is: - *
 
-     *      .
-     * 
- * where eventSet refers to the fully qualified name of the EventSet class, - * eventName refers to the name of the event Method, and eventDescriptor - * describes the event argument and return types using the method descriptor format - * defined in the Java Language Specification. - *

- * For example, given the following EventSet interface: - *

-     * @ControlInterface
-     * public interface MyControl
-     * {
-     *     @EventSet
-     *     public interface MyEvents
-     *     {
-     *          public String myEvent(int arg0, Object arg2);
-     *     }
-     * }
-     * 
- * the eventDescriptor for myEvent would be: - *
 
-     *     MyControl.MyEvents.myEvent(ILjava/lang/Object;)Ljava/lang/String;
-     * 
- * @param eventDescriptor the event descriptor string associated with the event - */ - public EventRef(String eventDescriptor) - { - _descriptor = eventDescriptor; - } - - /** - * Returns the event descriptor string associated with the EventRef. - * @param controlInterface the ControlInterface - */ - public String getEventDescriptor(Class controlInterface) - { - // - // NOTE: The input controlInterface is currently unused, but included to - // enable downstream optimization of serialization representation. See the - // OPTIMIZE comment below for more details. If implemented, the interface - // is needed to reverse the transformation from a hash back to a method or - // descriptor. - // - if (_descriptor == null) - _descriptor = computeEventDescriptor(_method); - - return _descriptor; - } - - /** - * Helper method that computes the event descriptor sting for a method - */ - private String computeEventDescriptor(Method method) - { - StringBuilder sb = new StringBuilder(); - - // Add event class and method name - sb.append(method.getDeclaringClass().getName()); - sb.append("."); - sb.append(method.getName()); - - // Add event arguments - Class [] parms = method.getParameterTypes(); - sb.append("("); - for (int i = 0; i < parms.length; i++) - appendTypeDescriptor(sb, parms[i]); - sb.append(")"); - - // Add event return type - appendTypeDescriptor(sb, method.getReturnType()); - - return sb.toString(); - } - - /** - * Helper method that appends a type descriptor to a StringBuilder. Used - * while accumulating an event descriptor string. - */ - private void appendTypeDescriptor(StringBuilder sb, Class clazz) - { - if (clazz.isPrimitive()) - sb.append(_primToType.get(clazz)); - else if (clazz.isArray()) - sb.append(clazz.getName().replace('.','/')); - else - { - sb.append("L"); - sb.append(clazz.getName().replace('.','/')); - sb.append(";"); - } - } - - /** - * Returns the event Method associated with this EventRef. - */ - public Method getEventMethod(Class controlInterface) - { - // - // If we already hold a method reference and its loader matches up with the input - // interface, then just return it. - // - if (_method != null && - _method.getDeclaringClass().getClassLoader().equals(controlInterface.getClassLoader())) - return _method; - - // - // Otherwise, obtain the mapping from descriptors to methods, and use it to - // convert back to a method. - // - String eventDescriptor = getEventDescriptor(controlInterface); - HashMap descriptorMap = getDescriptorMap(controlInterface); - if (!descriptorMap.containsKey(eventDescriptor)) - { - throw new IllegalArgumentException("Control interface " + controlInterface + - " does not contain an event method that " + - " corresponds to " + eventDescriptor); - } - return descriptorMap.get(eventDescriptor); - } - - /** - * A WeakHashMap used to cache the event descriptor-to-Method mapping for control - * interfaces. - */ - static private WeakHashMap> _descriptorMaps = - new WeakHashMap>(); - - private HashMap getDescriptorMap(Class controlInterface) - { - // - // If the local cache has the mapping, then return it. - // - HashMap descMap = _descriptorMaps.get(controlInterface); - if (descMap == null) - { - // - // Compute the mapping from event descriptors to event methods, using reflection - // - descMap = new HashMap(); - Class [] innerClasses = controlInterface.getClasses(); - for (int i = 0; i < innerClasses.length; i++) - { - if (!innerClasses[i].isInterface() || - !innerClasses[i].isAnnotationPresent(EventSet.class)) - continue; - - Method [] eventMethods = innerClasses[i].getMethods(); - for (int j = 0; j < eventMethods.length; j++) - descMap.put(computeEventDescriptor(eventMethods[j]), eventMethods[j]); - } - _descriptorMaps.put(controlInterface, descMap); - } - return descMap; - } - - - /** - * Two EventRefs are equal if the method descriptor string associated with them is equal - */ - public boolean equals(Object obj) - { - if (obj == null || !(obj instanceof EventRef)) - return false; - - return _descriptor.equals(((EventRef)obj)._descriptor); - } - - public String toString() - { - return "EventRef: " + _descriptor; - } - - // - // OPTIMIZE: A more efficient internal representation for serialization/wire purposes - // would be to compute a hash of the descriptor string (ala RMI opnums), that could be - // reconstituted on the other end, given a candidate ControlInterface. The public APIs - // are structured to support this downstream optimization. - // - private String _descriptor; - transient private Method _method; -} diff --git a/beehive-controls/src/main/java/org/apache/beehive/controls/api/events/EventSet.java b/beehive-controls/src/main/java/org/apache/beehive/controls/api/events/EventSet.java deleted file mode 100644 index e66988e..0000000 --- a/beehive-controls/src/main/java/org/apache/beehive/controls/api/events/EventSet.java +++ /dev/null @@ -1,80 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.api.events; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * The EventSet annotation type is used to mark an interface that defines a group of events - * associated with a Java Control. By convention, event interfaces are defined as inner - * classes on the Java Control public interface. Each method defined within a - * event interface indicates an event that can be delivered by the control. - *

- * Here is a simple example: - *

- * public interface MyControl extends org.apache.beehive.controls.api.Control
- * {
- *     @EventSet
- *     public interface MyEvents
- *     {
- *         public void anEvent();
- *     }
- *
- *     ...
- * }
- * 
- * This will declare an event interface named MyEvents that declares a single - * event: anEvent - * - * The declaration of an EventSet for a control also means that the associated Control - * JavaBean will have listener registration/deregistration APIs. The name of these - * APIs will be add/removeListener, and the argument will be an - * listener instance that implements the EventSet interface. - *

- * The above example would result in the following APIs on MyControlBean - * - *

- * public class MyControlBean implements MyControl
- * {
- *     ...
- *     public void addMyEventsListener(MyEvents listener) { ... }
- *     public void removeMyEventsListener(MyEvents listener) { ... }
- * 
- */ -@Retention(RetentionPolicy.RUNTIME) -@Target({ElementType.TYPE}) -public @interface EventSet -{ - /** - * Defines whether the events defined by the interface are unicast events. A unicast - * event set may have only a single listener registered to receive events for any - * given bean instance. Any attempt to register additional listeners will result in - * a java.util.TooManyListenersException being thrown by the event - * listener registration method. - *

- * If an event set provides multicast support (the default), then it may only declare - * event methods that have a void return type. Unicast event sets may - * support event return values, that will be provided by the (single) registered - * listener. - */ - public boolean unicast() default false; -} diff --git a/beehive-controls/src/main/java/org/apache/beehive/controls/api/events/RemoteEventDispatcher.java b/beehive-controls/src/main/java/org/apache/beehive/controls/api/events/RemoteEventDispatcher.java deleted file mode 100644 index 26b1cc4..0000000 --- a/beehive-controls/src/main/java/org/apache/beehive/controls/api/events/RemoteEventDispatcher.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.api.events; - -import java.rmi.RemoteException; - -import org.apache.beehive.controls.api.context.ControlHandle; - -/** - * The RemoteEventDispatcher interface defines the method signature that a container supporting - * the external dispatch of Control events would implement if events can be dispatched using RMI. - */ -public interface RemoteEventDispatcher -{ - /** - * Dispatches a Control event to a target control. - * @param target the target control - * @param event the event to deliver to the control - * @param args the parameters to the control event - * @throws IllegalAccessException the underlying event method is not accessible due to - * access control. - * @throws IllegalArgumentException the target is not valid, the event is not a valid event - * type for the requested target, or the argument types do not match the event - * signature. - * @throws InvocationTargetException wraps any exception thrown by the underlying event - * handler. - */ - public Object dispatchEvent(ControlHandle target, EventRef event, Object [] args) - throws RemoteException; -} diff --git a/beehive-controls/src/main/java/org/apache/beehive/controls/api/packaging/BeanInfo.java b/beehive-controls/src/main/java/org/apache/beehive/controls/api/packaging/BeanInfo.java deleted file mode 100644 index 31aa7d9..0000000 --- a/beehive-controls/src/main/java/org/apache/beehive/controls/api/packaging/BeanInfo.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.api.packaging; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Target; - -/** - * The FeatureInfo annotation type defines a JSR-175 syntax for annotating a Control to - * provide BeanInfo FeatureDescriptor information for the bean, its properties, methods, - * or events. - *

- * The elements of FeatureInfo correspond 1-to-1 with the information exposed by the - * java.beans.FeatureDescriptor class. - * - * @see java.beans.FeatureDescriptor - */ -@Target({ElementType.TYPE, ElementType.METHOD}) -public @interface BeanInfo -{ - /** - * The NoCustomizer class can be used as the value of the customizerClass attribute to - * indicate that the bean has no customizer. - */ - static public class NoCustomizer {} - - public Class customizerClass() default NoCustomizer.class; -} diff --git a/beehive-controls/src/main/java/org/apache/beehive/controls/api/packaging/EventSetInfo.java b/beehive-controls/src/main/java/org/apache/beehive/controls/api/packaging/EventSetInfo.java deleted file mode 100644 index d6f0dd2..0000000 --- a/beehive-controls/src/main/java/org/apache/beehive/controls/api/packaging/EventSetInfo.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.api.packaging; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Target; - -/** - * The EventSetInfo annotation type defines a JSR-175 syntax for annotating a Control - * property declaration to provide java.beans.EventSetDescriptor information. Generic - * feature information is defined using the FeatureInfo annotation type - *

- * The elements of EventStInfo correspond 1-to-1 with the information exposed by the - * java.beans.EventSetDescriptor class. - * - * @see java.beans.EventSetDescriptor - */ -@Target({ElementType.TYPE}) // appears on EventSet interface declaration -public @interface EventSetInfo -{ - public boolean isUnicast() default false; // single listener model - public boolean isDefault() default true; // is the default event set -} diff --git a/beehive-controls/src/main/java/org/apache/beehive/controls/api/packaging/FeatureAttribute.java b/beehive-controls/src/main/java/org/apache/beehive/controls/api/packaging/FeatureAttribute.java deleted file mode 100644 index 3f8ae75..0000000 --- a/beehive-controls/src/main/java/org/apache/beehive/controls/api/packaging/FeatureAttribute.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.api.packaging; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Target; - -/** - * The FeatureAttribute annotation type defines a JSR-175 syntax for specifying JavaBean - * FeatureDescriptor attributes associated with a Control. - * - * @see org.apache.beehive.controls.api.packaging.FeatureInfo - */ -public @interface FeatureAttribute -{ - /* Specifies the feature attribute name */ - public String name(); - - /* Specifies the feature attribute value */ - public String value(); -} diff --git a/beehive-controls/src/main/java/org/apache/beehive/controls/api/packaging/FeatureInfo.java b/beehive-controls/src/main/java/org/apache/beehive/controls/api/packaging/FeatureInfo.java deleted file mode 100644 index b9719cc..0000000 --- a/beehive-controls/src/main/java/org/apache/beehive/controls/api/packaging/FeatureInfo.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.api.packaging; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Target; - -/** - * The FeatureInfo annotation type defines a JSR-175 syntax for annotating a Control to - * provide BeanInfo FeatureDescriptor information for the bean, its properties, methods, - * or events. - *

- * The elements of FeatureInfo correspond 1-to-1 with the information exposed by the - * java.beans.FeatureDescriptor class. - * - * @see java.beans.FeatureDescriptor - */ -@Target({ElementType.TYPE, ElementType.METHOD}) -public @interface FeatureInfo -{ - public String displayName() default ""; // default: use reflection name - public String name() default ""; // default: use reflection name - public String shortDescription() default ""; - public boolean isExpert() default false; - public boolean isHidden() default false; - public boolean isPreferred() default false; - public FeatureAttribute [] attributes() default {}; -} diff --git a/beehive-controls/src/main/java/org/apache/beehive/controls/api/packaging/ManifestAttribute.java b/beehive-controls/src/main/java/org/apache/beehive/controls/api/packaging/ManifestAttribute.java deleted file mode 100644 index 7616877..0000000 --- a/beehive-controls/src/main/java/org/apache/beehive/controls/api/packaging/ManifestAttribute.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.api.packaging; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Target; - -/** - * The ManifestAttribute annotation type defines a JSR-175 syntax for specifying JAR - * manifest attributes associated with a control type. The Beehive Controls packaging - * support will process these annotation during the construction of a JAR file that - * contains Controls. - */ -@Target({ElementType.TYPE}) -public @interface ManifestAttribute -{ - /* Specifies the manifest attribute name */ - public String name(); - - /* Specifies the manifest attribute value */ - public String value(); -} diff --git a/beehive-controls/src/main/java/org/apache/beehive/controls/api/packaging/ManifestAttributes.java b/beehive-controls/src/main/java/org/apache/beehive/controls/api/packaging/ManifestAttributes.java deleted file mode 100644 index 5832209..0000000 --- a/beehive-controls/src/main/java/org/apache/beehive/controls/api/packaging/ManifestAttributes.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.api.packaging; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Target; - -/** - * The ManifestAttributes annotation type enables a set of manifest attributes attributes - * to be defined for a given control type. - * - * @see org.apache.beehive.controls.api.packaging.ManifestAttribute - */ -@Target({ElementType.TYPE}) -public @interface ManifestAttributes -{ - /* Specifies the set of ManifestAttribute annotation values */ - public ManifestAttribute [] value(); -} diff --git a/beehive-controls/src/main/java/org/apache/beehive/controls/api/packaging/PropertyInfo.java b/beehive-controls/src/main/java/org/apache/beehive/controls/api/packaging/PropertyInfo.java deleted file mode 100644 index 7c14a4c..0000000 --- a/beehive-controls/src/main/java/org/apache/beehive/controls/api/packaging/PropertyInfo.java +++ /dev/null @@ -1,49 +0,0 @@ -package org.apache.beehive.controls.api.packaging; - -/* - * 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. - * - * $Header:$ - */ - -import java.lang.annotation.ElementType; -import java.lang.annotation.Target; - -import java.beans.PropertyEditor; - -/** - * The PropertyInfo annotation type defines a JSR-175 syntax for annotating a Control - * property declaration to provide java.beans.PropertyDescriptor information. Generic - * feature information is defined using the FeatureInfo annotation type - *

- * The elements of PropertyInfo correspond 1-to-1 with the information exposed by the - * java.beans.PropertyDescriptor class. - * - * @see java.beans.PropertyDescriptor - */ -@Target({ElementType.METHOD}) // appears on PropertySet method declaration (i.e. properties) -public @interface PropertyInfo -{ - /** - * The NoEditor class can be used as the value of the editorClass attribute to - * indicate that the property has no editor - */ - static public class NoEditor {}; - - public boolean bound() default false; // Sends PropertyChange events - public boolean constrained() default false; // Sends VetoableChange events - public Class editorClass() default NoEditor.class; // default == no editor -} diff --git a/beehive-controls/src/main/java/org/apache/beehive/controls/api/properties/AnnotatedElementMap.java b/beehive-controls/src/main/java/org/apache/beehive/controls/api/properties/AnnotatedElementMap.java deleted file mode 100644 index 3cad6ca..0000000 --- a/beehive-controls/src/main/java/org/apache/beehive/controls/api/properties/AnnotatedElementMap.java +++ /dev/null @@ -1,292 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.api.properties; - -import java.io.IOException; -import java.lang.annotation.Annotation; -import java.lang.annotation.Inherited; -import java.lang.reflect.AnnotatedElement; -import java.lang.reflect.Field; -import java.lang.reflect.Method; - -import org.apache.beehive.controls.api.bean.ControlBean; -import org.apache.beehive.controls.api.bean.ControlExtension; -import org.apache.beehive.controls.api.bean.ControlInterface; - -/** - * The AnnotatedElementMap represents a read-only PropertyMap where property values are - * derived from Java 5.0 (JSR-175) annotations. - */ -public class AnnotatedElementMap - extends BaseMap - implements PropertyMap,java.io.Serializable -{ - /** - * Creates a new PropertyMap that is initialized based upon the type and annotations - * associated with an AnnotatedElement. - */ - public AnnotatedElementMap(AnnotatedElement annotElem) - { - if (annotElem instanceof Class) - setMapClass((Class)annotElem); - else if (annotElem instanceof Field) - setMapClass(((Field)annotElem).getType()); - else if (annotElem instanceof Method) - { - Class mapClass = getMethodMapClass((Method)annotElem); - setMapClass(mapClass); - } - else - throw new IllegalArgumentException("Unsupported element type: " + annotElem.getClass()); - - _annotElem = annotElem; - } - - // For methods, make sure we find a declaring class that is a valid - // map class. For extended callback methods, we need to walk up a bit - // further in the hierarchy. - - Class getMethodMapClass(Method method) { - - Class origMapClass = method.getDeclaringClass(); - Class mapClass = origMapClass; - while (mapClass != null && !isValidMapClass(mapClass)) { - mapClass = mapClass.getDeclaringClass(); - } - if (mapClass == null) { - mapClass = origMapClass; - } - return mapClass; - } - - boolean isValidMapClass(Class mapClass) { - if (ControlBean.class.isAssignableFrom(mapClass)) - { - return true; - } - else - { - if (mapClass.isAnnotation() || - mapClass.isAnnotationPresent(ControlInterface.class) || - mapClass.isAnnotationPresent(ControlExtension.class)) { - return true; - } - } - return false; - } - - /** - * Sets the property specifed by 'key' within this map. - */ - public void setProperty(PropertyKey key, Object value) - { - throw new IllegalStateException("AnnotatedElementMap is a read-only PropertyMap"); - } - - /** - * Returns the property value specified by 'key' within this map. - */ - public Object getProperty(PropertyKey key) - { - if (!isValidKey(key)) - throw new IllegalArgumentException("Key " + key + " is not valid for " + _mapClass); - - - // - // Look for the property value on the associated annotated element - // - Class propertySet = key.getPropertySet(); - Annotation annot = _annotElem.getAnnotation(propertySet); - if (annot != null) - return key.extractValue(annot); - - // - // If the property supports inheritance and the annotated element is an interface, - // then we'll search up the ControlInheritance/Extension hierachy to see if it is - // provided higher up the chain. - // - if (propertySet.isAnnotationPresent(Inherited.class) && _annotElem instanceof Class) - { - Class controlIntf = (Class)_annotElem; - do - { - Class [] superIntfs = controlIntf.getInterfaces(); - controlIntf = null; - for (int i = 0; i < superIntfs.length; i++) - { - if (superIntfs[i].isAnnotationPresent(ControlInterface.class) || - superIntfs[i].isAnnotationPresent(ControlExtension.class)) - { - controlIntf = superIntfs[i]; - annot = controlIntf.getAnnotation(propertySet); - if (annot != null) - return key.extractValue(annot); - } - } - - } - while (controlIntf != null); - } - - // - // Call up to superclass for delegation / default value - // - return super.getProperty(key); - } - - /** - * Returns true if the PropertyMap contains one or more values for the specified - * PropertySet, false otherwise - */ - public boolean containsPropertySet(Class propertySet) - { - if (_annotElem.isAnnotationPresent(propertySet)) - return true; - - // - // Call up to superclass for delegation - // - return super.containsPropertySet(propertySet); - } - - /** - * Returns the AnnotatedElement used for PropertyMap values. - */ - public AnnotatedElement getAnnotatedElement() - { - return _annotElem; - } - - /** - * Returns a String version of method argument lists based upon the method argument types - */ - private String getMethodArgs(Method m) - { - StringBuffer sb = new StringBuffer(); - Class [] argTypes = m.getParameterTypes(); - for (int i = 0; i < argTypes.length; i++) - { - if (i != 0) sb.append(","); - sb.append(argTypes[i].toString()); - } - return sb.toString(); - } - - /** - * Overrides the standard Serialization writeObject method to compute and store the element - * information in a serializable form. - */ - private void writeObject(java.io.ObjectOutputStream out) throws IOException - { - // - // When serializing, compute sufficient information about the annotated element to - // allow it to be reassociated later in readObject - // - if (_annotElem instanceof Class) - { - _elemClass = (Class)_annotElem; - _elemDesc = null; // non required - } - else if (_annotElem instanceof Field) - { - Field f = (Field)_annotElem; - _elemClass = f.getDeclaringClass(); - _elemDesc = f.getName(); - } - else if (_annotElem instanceof Method) - { - Method m = (Method)_annotElem; - _elemClass = m.getDeclaringClass(); - _elemDesc = m.getName() + "(" + getMethodArgs(m) + ")"; - } - - out.defaultWriteObject(); - } - - /** - * Overrides the standard Serialization readObject implementation to reassociated with the - * target AnnotatedElement after deserialization. - */ - private void readObject(java.io.ObjectInputStream in) - throws IOException, ClassNotFoundException - { - in.defaultReadObject(); - - if (_elemDesc == null) // element is a Class - _annotElem = _elemClass; - else - { - int argsIndex = _elemDesc.indexOf('('); - if (argsIndex < 0) // element is a Field - { - try - { - _annotElem = _elemClass.getDeclaredField(_elemDesc); - } - catch (NoSuchFieldException nsfe) - { - throw new IOException("Unable to locate field " + nsfe); - } - } - else // element is a method - { - String methodName = _elemDesc.substring(0, argsIndex); - if (_elemDesc.charAt(argsIndex+1) == ')') - { - // At least handle the null args case quickly - try - { - _annotElem = _elemClass.getDeclaredMethod(methodName, new Class [] {}); - } - catch (NoSuchMethodException nsme) - { - throw new IOException("Unable to locate method " +_elemDesc); - } - } - else - { - // Linear search for the rest :( - String methodArgs = _elemDesc.substring(argsIndex+1, _elemDesc.length()-1); - Method [] methods = _elemClass.getDeclaredMethods(); - for (int i = 0; i < methods.length; i++) - { - if (methods[i].getName().equals(methodName) && - getMethodArgs(methods[i]).equals(methodArgs)) - { - _annotElem = methods[i]; - break; - } - } - - if (_annotElem == null) - { - throw new IOException("Unable to locate method " + _elemDesc); - } - } - } - } - } - - // The AnnotatedElement upon which this PropertyMap is based. This is marked transient, - // because many Reflection types are not Serializable. - transient private AnnotatedElement _annotElem; - - private Class _elemClass; // Class associated with the annotated element - private String _elemDesc; // Description of the element -} diff --git a/beehive-controls/src/main/java/org/apache/beehive/controls/api/properties/BaseMap.java b/beehive-controls/src/main/java/org/apache/beehive/controls/api/properties/BaseMap.java deleted file mode 100644 index db0c6c0..0000000 --- a/beehive-controls/src/main/java/org/apache/beehive/controls/api/properties/BaseMap.java +++ /dev/null @@ -1,217 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.api.properties; - -import java.lang.annotation.Annotation; - -import org.apache.beehive.controls.api.bean.ControlBean; -import org.apache.beehive.controls.api.bean.ControlExtension; -import org.apache.beehive.controls.api.bean.ControlInterface; -import org.apache.beehive.controls.api.bean.ExternalPropertySets; - -/** - * The BaseMap class provide an abstract base PropertyMap class from which other - * concrete PropertyMap implementation can derive. It contains some common code - * (such as property key validation and the implementation of the base delegation model) - * that is generically useful. - */ -abstract public class BaseMap implements PropertyMap, java.io.Serializable -{ - /** - * Sets the PropertySet or Control interface associated with this map. Only properties - * declared by the PropertySet or one of the PropertySets on the Control interface may - * be used with this map. - */ - protected void setMapClass(Class mapClass) - { - // - // If the provided map class is a ControlBean type, then locate associated control - // interface or extension that defines properties. - // - if (ControlBean.class.isAssignableFrom(mapClass)) - { - Class [] intfs = mapClass.getInterfaces(); - for (int i = 0; i < intfs.length; i++) - { - if (intfs[i].isAnnotationPresent(ControlInterface.class) || - intfs[i].isAnnotationPresent(ControlExtension.class)) - { - mapClass = intfs[i]; - break; - } - } - } - else - { - if (!mapClass.isAnnotation() && - !mapClass.isAnnotationPresent(ControlInterface.class) && - !mapClass.isAnnotationPresent(ControlExtension.class)) - throw new IllegalArgumentException(mapClass+" must be Control or annotation type"); - } - - _mapClass = mapClass; - } - - /** - * Returns the PropertySet or Control interface class associated with the PropertyMap. - */ - public Class getMapClass() { return _mapClass; } - - /** - * Checks to see if the provided class is a control or property set interface that is - * compatible with the local PropertyMap. - */ - private boolean isCompatibleClass(Class checkClass) - { - // - // If the check class is equal to or a super-interface of the map class, then - // they are compatible. - // - if (_mapClass.isAssignableFrom(checkClass)) - return true; - - // - // If the check class is a property set declared by the map class or a super interface - // of the map class, then they are compatible. - // - if (checkClass.isAnnotationPresent(PropertySet.class)) - { - Class declaringClass = checkClass.getDeclaringClass(); - - // External property sets are always compatible. - // TODO: Could do a more extensive check.. - if (declaringClass == null) - return true; - - if (declaringClass.isAssignableFrom(_mapClass)) - return true; - } - - // - // If the map class is a property set declared by the check class or a super interface - // of the check class, then they are compatible. This is the inverse of the last check, - // and happens e.g. when a programatically instantiated control w/ an initial property - // map needs to delegate to the control interface's property map. - // - if (_mapClass.isAnnotationPresent(PropertySet.class)) - { - Class declaringClass = _mapClass.getDeclaringClass(); - if (declaringClass != null && - declaringClass.isAssignableFrom(checkClass)) - return true; - - // External property sets have no declaring class - if (declaringClass == null) - { - ExternalPropertySets eps = (ExternalPropertySets) checkClass.getAnnotation(ExternalPropertySets.class); - if (eps != null) - { - Class[] propSets = eps.value(); - if (propSets != null) - { - for (Class ps : propSets) - { - if (_mapClass.equals(ps)) - return true; - } - } - } - } - } - - return false; - } - - /** - * Checks to ensure that the provided key is a valid key for this PropertyMap - */ - protected boolean isValidKey(PropertyKey key) - { - return isCompatibleClass(key.getPropertySet()); - } - - /** - * Sets a delegate base property map from which values will be derived if not found within - * the local property map. - */ - public synchronized void setDelegateMap(PropertyMap delegateMap) - { - if (!isCompatibleClass(delegateMap.getMapClass())) - throw new IllegalArgumentException("The delegate map type (" + delegateMap.getMapClass() + " is an incompatible type with " + _mapClass); - - _delegateMap = delegateMap; - } - - /** - * Returns a delegate base property map from which values will be derived if not found within - * the local property map. - */ - public PropertyMap getDelegateMap() - { - return _delegateMap; - } - - /** - * Returns the property value specified by 'key' within this map. - */ - public Object getProperty(PropertyKey key) - { - // - // Delegate up to any parent map - // - if (_delegateMap != null) - return _delegateMap.getProperty(key); - - // - // If neither found a value, return the default value - // - return key.getDefaultValue(); - } - - /** - * Returns true if the PropertyMap contains one or more values for the specified - * PropertySet, false otherwise. - */ - public boolean containsPropertySet(Class propertySet) - { - // - // Defer to any delegate map - // - if (_delegateMap != null) - return _delegateMap.containsPropertySet(propertySet); - - return false; - } - - /** - * Returns a PropertySet proxy instance that derives its data from the contents of - * the property map. Will return null if the PropertyMap does not contain any properties - * associated with the specified PropertySet. - */ - public T getPropertySet(Class propertySet) - { - if (!containsPropertySet(propertySet)) - return null; - - return PropertySetProxy.getProxy(propertySet, this); - } - - Class _mapClass; // associated Control or PropertySet class - PropertyMap _delegateMap; // wrapped PropertyMap (or null) -} diff --git a/beehive-controls/src/main/java/org/apache/beehive/controls/api/properties/BaseProperties.java b/beehive-controls/src/main/java/org/apache/beehive/controls/api/properties/BaseProperties.java deleted file mode 100644 index 3dd9a70..0000000 --- a/beehive-controls/src/main/java/org/apache/beehive/controls/api/properties/BaseProperties.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.api.properties; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Target; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; - -/** - * Base properties that are present intrinsically on all controls. - */ -@PropertySet -@Target( {ElementType.TYPE, ElementType.FIELD} ) -@Retention( RetentionPolicy.RUNTIME ) -public @interface BaseProperties -{ - /** - * Fully qualified classname of the implementation class for the control. If null, - * the default algorithm for * determining the implementation class will be used -- - * basically, adding "Impl" to the control interface name. - */ - String controlImplementation() default ""; -} diff --git a/beehive-controls/src/main/java/org/apache/beehive/controls/api/properties/BeanPropertyMap.java b/beehive-controls/src/main/java/org/apache/beehive/controls/api/properties/BeanPropertyMap.java deleted file mode 100644 index 6d88e5c..0000000 --- a/beehive-controls/src/main/java/org/apache/beehive/controls/api/properties/BeanPropertyMap.java +++ /dev/null @@ -1,186 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.api.properties; - -import java.lang.annotation.Annotation; -import java.lang.reflect.Proxy; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Set; - -/** - * The BeanPropertyMap class represents a collection of property values where properties are - * stored in a local HashMap. - */ -public class BeanPropertyMap extends BaseMap implements PropertyMap,java.io.Serializable -{ - private static final HashMap _primToObject = new HashMap(); - - static - { - _primToObject.put(Integer.TYPE, Integer.class); - _primToObject.put(Long.TYPE, Long.class); - _primToObject.put(Short.TYPE, Short.class); - _primToObject.put(Byte.TYPE, Byte.class); - _primToObject.put(Float.TYPE, Float.class); - _primToObject.put(Double.TYPE, Double.class); - _primToObject.put(Character.TYPE, Character.class); - _primToObject.put(Boolean.TYPE, Boolean.class); - } - - /** - * Creates an empty BeanPropertyMap associated with the specific Control public - * interface, PropertySet, or annotation type. - */ - public BeanPropertyMap(Class mapClass) - { - setMapClass(mapClass); - } - - /** - * Creates a BeanPropertyMap that wraps another PropertyMap. Any changes via setProperty - * will be maintained locally on the constructed map, but getProperty will delegate to the - * base PropertyMap for properties not set locally. - */ - public BeanPropertyMap(PropertyMap map) - { - setMapClass(map.getMapClass()); - setDelegateMap(map); - } - - /** - * Creates a BeanPropertyMap where default values are derived from a single annotation - * type instance. This can be used to create a map from a property getter return value, - * to modify element values. - */ - public BeanPropertyMap(T annot) - { - // If the annotation value is actually a PropertySetProxy, then unwrap it and use - // the standard delegation model - try - { - Object handler = Proxy.getInvocationHandler(annot); - if (handler instanceof PropertySetProxy) - { - PropertySetProxy psp = (PropertySetProxy)handler; - setMapClass(psp.getPropertySet()); - setDelegateMap(psp.getPropertyMap()); - return; - } - } - catch (IllegalArgumentException iae) {} // regular annotation - - _annot = annot; - setMapClass(annot.getClass()); - } - - /** - * Sets the property specifed by 'key' within this map. - */ - public synchronized void setProperty(PropertyKey key, Object value) - { - if (!isValidKey(key)) - throw new IllegalArgumentException("Key " + key + " is not valid for " + getMapClass()); - - // - // Validate the value argument, based upon the property type reference by the key - // - Class propType = key.getPropertyType(); - if (value == null) - { - if (propType.isPrimitive() || propType.isAnnotation()) - throw new IllegalArgumentException("Invalid null value for key " + key); - } - else - { - if (propType.isPrimitive()) - propType = (Class)_primToObject.get(propType); - - if (!propType.isAssignableFrom(value.getClass())) - { - throw new IllegalArgumentException("Value class (" + value.getClass() + - ") not of expected type: " + propType); - } - } - _properties.put(key, value); - _propertySets.add(key.getPropertySet()); - } - - /** - * Returns the property value specified by 'key' within this map. - */ - public Object getProperty(PropertyKey key) - { - if (!isValidKey(key)) - throw new IllegalArgumentException("Key " + key + " is not valid for " + getMapClass()); - - // - // Check local properties first - // - if (_properties.containsKey(key)) - return _properties.get(key); - - // - // Return the value of the annotation type instance (if any) - // - if (_annot != null) - return key.extractValue(_annot); - - // - // Call up to superclass, for delegation model / default value - // - return super.getProperty(key); - } - - /** - * Returns true if the PropertyMap contains one or more values for the specified - * PropertySet, false otherwise - */ - public boolean containsPropertySet(Class propertySet) - { - // If we have an annotation type instance and it matches up with the requested - // type, then return true - if (_annot != null && _annot.getClass().equals(propertySet)) - return true; - - if (_propertySets.contains(propertySet)) - return true; - - // - // Call up to superclass, for delegation model - // - return super.containsPropertySet(propertySet); - } - - /** - * Returns the set of PropertyKeys that are locally set in this property map. Note: - * this does not include any properties that might be set as a result of - * property lookup delegation. - */ - public Set getPropertyKeys() { return _properties.keySet(); } - - // local default annotation value, only set if annot constructor form is used - Annotation _annot; - - // locally maintained property values - HashMap _properties = new HashMap(); - - // locally maintained PropertySets - HashSet _propertySets = new HashSet(); -} diff --git a/beehive-controls/src/main/java/org/apache/beehive/controls/api/properties/PropertyKey.java b/beehive-controls/src/main/java/org/apache/beehive/controls/api/properties/PropertyKey.java deleted file mode 100644 index eb78591..0000000 --- a/beehive-controls/src/main/java/org/apache/beehive/controls/api/properties/PropertyKey.java +++ /dev/null @@ -1,159 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.api.properties; - -import java.lang.annotation.Annotation; -import java.lang.reflect.Method; - -import org.apache.beehive.controls.api.ControlException; - -/** - * The PropertyKey class represents a key that can be used to set a JSR-175 attribute member - * value within a PropertyMap. - */ -public class PropertyKey implements java.io.Serializable -{ - /** - * This constructor takes the JSR-175 metadata interface that is associated with - * the contained attributes. - */ - public PropertyKey(Class propertySet, String propertyName) - { - if (!propertySet.isAnnotation()) - { - throw new IllegalArgumentException("Class " + propertySet + " is not a valid annotation type"); - } - - try - { - _getMethod = propertySet.getMethod(propertyName, (Class [])null); - _propertySet = propertySet; - _propertyName = propertyName; - _propertyType = _getMethod.getReturnType(); - - // - // Compute a hash code for the key instance that will be constant for all keys - // that reference the same interface/member combo - // - _hashCode = new String(propertySet.getName() + "." + propertyName).hashCode(); - } - catch (NoSuchMethodException nsme) - { - throw new IllegalArgumentException(propertyName + - "is not a valid member of the metadata interface " + propertySet); - } - } - - protected Method getMethod() - { - if (null == _getMethod) - { - try - { - _getMethod = _propertySet.getMethod(_propertyName, (Class [])null); - } - catch(NoSuchMethodException nsmEx) - { - // This can only happen if a PropertySet is incompatibly changed after - // serialization of a PropertyKey (since it is initially validated in - // the constructor). - throw new ControlException("Unable to locate PropertyKey accessor method", nsmEx); - } - } - return _getMethod; - } - - /** - * Computes the default value for the value of this property key, or null if there - * is no defined default. - */ - public Object getDefaultValue() - { - // Query the accessor method for the default value - // This method will return 'null' if there is no defined default - return getMethod().getDefaultValue(); - } - - /** - * Extracts the value of the key from an Annotation instance - */ - /* package */ Object extractValue(Annotation annot) - { - try - { - return getMethod().invoke(annot, new Object [] {}); - } - // TODO -- cleanup exception handling, property defining a PropertyException - catch (RuntimeException re) { throw re; } - catch (Exception e) - { - throw new RuntimeException("Unable to extract value for " + _propertyName, e); - } - } - - public boolean equals(Object obj) - { - // fast success for static key declaration cases - if (this == obj) - return true; - - // fast fail on obvious differences - if (obj == null || !(obj instanceof PropertyKey) || _hashCode != obj.hashCode()) - return false; - - // slower success on two equivalent keys constructed independently - PropertyKey keyObj = (PropertyKey)obj; - return _propertySet.equals(keyObj._propertySet) && - _propertyName.equals(keyObj._propertyName); - } - - public int hashCode() { - return _hashCode; - } - - public String toString() - { - return "PropertyKey: " + _propertySet.getName() + "." + _propertyName; - } - - public Class getPropertySet() { - return _propertySet; - } - - public String getPropertyName() { - return _propertyName; - } - - public Class getPropertyType() { - return _propertyType; - } - - public Annotation[] getAnnotations() { - return getMethod().getAnnotations(); - } - - Class _propertySet; - String _propertyName; - Class _propertyType; - int _hashCode; - - // WARNING: This field should never be accessed directly but instead via the getMethod() - // API. This ensures that the (transient) value is appropriately recomputed when necessary. - private transient Method _getMethod; -} \ No newline at end of file diff --git a/beehive-controls/src/main/java/org/apache/beehive/controls/api/properties/PropertyMap.java b/beehive-controls/src/main/java/org/apache/beehive/controls/api/properties/PropertyMap.java deleted file mode 100644 index fb27400..0000000 --- a/beehive-controls/src/main/java/org/apache/beehive/controls/api/properties/PropertyMap.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.api.properties; - -import java.lang.annotation.Annotation; - -/** - * The PropertyMap interface represents a collection of ControlBean properties. Concrete - * implementations of this interface might derive property values from a local Map, Java 5.0 - * annotations, external configuration, or other property sources. - */ -public interface PropertyMap -{ - /** - * Returns the PropertySet or Control interface class associated with the PropertyMap. - */ - public Class getMapClass(); - - /** - * Sets a delegate base property map from which values will be derived if not found within - * the local property map. - */ - public void setDelegateMap(PropertyMap delegateMap); - - /** - * Returns a delegate base property map from which values will be derived if not found within - * the local property map. - */ - public PropertyMap getDelegateMap(); - - /** - * Sets the property specifed by 'key' within this map. - */ - public void setProperty(PropertyKey key, Object value); - - /** - * Returns the property value specified by 'key' within this map. - */ - public Object getProperty(PropertyKey key); - - /** - * Returns true if the PropertyMap contains one or more values for the specified - * PropertySet, false otherwise - */ - public boolean containsPropertySet(Class propertySet); - - /** - * Returns a PropertySet proxy instance that derives its data from the contents of - * the property map. Will return null if the PropertyMap does not contain any properties - * associated with the specified PropertySet. - */ - public T getPropertySet(Class propertySet); -} diff --git a/beehive-controls/src/main/java/org/apache/beehive/controls/api/properties/PropertySet.java b/beehive-controls/src/main/java/org/apache/beehive/controls/api/properties/PropertySet.java deleted file mode 100644 index d8c07b1..0000000 --- a/beehive-controls/src/main/java/org/apache/beehive/controls/api/properties/PropertySet.java +++ /dev/null @@ -1,99 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.api.properties; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Inherited; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * The PropertySet annotation type is used to mark an interface that defines a set of - * properties that are associated with a Java Control. By convention, property sets - * are declared as an inner annotation types on the Java Control public interface. - *

- * Each member of the annotation type targeted by the PropertySet annotation - * will define a new property for the control. - *

- * Here is a simple example: - *

- * public interface MyControl extends org.apache.beehive.controls.api.Control
- * {
- *     @PropertySet
- *     public @interface MyProperties
- *     {
- *         public String aStringProperty();
- *         public int anIntProperty();
- *         ...
-       }
- * }
- * 
- *

- * A Java Control can have multiple property sets associated with it. - */ -@Inherited -@Retention(RetentionPolicy.RUNTIME) -@Target({ElementType.ANNOTATION_TYPE}) -public @interface PropertySet -{ - /** - * The prefix member defines a prefix that will be used in all property setter/getter - * methods for properties in the PropertySet. It is necessary to specify - * a prefixes when a control interface has multiple property sets that contain - * properties with the same name. - *

- * The following code shows the basic conventions for setter/getter methods on a Java - * Control Bean: - *

-     *     public void set<prefix><propertyName>(<propertyType> value);
-     *     public <propertyType> get<prefix><propertyName>();
-     * 
/code> - * where prefix is the prefix member value, propertyName is - * the name of the declared property member, and propertyType is the - * type associated with the declared property member. - */ - String prefix() default ""; - - /** - * The externalConfig member defines whether properties in the set will be settable - * via external configuration. - */ - boolean externalConfig() default true; - - /** - * The optional member specifies that this property set may optionally be associated - * with the control. Because there is no way to represent an 'unset' property value, - * optional properties will not expose a getter method to clients; a control - * implementation class can determine whether a property is/is not set, because the - * PropertySet query APIs on ControlBeanContext will return null if unset. For - * properties that are not optional, a PropertySet instance with all default values - * will be returned if unset. - * - * @see org.apache.beehive.controls.api.context.ControlBeanContext#getControlPropertySet - * @see org.apache.beehive.controls.api.context.ControlBeanContext#getMethodPropertySet - */ - boolean optional() default false; - - /** - * The hasSetters member defines whether properties in the set will have programmatic - * setter methods. - */ - boolean hasSetters() default true; -} \ No newline at end of file diff --git a/beehive-controls/src/main/java/org/apache/beehive/controls/api/properties/PropertySetProxy.java b/beehive-controls/src/main/java/org/apache/beehive/controls/api/properties/PropertySetProxy.java deleted file mode 100644 index 1743e59..0000000 --- a/beehive-controls/src/main/java/org/apache/beehive/controls/api/properties/PropertySetProxy.java +++ /dev/null @@ -1,139 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.api.properties; - -import java.lang.annotation.Annotation; -import java.lang.reflect.InvocationHandler; -import java.lang.reflect.Method; -import java.lang.reflect.Proxy; - -/** - * The PropertySetProxy class is a dynamic proxy {@link InvocationHandler} class that exposes the - * values held within a PropertyMap as an Object implementing an annotation type interface. - *

- * This enables properties resolved using the {@link PropertyMap}'s hiearchical resolution mechanism to - * be exposed to the client of the proxy in the same way that Java 5 annotations are - * exposed using raw Java reflection APIs. A proxy of this type should behave identically - * to the one returned from a call to AnnotatedElement.getAnnotation(), but backed - * by a richer, more dynamic resolution mechanism. - * - * @see java.lang.reflect.Proxy - * @see java.lang.reflect.InvocationHandler - * @see java.lang.reflect.AnnotatedElement#getAnnotation - * @see org.apache.beehive.controls.api.properties.PropertySet - * @see org.apache.beehive.controls.api.properties.PropertyMap - */ -public class PropertySetProxy implements InvocationHandler -{ - /** - * Creates a new proxy instance implementing the PropertySet interface and backed - * by the data from the property map. - * - * @param propertySet an annotation type that has the PropertySet meta-annotation - * @param propertyMap the PropertyMap containing property values backing the proxy - * @return proxy that implements the PropertySet interface - */ - public static T getProxy(Class propertySet, PropertyMap propertyMap) - { - assert propertySet != null && propertyMap != null; - - if (!propertySet.isAnnotation()) - throw new IllegalArgumentException(propertySet + " is not an annotation type"); - - return (T)Proxy.newProxyInstance(propertySet.getClassLoader(), - new Class [] {propertySet }, - new PropertySetProxy(propertySet, propertyMap)); - } - - /** - * Private constructor, called only from the getProxy factory method - */ - private PropertySetProxy(Class propertySet, PropertyMap propertyMap) - { - _propertySet = propertySet; - _propertyMap = propertyMap; - } - - // - // InvocationHandler.invoke - // - public Object invoke(Object proxy, Method method, Object[] args) throws Throwable - { - // Handle cases where Object/Annotation methods are called on this - // proxy. We were getting null back from Annotation.annotationType. - Object value = null; - if (method.getDeclaringClass() == Object.class) - { - try { - if (method.getName().equals("getClass")) - { - value = _propertySet; - } - else - { - value = method.invoke(_propertyMap, args); - } - } - catch (Exception e) - { - e.printStackTrace(); - } - } - else if (method.getDeclaringClass() == Annotation.class && - method.getName().equals("annotationType")) - { - value = _propertySet; - } - else - { - - // Query the nested value in the property map - PropertyKey key = new PropertyKey(_propertySet, method.getName()); - value = _propertyMap.getProperty(key); - - // If the returned value is itself a PropertyMap (i.e. a nested annotation type), - // then wrap it in a PropertySetProxy instance before returning. - if (value instanceof PropertyMap) - { - PropertyMap propertyMap = (PropertyMap)value; - value = getProxy(propertyMap.getMapClass(), propertyMap); - } - } - - return value; - } - - /** - * Returns the PropertySet annotation type associated with the proxy - */ - public Class getPropertySet() { - return _propertySet; - } - - /** - * Returns the underlying PropertyMap containing the property values exposed by the - * proxy. - */ - public PropertyMap getPropertyMap() { - return _propertyMap; - } - - private Class _propertySet; - private PropertyMap _propertyMap; -} diff --git a/beehive-controls/src/main/java/org/apache/beehive/controls/api/versioning/Version.java b/beehive-controls/src/main/java/org/apache/beehive/controls/api/versioning/Version.java deleted file mode 100644 index 3704f9f..0000000 --- a/beehive-controls/src/main/java/org/apache/beehive/controls/api/versioning/Version.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.api.versioning; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * Used by the control author to specify the version (major.minor) of the control interface. - * Allowed on interfaces annotated with @ControlInterface. This version number - * is the basis for control versioning, and versioning constraints against it are enforced both at - * compile time and runtime. - */ -@Retention(RetentionPolicy.RUNTIME) -@Target({ElementType.TYPE}) -public @interface Version -{ - /** - * Major version number, typically used to track significant functionality changes. - */ - int major(); - /** - * Minor version number, typically used to track small internal changes/fixes. Version - * constraints default to ignoring the minor version number in their comparisons, but may - * be configured to specify a particular minor version. - */ - int minor() default 0; -} diff --git a/beehive-controls/src/main/java/org/apache/beehive/controls/api/versioning/VersionRequired.java b/beehive-controls/src/main/java/org/apache/beehive/controls/api/versioning/VersionRequired.java deleted file mode 100644 index a89a012..0000000 --- a/beehive-controls/src/main/java/org/apache/beehive/controls/api/versioning/VersionRequired.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.api.versioning; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * Specifies the minimum version of the control interface that this extension - * requires. Allowed on control extensions (interfaces annotated with - * @ControlExtension), and on control field declarations (fields annotated - * with @Control). The version requirement is enforced at compile time of - * extensions and control client, and at runtime when the appropriate control - * bean is classloaded. - */ -@Retention(RetentionPolicy.RUNTIME) -@Target({ElementType.TYPE, ElementType.FIELD}) -public @interface VersionRequired -{ - /** - * The major version value required for this control extension or instance - * declaration to work. Any version number greater than or equal to this - * value will suffice, implying that this requirement is valid only when - * back compatibility is part of the contract when increasing the version - * number. Negative values mean that any major version is - * acceptable (in which case this annotation should probably just not be - * present). - */ - int major(); - - /** - * The minor version value required for this control extension or instance - * declaration to work. Any version number greater than or equal to this - * value will suffice. Negative values mean that any minor version is - * acceptable (the default case). - */ - int minor() default -1; -} diff --git a/beehive-controls/src/main/java/org/apache/beehive/controls/api/versioning/VersionSupported.java b/beehive-controls/src/main/java/org/apache/beehive/controls/api/versioning/VersionSupported.java deleted file mode 100644 index 47682b7..0000000 --- a/beehive-controls/src/main/java/org/apache/beehive/controls/api/versioning/VersionSupported.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.api.versioning; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * Specifies the maximum version of the control interface that this implementation - * supports. Allowed on control implementations (interfaces annotated with - * @ControlImplementation). This version requirement is enforced at compile time - * of the implementation, and at runtime when the implementation is classloaded. - */ -@Retention(RetentionPolicy.RUNTIME) -@Target({ElementType.TYPE}) -public @interface VersionSupported -{ - /** - * The major version of the control interface that this implementation - * supports. Any version number less than or equal to this value will suffice, - * implying that this constraint is only valid when backwards compatibility - * is part of the contract when increasing the version number. Negative - * values mean that any major version is acceptable (in which case this - * annotation should probably just not be - * present). - */ - int major(); - - /** - * The minor version of the control interface that this implementation - * supports. Any version number less than or equal to this value will suffice. - * Negative values mean that any minor version is acceptable (the default case). - */ - int minor() default -1; -} diff --git a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/assembly/AppAssemblyContext.java b/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/assembly/AppAssemblyContext.java deleted file mode 100644 index ffb5e67..0000000 --- a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/assembly/AppAssemblyContext.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.runtime.assembly; - -import org.apache.beehive.controls.api.assembly.ControlAssemblyContext; -import org.apache.beehive.controls.api.assembly.ControlAssemblyException; - -import java.io.File; -import java.util.Map; -import java.util.Set; - -/** - * A ControlAssemblyContext implementation supporting standard Enterprise app modules - */ -public class AppAssemblyContext - extends BaseAssemblyContext - implements ControlAssemblyContext.EntAppModule -{ - - public static class Factory - implements ControlAssemblyContext.Factory - { - public AppAssemblyContext newInstance( Class controlIntfOrExt, - Map bindings, - Set clients, - File moduleRoot, - String moduleName, - File srcOutputRoot ) - throws ControlAssemblyException - { - return new AppAssemblyContext( controlIntfOrExt, bindings, clients, - moduleRoot, moduleName, srcOutputRoot ); - } - } - - protected AppAssemblyContext( Class controlIntfOrExt, Map bindings, - Set clients, File moduleRoot, - String moduleName, File srcOutputRoot ) - throws ControlAssemblyException - { - super( controlIntfOrExt, bindings, clients, moduleRoot, moduleName, srcOutputRoot ); - } - - public File getApplicationXml() - { - return new File( getModuleDir(), "META-INF" + File.separator + "application.xml" ); - } -} diff --git a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/assembly/AssembleTask.java b/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/assembly/AssembleTask.java deleted file mode 100644 index fff2a32..0000000 --- a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/assembly/AssembleTask.java +++ /dev/null @@ -1,268 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.runtime.assembly; - -import java.io.File; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.HashMap; -import java.util.Set; -import java.util.TreeSet; -import java.net.URL; -import java.net.URLClassLoader; - -import org.apache.tools.ant.BuildException; -import org.apache.tools.ant.Task; -import org.apache.tools.ant.types.Path; -import org.apache.tools.ant.types.FileSet; -import org.apache.beehive.controls.runtime.generator.apt.ControlClientManifest; -import org.apache.beehive.controls.api.assembly.ControlAssemblyException; - -/** - * AssembleTask defines a custom ant task to perform control assembly. - *

- * The core assembly algorithm is documented and implemented in {@link Assembler}. - *

- * Required attributes:
- * moduleDir: path to the root of J2EE module on which to perform assembly.
- * srcOutputDir: path to the dir where control assemblers may output source files. - * It may be necessary to run additional build steps in order to process such files (for example, - * if an assembler outputs Java source code, that code may need to be compiled).
- * contextFactoryClassname: fully qualified classname of a factory class that implements - * {@link org.apache.beehive.controls.api.assembly.ControlAssemblyContext.Factory}. Typically this - * would depend on the type of module on which assembly is being run (EJB, webapp, etc). Different - * contexts will expose different APIs to control assemblers (making different descriptors available, - * etc). - *

- * Supported nested elements:
- * classpath: specifies the classpath that will be searched for control interfaces/implementations, - * control clients and control assemblers.
- * fileset: specifies the control client manifests that should be processed by this assembly call.
- *

- * An example usage of the AssembleTask in an ant build script (build.xml): - *

-

- <taskdef name="assemble" classname="org.apache.beehive.controls.runtime.assembly.AssembleTask" - classpathref="controls.dependency.path" onerror="report" /> - - <assemble moduleDir="${build.beans}" - srcOutputDir="${build.beansrc}" - contextFactoryClassname="org.apache.beehive.controls.runtime.assembly.EJBAssemblyContext$Factory"> - <classpath> - <path refid="test.classpath"/> - <pathelement location="${build.beans}"/> - </classpath> - <fileset dir="${build.beans}"> - <include name="**\*.controls.properties"/> - </fileset> - </assemble> - - */ -public class AssembleTask extends Task -{ - public AssembleTask() - { - // do nothing - } - - public void setContextFactoryClassName(String contextFactoryClassName) - { - _contextFactoryClassName = contextFactoryClassName; - } - - public void setModuleDir( File moduleDir ) - { - _moduleDir = moduleDir; - } - - public void setModuleName( String moduleName ) - { - _moduleName = moduleName; - } - - public void setSrcOutputDir( File srcOutputDir ) - { - _srcOutputDir = srcOutputDir; - } - - public void setBindingFile(File bindingFile) - { - _bindingFile = bindingFile; - } - - public FileSet createFileset() - { - _clientManifestFileSet = new FileSet(); - return _clientManifestFileSet; - } - - // used to set classpath as an attribute - public void setClasspath(Path classpath) - { - _classPath = new Path(getProject()); - _classPath.append(classpath); - } - - // used to set classpath as a nested element - public Path createClasspath() - { - _classPath = new Path(getProject()); - return _classPath; - } - - public void execute() - { - validateAttributeSettings(); - - if (_clientManifestFileSet == null) - { - log("No input fileset specified, nothing to do."); - return; - } - - // get list of input files as list of ControlRefs files - File filesetDir = _clientManifestFileSet.getDir(getProject()); - String[] clientManifests = _clientManifestFileSet. - getDirectoryScanner(getProject()).getIncludedFiles(); - - if (clientManifests.length == 0) - { - log("Input fileset contained no files, nothing to do."); - return; - } - - List manifestFiles = new ArrayList(); - for ( String mf : clientManifests ) - { - File f = new File(filesetDir, mf ); - if (!f.exists()) - { - log("File " + f.getAbsolutePath() + - " in input fileset does not exist."); - continue; - } - - manifestFiles.add(f); - } - - // REVIEW: nested control usage is handled poorly right now. - // Need to refine how we pick up control client manifests, especially - // for manifests inside control jars (instead of blindly scanning and - // including all manifests inside all jars, should base it on actual nested - // control usage as analyzed by starting at non-control clients). - try - { - // Build map of control types to assemble by scanning supplied manifests - - Map controlTypesToImpls = new HashMap(); - Map> controlTypesToClients = - new HashMap>(); - - for ( File mf : manifestFiles ) - { - ControlClientManifest ccmf = new ControlClientManifest( mf ); - String controlClient = ccmf.getControlClient(); - List controlTypes = ccmf.getControlTypes(); - for ( String ct : controlTypes ) - { - controlTypesToImpls.put( ct, ccmf.getDefaultImpl( ct ) ); - Set clients = controlTypesToClients.get( ct ); - if (clients == null) - { - clients = new TreeSet(); - controlTypesToClients.put( ct, clients ); - } - clients.add( controlClient ); - } - } - - // Build classloader to do loading - // - // TODO: The module dir should probably be in the classpath, since it seems reasonable - // for assemblers to want access to the classes in the module. - - String[] classpaths = _classPath == null ? new String[0] : _classPath.list(); - ClassLoader cl = buildClassLoader( classpaths, Assembler.class.getClassLoader() ); - - Assembler.assemble( _moduleDir, _moduleName, _srcOutputDir, _contextFactoryClassName, - controlTypesToImpls, controlTypesToClients, cl ); - } - catch (Exception e) - { - e.printStackTrace(); - throw new BuildException("Assembly failed.", e); - } - } - - private void validateAttributeSettings() throws BuildException - { - if (_contextFactoryClassName == null) - throw new BuildException("The contextFactoryClassName attribute must be set"); - - if (_moduleDir == null) - throw new BuildException("The moduleDir attribute must be set"); - - if (_srcOutputDir == null) - throw new BuildException("The srcOutputDir attribute must be set"); - } - - private ClassLoader buildClassLoader( String[] paths, ClassLoader parentCL) - throws ControlAssemblyException - { - List list = new ArrayList(); - for (int i=0; i controlTypeToImpl, - Map> controlTypeToClients, - ClassLoader cl ) - throws ControlAssemblyException, IOException - { - if ( !moduleRoot.exists() || !srcOutputRoot.exists() ) - throw new IOException( "Directories " + moduleRoot + " or " + srcOutputRoot + " don't exist!"); - - if ( factoryName == null ) - throw new ControlAssemblyException( "Missing context factory names" ); - - if ( cl == null ) - throw new ControlAssemblyException( "Must specify a classloader" ); - - ClassLoader origCL = Thread.currentThread().getContextClassLoader(); - Thread.currentThread().setContextClassLoader( cl ); - - try - { - // Create the requested ControlAssemblyContext.Factory - Class factoryClass = cl.loadClass( factoryName ); - ControlAssemblyContext.Factory factory = (ControlAssemblyContext.Factory)factoryClass.newInstance(); - - // Iterate over control types - Set controlTypes = controlTypeToImpl.keySet(); - for ( String ct : controlTypes ) - { - // Search for applicable ControlAssemblers as specified on the control impls - String cImpl = controlTypeToImpl.get( ct ); - Class cImplClass = cl.loadClass( cImpl ); - - ControlImplementation a = (ControlImplementation)cImplClass.getAnnotation(ControlImplementation.class); - if ( a == null ) - throw new ControlAssemblyException( "Control implementation class=" + cImpl + " missing ControlImplementation annotation" ); - - // For each non-default ControlAssembler, create one and call it. - Class assemblerClass = a.assembler(); - if ( !assemblerClass.equals(DefaultControlAssembler.class) ) - { - ControlAssembler assembler = assemblerClass.newInstance(); - Set clients = controlTypeToClients.get( ct ); - ControlAssemblyContext cac = factory.newInstance( - cl.loadClass(ct), null, clients, moduleRoot, moduleName, srcOutputRoot ); - assembler.assemble( cac ); - } - } - } - catch ( ControlAssemblyException cae ) - { - // just rethrow ControlAssemblyExceptions, which will typically come from user-provided assemblers. - throw cae; - } - catch ( Throwable t ) - { - // Not expecting any throwables other than ControlAssemblyExceptions, so consider them as - // unexpected infrastructure issues and wrap them in a CAE. - throw new ControlAssemblyException( "Assembly infrastructure exception", t); - } - finally - { - Thread.currentThread().setContextClassLoader( origCL ); - } - } -} diff --git a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/assembly/BaseAssemblyContext.java b/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/assembly/BaseAssemblyContext.java deleted file mode 100644 index 969471d..0000000 --- a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/assembly/BaseAssemblyContext.java +++ /dev/null @@ -1,204 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.runtime.assembly; - -import java.io.File; -import java.lang.annotation.Annotation; -import java.lang.reflect.Method; -import java.util.Map; -import java.util.Set; -import java.util.LinkedList; -import java.util.Queue; - -import com.sun.mirror.apt.Messager; -import com.sun.mirror.util.SourcePosition; - -import org.apache.beehive.controls.api.bean.ControlInterface; -import org.apache.beehive.controls.api.assembly.ControlAssemblyContext; -import org.apache.beehive.controls.api.assembly.ControlAssemblyException; -import org.apache.beehive.controls.runtime.bean.ControlUtils; - -/** - * Abstract ControlAssemblyContext implementation. Provides a basic implementation of most non-module-specific - * APIs, meant to be extended by module-specific types. - */ -public abstract class BaseAssemblyContext implements ControlAssemblyContext -{ - protected BaseAssemblyContext( Class controlIntfOrExt, Map bindings, - Set clients, File moduleRoot, - String moduleName, File srcOutputRoot ) - throws ControlAssemblyException - { - _controlIntfOrExt = controlIntfOrExt; - _bindings = bindings; - _clients = clients; - _moduleRoot = moduleRoot; - _moduleName = moduleName; - _srcOutputRoot = srcOutputRoot; - _messager = new DefaultAssemblyMessager(); - - // Compute and cache "most derived ControlInterface" - Queue q = new LinkedList(); - Class ci = controlIntfOrExt; - - while ( ci != null ) - { - if ( ci.isAnnotationPresent(ControlInterface.class) ) - { - _controlMostDerivedIntf = ci; - break; - } - - Class[] supers = ci.getInterfaces(); - for ( Class s : supers ) - q.offer( s ); - - ci = q.poll(); - } - - if ( _controlMostDerivedIntf == null ) - throw new ControlAssemblyException( "Invalid control type: " + controlIntfOrExt.getName() ); - } - - public Class getControlType() - { - return _controlIntfOrExt; - } - - public Class getMostDerivedControlInterface() - { - return _controlMostDerivedIntf; - } - - // TODO - if we want to override class annotations on instance then here is where we will do it - public T - getControlAnnotation(Class annotationClass) - { - Class controlInterface = getControlType(); - return (T)controlInterface.getAnnotation(annotationClass); - } - - public T - getControlMethodAnnotation(Class annotationClass, Method m) - throws NoSuchMethodException - { - Class controlInterface = getControlType(); - Method controlMethod = controlInterface.getMethod( - m.getName(), m.getParameterTypes()); - - return (T)controlMethod.getAnnotation(annotationClass); - } - - public String getDefaultImplClassName() - { - Class ci = getMostDerivedControlInterface(); - ControlInterface a = (ControlInterface) - ci.getAnnotation(ControlInterface.class); - - return ControlUtils.resolveDefaultBinding( a.defaultBinding(), ci.getName() ); - } - - public File getSrcOutputDir() - { - return _srcOutputRoot; - } - - public File getModuleDir() - { - return _moduleRoot; - } - - public String getModuleName() - { - return _moduleName; - } - - public Set getClients() - { - return _clients; - } - - public Messager getMessager() - { - return _messager; - } - - public boolean hasErrors() - { - return _nErrors > 0; - } - - private class DefaultAssemblyMessager implements Messager - { - public void printError( SourcePosition pos, String msg ) - { - printDiagnostic( "Error", pos, msg ); - _nErrors++; - } - public void printError( String msg ) - { - printError( null, msg ); - } - - public void printNotice( SourcePosition pos, String msg ) - { - printDiagnostic( "Notice", pos, msg ); - } - public void printNotice( String msg ) - { - printNotice( null, msg ); - } - - public void printWarning( SourcePosition pos, String msg ) - { - printDiagnostic( "Warning", pos, msg ); - } - public void printWarning( String msg ) - { - printWarning( null, msg ); - } - - protected void printDiagnostic( String type, SourcePosition pos, String msg ) - { - String fn = ""; - int line = 0; - int column = 0; - - if ( pos != null ) - { - fn = pos.file().getName(); - line = pos.line(); - column = pos.column(); - } - - System.out.println( type + ": (" + fn + ":" + line + ":" + column + ") " + msg ); - } - } - - private File _moduleRoot; - private String _moduleName; - private File _srcOutputRoot; - private Class _controlIntfOrExt; - private Map _bindings; - private Set _clients; - private Messager _messager; - private int _nErrors = 0; - - private Class _controlMostDerivedIntf; -} diff --git a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/assembly/EJBAssemblyContext.java b/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/assembly/EJBAssemblyContext.java deleted file mode 100644 index dadd3be..0000000 --- a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/assembly/EJBAssemblyContext.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.runtime.assembly; - -import org.apache.beehive.controls.api.assembly.ControlAssemblyContext; -import org.apache.beehive.controls.api.assembly.ControlAssemblyException; - -import java.io.File; -import java.util.Map; -import java.util.Set; - -/** - * A ControlAssemblyContext implementation supporting standard EJB modules - */ -public class EJBAssemblyContext - extends BaseAssemblyContext - implements ControlAssemblyContext.EJBModule -{ - public static class Factory implements ControlAssemblyContext.Factory - { - public EJBAssemblyContext newInstance( Class controlIntfOrExt, - Map bindings, - Set clients, - File moduleRoot, - String moduleName, - File srcOutputRoot ) - throws ControlAssemblyException - { - return new EJBAssemblyContext( controlIntfOrExt, bindings, clients, - moduleRoot, moduleName, srcOutputRoot ); - } - } - - protected EJBAssemblyContext( Class controlIntfOrExt, Map bindings, - Set clients, File moduleRoot, - String moduleName, File srcOutputRoot ) - throws ControlAssemblyException - { - super( controlIntfOrExt, bindings, clients, moduleRoot, moduleName, srcOutputRoot ); - } - - public File getEjbJarXml() - { - return new File( getModuleDir(), "META-INF" + File.separator + "ejb-jar.xml"); - } -} diff --git a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/assembly/WebAppAssemblyContext.java b/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/assembly/WebAppAssemblyContext.java deleted file mode 100644 index c1e909a..0000000 --- a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/assembly/WebAppAssemblyContext.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.runtime.assembly; - -import org.apache.beehive.controls.api.assembly.ControlAssemblyContext; -import org.apache.beehive.controls.api.assembly.ControlAssemblyException; - -import java.io.File; -import java.util.Map; -import java.util.Set; - -/** - * A ControlAssemblyContext implementation supporting standard web-app modules - */ -public class WebAppAssemblyContext - extends BaseAssemblyContext - implements ControlAssemblyContext.WebAppModule -{ - public static class Factory - implements ControlAssemblyContext.Factory - { - public WebAppAssemblyContext newInstance( Class controlIntfOrExt, - Map bindings, - Set clients, - File moduleRoot, - String moduleName, - File srcOutputRoot ) - throws ControlAssemblyException - { - return new WebAppAssemblyContext( controlIntfOrExt, bindings, clients, - moduleRoot, moduleName, srcOutputRoot ); - } - } - - protected WebAppAssemblyContext(Class controlIntfOrExt, - Map bindings, - Set clients, - File moduleRoot, - String moduleName, - File srcOutputRoot ) - throws ControlAssemblyException - { - super( controlIntfOrExt, bindings, clients, moduleRoot, moduleName, srcOutputRoot ); - } - - public File getWebXml() - { - return new File( getModuleDir(), "WEB-INF" + File.separator + "web.xml"); - } -} diff --git a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/bean/AdaptorPersistenceDelegate.java b/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/bean/AdaptorPersistenceDelegate.java deleted file mode 100644 index aa72e8c..0000000 --- a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/bean/AdaptorPersistenceDelegate.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.runtime.bean; - -import java.beans.DefaultPersistenceDelegate; -import java.beans.Encoder; -import java.beans.Expression; - -/** - * The AdaptorPersistenceDelegate class supports the XML persistance of Control Client Event - * Adaptor instances by implementing the java.beans.PersistenceDelegate API, and - * overriding the default persistance algorithm based upon the runtime structure for Controls. - */ -public class AdaptorPersistenceDelegate extends DefaultPersistenceDelegate -{ - /** - * PersistenceDelegate.instantiate() - */ - protected Expression instantiate(Object oldInstance, Encoder out) - { - if (! (oldInstance instanceof EventAdaptor)) - return super.instantiate(oldInstance, out); - - // - // An implementation instance is actually constructed at decode time by calling - // ControlBean.ensureControl on the parent bean. This will create a new impl - // instance and run the impl initializer on it. - // - return new Expression(oldInstance, oldInstance.getClass(), "new", - new Object[] { ((EventAdaptor)oldInstance).getClient() }); - } - - /** - * PersistenceDelegate.initialize() - */ - protected void initialize(Class type, Object oldInstance, Object newInstance, Encoder out) - { - super.initialize(type, oldInstance, newInstance, out); - } - - /** - * PersistenceDelegate.writeObject() - */ - public void writeObject(Object oldInstance, Encoder out) - { - super.writeObject(oldInstance, out); - } -} diff --git a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/bean/AnnotatedElementMapPersistenceDelegate.java b/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/bean/AnnotatedElementMapPersistenceDelegate.java deleted file mode 100644 index 27b61b5..0000000 --- a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/bean/AnnotatedElementMapPersistenceDelegate.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.runtime.bean; - -import java.beans.PersistenceDelegate; -import java.beans.Encoder; -import java.beans.Expression; - -import org.apache.beehive.controls.api.properties.AnnotatedElementMap; - -/** - * The AnnotatedElementMapPersistenceDelegate is an XMLEncoder PersistenceDelegate for - * the org.apache.beehive.controls.api.properties.AnnotatedElementMap - * class. - */ -public class AnnotatedElementMapPersistenceDelegate extends PersistenceDelegate -{ - protected Expression instantiate(Object oldInstance, Encoder out) - { - // - // Modify the default constructor to pass in the AnnotatedElement wrapped by the map - // - AnnotatedElementMap aem = (AnnotatedElementMap)oldInstance; - return new Expression(aem, aem.getClass(), "new", - new Object [] { aem.getAnnotatedElement() }); - } -} diff --git a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/bean/AnnotationConstraintValidator.java b/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/bean/AnnotationConstraintValidator.java deleted file mode 100644 index 0cff69f..0000000 --- a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/bean/AnnotationConstraintValidator.java +++ /dev/null @@ -1,574 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.runtime.bean; - -import java.lang.annotation.Annotation; -import java.lang.reflect.Method; -import java.net.MalformedURLException; -import java.net.URI; -import java.net.URL; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.text.ParsePosition; -import java.util.Date; - -import org.apache.beehive.controls.api.bean.AnnotationMemberTypes; -import org.apache.beehive.controls.api.bean.AnnotationConstraints.MembershipRule; -import org.apache.beehive.controls.api.bean.AnnotationConstraints.MembershipRuleValues; -import org.apache.beehive.controls.api.properties.PropertyKey; - -/** - * This class offers methods for validating values assigned to a control property. - * The validation process will ensure - * 1. The value is appropriate for the property's property type - * 2. The value satisfies the constraints defined on the property type - * 3. The value satisfies the constraints defined on the property set that the property is defined in. - * Refer to {@link org.apache.beehive.controls.api.bean.AnnotationMemberTypes AnnotationMemberTypes} and - * {@link org.apache.beehive.controls.api.bean.AnnotationConstraints AnnotationConstraints} for more - * information on property constraints. - */ -public class AnnotationConstraintValidator -{ - - public AnnotationConstraintValidator() - { - super(); - } - - /** - * This method ensures that any control property value assignment satisfies - * all property constraints. This method should be called by control - * property setters to ensure values assigned to properties at runtime are - * validated. - * - * @param key - * The property that the specified key is assigned to - * @param value - * The value assigned to the specified property key - * @throws IllegalArgumentException - * when the value assigned to the specified property key does - * not satisfy a property constraint. - */ - public static void validate(PropertyKey key, Object value) - throws IllegalArgumentException - { - validate(key.getAnnotations(), value); - } - - /** - * This method ensures the membership constraints defined on a property set - * is satisfied. - * - * @param propertySet the property set to validate - */ - public static void validateMembership(Annotation propertySet) - { - Class c = propertySet.annotationType(); - MembershipRule rule = (MembershipRule) c.getAnnotation(MembershipRule.class); - if (rule == null) - return; - MembershipRuleValues ruleValue = rule.value(); - String[] memberNames = rule.memberNames(); - Method[] members = getMembers(c, memberNames); - int i = getNumOfMembersSet(propertySet, members); - if (ruleValue == MembershipRuleValues.ALL_IF_ANY) - { - if (i != 0 && i != members.length) - throw new IllegalArgumentException("The membership rule on " + propertySet.toString() + - " is not satisfied. Either all members must be set or none is set"); - } - else if (ruleValue == MembershipRuleValues.EXACTLY_ONE) - { - if (i != 1) - throw new IllegalArgumentException("The membership rule on " + propertySet.toString() + - " is not satisfied. Exactly one member must be set"); - } - else if (ruleValue == MembershipRuleValues.AT_LEAST_ONE) - { - if (i < 1) - throw new IllegalArgumentException("The membership rule on " + propertySet.toString() + - " is not satisfied. At least one member must be set"); - } - else if (ruleValue == MembershipRuleValues.AT_MOST_ONE) - { - if (i > 1) - throw new IllegalArgumentException("The membership rule on " + propertySet.toString() + - " is not satisfied. At most one member may be set"); - } - } - - private static Method[] getMembers(Class c, String[] memberNames) - { - Method[] methods = null; - if (memberNames == null || memberNames.length == 0) - { - methods = c.getDeclaredMethods(); - } - else - { - methods = new Method[memberNames.length]; - for (int i = 0; i < memberNames.length; i++) - { - try - { - methods[i] = c.getMethod(memberNames[i], (Class[]) null); - } - catch (Exception e) - { - // method is not found, so the member is ignored. - } - } - } - return methods; - } - - private static int getNumOfMembersSet(Annotation propertySet, - Method[] members) - { - int num = 0; - for (Method m : members) - { - Class returnType = m.getReturnType(); - Object o = null; - try - { - o = m.invoke(propertySet, (Object[]) null); - } - catch (Exception e) - { - // This should never happen. - throw new RuntimeException(e); - } - - if ((returnType == String.class && !((String) o) - .equals(AnnotationMemberTypes.OPTIONAL_STRING)) - || (returnType == int.class && ((Integer) o).intValue() != AnnotationMemberTypes.OPTIONAL_INT) - || (returnType == short.class && ((Short) o) - .shortValue() != AnnotationMemberTypes.OPTIONAL_SHORT) - || (returnType == long.class && ((Long) o).longValue() != AnnotationMemberTypes.OPTIONAL_LONG) - || (returnType == float.class && ((Float) o) - .floatValue() != AnnotationMemberTypes.OPTIONAL_FLOAT) - || (returnType == double.class && ((Double) o) - .doubleValue() != AnnotationMemberTypes.OPTIONAL_DOUBLE) - || (returnType == char.class && ((Character) o) - .charValue() != AnnotationMemberTypes.OPTIONAL_CHAR) - || (returnType == byte.class && ((Byte) o).byteValue() != AnnotationMemberTypes.OPTIONAL_BYTE) - || (returnType == boolean.class && !((Boolean) o) - .booleanValue())) - num++; - } - return num; - } - - protected static synchronized void validate(Annotation[] annotations, - Object value) throws IllegalArgumentException - { - - // Determine if the member is optional. This is done in a separate loop - // because a control property may have multiple constraints and the - // optional - // annotation may be declared after another constraint annotation. - boolean optional = false; - for (Annotation a : annotations) - { - if (a instanceof AnnotationMemberTypes.Optional) - { - optional = true; - break; - } - } - - for (Annotation a : annotations) - { - if (a instanceof AnnotationMemberTypes.Text) - validateText((AnnotationMemberTypes.Text) a, value, optional); - else if (a instanceof AnnotationMemberTypes.Decimal) - validateDecimal((AnnotationMemberTypes.Decimal) a, value, - optional); - else if (a instanceof AnnotationMemberTypes.Int) - validateInt((AnnotationMemberTypes.Int) a, value, optional); - else if (a instanceof AnnotationMemberTypes.Date) - validateDate((AnnotationMemberTypes.Date) a, value, optional); - else if (a instanceof AnnotationMemberTypes.FilePath) - validateFilePath((AnnotationMemberTypes.FilePath) a, value, - optional); - else if (a instanceof AnnotationMemberTypes.JndiName) - validateJndiName((AnnotationMemberTypes.JndiName) a, value, - optional); - else if (a instanceof AnnotationMemberTypes.QName) - validateQName((AnnotationMemberTypes.QName) a, value, optional); - else if (a instanceof AnnotationMemberTypes.URI) - validateURI((AnnotationMemberTypes.URI) a, value, optional); - else if (a instanceof AnnotationMemberTypes.URL) - validateURL((AnnotationMemberTypes.URL) a, value, optional); - else if (a instanceof AnnotationMemberTypes.URN) - validateURN((AnnotationMemberTypes.URN) a, value, optional); - else if (a instanceof AnnotationMemberTypes.XML) - validateXML((AnnotationMemberTypes.XML) a, value, optional); - } - } - - private static void validateXML(AnnotationMemberTypes.XML a, Object value, - boolean optional) - { - } - - private static void validateURN(AnnotationMemberTypes.URN a, Object value, - boolean optional) - { - if (optional - && (value == null || value - .equals(AnnotationMemberTypes.OPTIONAL_STRING))) - return; - - if (!(value instanceof String)) - { - error("The value, " - + value - + ", assigned to an URN property must be of type java.lang.String."); - } - - URI.create((String) value); - } - - private static void validateURL(AnnotationMemberTypes.URL a, Object value, - boolean optional) - { - if (optional - && (value == null || value - .equals(AnnotationMemberTypes.OPTIONAL_STRING))) - return; - - if (!(value instanceof String)) - { - error("The value, " - + value - + ", assigned to an URL property must be of type java.lang.String."); - } - - try - { - new URL((String) value); - } - catch (MalformedURLException mue) - { - error("The value, " + value - + ", assigned to the URL property is a malformed URL.", mue); - } - } - - private static void validateURI(AnnotationMemberTypes.URI a, Object value, boolean optional) - { - if (optional - && (value == null || value - .equals(AnnotationMemberTypes.OPTIONAL_STRING))) - return; - - if (!(value instanceof String)) - { - error("The value, " - + value - + ", assigned to an URI property must be of type java.lang.String."); - } - - URI.create((String) value); - } - - private static void validateQName(AnnotationMemberTypes.QName a, Object value, boolean optional) - { - } - - private static void validateJndiName(AnnotationMemberTypes.JndiName a, Object value, boolean optional) - { - } - - private static void validateFilePath(AnnotationMemberTypes.FilePath a, Object value, boolean optional) - { - if (optional - && (value == null || value - .equals(AnnotationMemberTypes.OPTIONAL_STRING))) - return; - - if (!(value instanceof String)) - { - error("The value, " - + value - + ", assigned to a FilePath property must be of type java.lang.String."); - } - -//Temporarily commenting out the following check on FilePath until -//an agreement is reached on what is a valid FilePath. -// -// File file = new File((String) value); -// if (!file.isFile() || !file.canRead()) -// { -// error("The value, " -// + value -// + ", assigned to a FilePath property must be a readable file."); -// } - - } - - private static void validateDate(AnnotationMemberTypes.Date a, Object value, boolean optional) { - - if (optional && (value == null || value.equals(AnnotationMemberTypes.OPTIONAL_STRING))) - return; - - if (!(value instanceof String)) - error("The value, " - + value - + ", assigned to a date property must be of type java.lang.String."); - - String format = a.format(); - Date date = null; - try { - date = parseDate(format , (String)value); - } catch (ParseException pe) { - error("The value, " - + value - + ", assigned to a date property is not in the specified format of: " - + format); - } - - String minValue = a.minValue(); - if (minValue != null && minValue.length() > 0) { - - Date minDate = null; - try { - minDate = parseDate(format, a.minValue()); - } catch (ParseException pe) { - error("The value, " - + minValue - + ", assigned to minValue date constraint property is not in the specified format of: " - + format); - } - - if (minDate.compareTo(date) > 0) { - error("The value, " - + value - + ", assigned to a date property is earlier than the earliest date allowed: " - + minValue); - } - } - - String maxValue = a.maxValue(); - if (maxValue != null && maxValue.length() > 0) { - - Date maxDate = null; - try { - maxDate = parseDate(format, a.maxValue()); - } catch (ParseException pe) { - error("The value, " - + maxValue - + ", assigned to maxValue date constraint property is not in the specified format of: " - + format); - } - - if (maxDate.compareTo(date) < 0) { - error("The date, " - + value - + ", assigned to a date property is later than the latest date allowed: " - + maxValue); - } - } - } - - /** - * Parse a date value into the specified format. Pay special attention to the case of the value - * having trailing characters, ex. 12/02/2005xx which will not cause the parse of the date to fail - * but should be still treated as an error for our purposes. - * - * @param format Format string for the date. - * @param value A String containing the date value to parse. - * @return A Date instance if the parse was successful. - * @throws ParseException If the value is not a valid date. - */ - public static Date parseDate(String format, String value) - throws ParseException { - - SimpleDateFormat sdFormat = new SimpleDateFormat(format); - sdFormat.setLenient(false); - ParsePosition pp = new ParsePosition(0); - Date d = sdFormat.parse(value, pp); - - /* - a date value such as: 12/01/2005x will not cause a parse error, - use the parse position to detect this case. - */ - if (d == null || pp.getIndex() < value.length()) - throw new ParseException("Parsing date value, " - + value - + ", failed at index " + pp.getIndex(), pp.getIndex()); - else return d; - } - - /** - * @param value - */ - private static void validateInt(AnnotationMemberTypes.Int a, Object value, boolean optional) { - if (optional - && (value == null || - value.equals(AnnotationMemberTypes.OPTIONAL_STRING) || - value.equals(AnnotationMemberTypes.OPTIONAL_INT))) - return; - - int intValue = 0; - - if (value instanceof String) - { - try - { - intValue = Integer.parseInt((String) value); - } - catch (NumberFormatException nfe) - { - error("The value ," - + value - + ", assigned to an int property does not represent an integer."); - } - } - else if (value instanceof Integer) - { - intValue = ((Integer) value).intValue(); - } - else - { - error("The value, " - + value - + ", assigned to an int property must be of type java.lang.String or int."); - } - - if (intValue < a.minValue()) - error("The value, " - + intValue - + ", assigned to an int property is less than the minimum value allowed: " - + a.minValue() + "."); - else if (intValue > a.maxValue()) - error("The value, " - + intValue - + ", assigned to an int property exeeds the maximum value allowed: " - + a.maxValue() + "."); - } - - private static void validateDecimal(AnnotationMemberTypes.Decimal a, - Object value, boolean optional) - { - if (optional - && (value == null || - value.equals(AnnotationMemberTypes.OPTIONAL_STRING) || - value.equals(AnnotationMemberTypes.OPTIONAL_FLOAT) || - value.equals(AnnotationMemberTypes.OPTIONAL_DOUBLE))) - return; - - double doubleValue = 0; - String doubleString = null; - - if (value instanceof String) - { - doubleValue = Double.parseDouble((String)value); - doubleString = (String)value; - } - else if (value instanceof Float) - { - doubleValue = ((Float)value).doubleValue(); - doubleString = ((Float)value).toString(); - } - else if (value instanceof Double) - { - doubleValue = ((Double)value).doubleValue(); - doubleString = ((Double)value).toString(); - } - else - { - error("The value, " - + value - + ", assigned to a decimal property must be of type float, double, or java.lang.String."); - } - - if (doubleValue < a.minValue()) - error("The value, " - + doubleValue - + ", assigned to a decimal property is less than the the minimum value allowed: " - + a.minValue() + "."); - - if (doubleValue > a.maxValue()) - error("The value, " - + doubleValue - + ", assigned to a decimal property exceeds the maximum value allowed: " - + a.maxValue() + "."); - - int decimalPos = doubleString.indexOf('.'); - - if (decimalPos == -1 || a.places() == AnnotationMemberTypes.UNLIMITED_PLACES) - return; - - if (doubleString.length() - decimalPos - 1 > a.places()) - error("The decimal places in the value, " + doubleString - + ", assigned to a decimal property exceeds " + a.places() - + ", the number of decimal places allowed."); - - } - - private static void validateText(AnnotationMemberTypes.Text a, - Object value, boolean optional) - { - if (optional - && (value == null || value - .equals(AnnotationMemberTypes.OPTIONAL_STRING))) - return; - - if (!(value instanceof String)) - error("The value, " - + value - + ", assigned to a text property must be of type java.lang.String."); - - String str = (String) value; - if (str.length() > a.maxLength()) - error("The value, " - + str - + ", assigned to a text property exceeds the maximum length allowed: " - + a.maxLength()); - - if (a.isLong()) - { - try - { - Long.parseLong(str); - } - catch (NumberFormatException nfe) - { - error("The value, " - + str - + ", assigned to a text property with a long number constraint does not represent a long number."); - } - } - - } - - private static void error(String message) - { - error(message, null); - } - - private static void error(String message, Throwable t) - { - throw new IllegalArgumentException(message, t); - } - -} diff --git a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/bean/BeanListener.java b/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/bean/BeanListener.java deleted file mode 100644 index 9d41ebf..0000000 --- a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/bean/BeanListener.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.runtime.bean; - -/** - * The BeanListener class acts as the abstract base class for generated event listeners - * associated with a ControlBean. - */ -abstract public class BeanListener - implements java.io.Serializable -{ - protected BeanListener() - { - this(null); - } - - protected BeanListener(Object source) - { - _source = source; - } - - abstract public BeanListener cloneListener(Object source); - - public Object getSource() { - return _source; - } - - Object _source; -} diff --git a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/bean/BeanPersistenceDelegate.java b/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/bean/BeanPersistenceDelegate.java deleted file mode 100644 index c1c8798..0000000 --- a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/bean/BeanPersistenceDelegate.java +++ /dev/null @@ -1,312 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.runtime.bean; - -import java.beans.BeanInfo; -import java.beans.DefaultPersistenceDelegate; -import java.beans.Encoder; -import java.beans.EventSetDescriptor; -import java.beans.Expression; -import java.beans.IntrospectionException; -import java.beans.Introspector; -import java.beans.PersistenceDelegate; -import java.beans.PropertyDescriptor; -import java.beans.Statement; -import java.beans.XMLEncoder; -import java.lang.reflect.Field; -import java.lang.reflect.Method; -import java.util.Iterator; - -import org.apache.beehive.controls.api.ControlException; -import org.apache.beehive.controls.api.properties.AnnotatedElementMap; -import org.apache.beehive.controls.api.properties.BeanPropertyMap; -import org.apache.beehive.controls.api.properties.PropertyKey; -import org.apache.beehive.controls.api.properties.PropertyMap; - -/** - * The BeanPersistenceDelegate class supports the XML persistence of Control JavaBeans by - * implementing the java.beans.PersistenceDelegate API, and overriding the default - * persistence algorithm based upon the runtime structure for Controls. It selectively registers - * other PersistenceDelegate instances for other nested entities, as required, to ensure that - * runtime-defined state and object relationships are properly maintained. - *

- * For the BeanInfo of all generated ControlJavaBeans, a BeanPersistenceDelegate instance will - * be registered as the "persistenceDelegate" attribute in the BeanDescriptor. The standard - * java.beans.Encoder persistence delegate lookup mechanism recognizes this attribute - * and will use the instance to persist an ControlBeans written to the encoding stream. - *

- * The BeanPersistence class implements optimized property persistence based upon the - * fact that the ControlBean already has a map containing all non-default property state. Rather - * than using the standard (and slower) algorithm of comparing the encoding instance against a - * 'clean' instance, the delegate can simply retrieve the map and persist the values contained - * within it. - * - * @see java.beans.XMLEncoder - * @see java.beans.PersistenceDelegate - */ -public class BeanPersistenceDelegate extends DefaultPersistenceDelegate -{ - /** - * The FieldPersistencersistence is an XMLEncoder PersistenceDelegate for the - * java.lang.reflect.Field claass. It is similar to the one that comes - * bundled with the JDK with one key exception: it works for non-public fields as - * well. - */ - class FieldPersistenceDelegate extends PersistenceDelegate - { - protected Expression instantiate(Object oldInstance, Encoder out) - { - Field f = (Field)oldInstance; - return new Expression(oldInstance, f.getDeclaringClass(), "getDeclaredField", - new Object[]{f.getName()}); - } - } - - /** - * PersistenceDelegate.instantiate() - */ - protected Expression instantiate(Object oldInstance, Encoder out) - { - XMLEncoder xmlOut = (XMLEncoder)out; - ControlBean control = (ControlBean)oldInstance; - - // - // If processing a nested control, then use the parent bean's context as the - // constructor context - // - ControlBeanContext cbc = null; - if (xmlOut.getOwner() != null) - cbc = ((ControlBean)xmlOut.getOwner()).getControlBeanContext(); - - // - // See if the ControlBean has any associated PropertyMap in its delegation chain - // that was derived from an AnnotatedElement so this relationship (and any associated - // external config delegates) will be restored as part of the decoding process. - // - // BUGBUG: What about a user-created PropertyMap that was passed into the constructor? - // - AnnotatedElementMap aem = null; - PropertyMap pMap = control.getPropertyMap(); - while (pMap != null) - { - if (pMap instanceof AnnotatedElementMap) - { - aem = (AnnotatedElementMap)pMap; - - // - // Ignore a class-valued AnnotationElementMap.. this just refers to the - // Control type, and will be automatically reassociated at construction - // time - // - if (aem.getAnnotatedElement() instanceof Class) - aem = null; - - xmlOut.setPersistenceDelegate(AnnotatedElementMap.class, - new AnnotatedElementMapPersistenceDelegate()); - - break; - } - - pMap = pMap.getDelegateMap(); - } - - - // - // Create a constructor that that uses the following form: - // new (ControlBeanContext cbc, String id, PropertyMap map) - // The context is set to null, so the current active container context will be - // used, the id will be the ID of the original control and the map will be - // any AnnotatedElementMap that was passed into the original constructor. - // - return new Expression(control, control.getClass(), "new", - new Object [] {cbc, control.getLocalID(), aem}); - } - - /** - * PersistenceDelegate.initialize() - */ - protected void initialize(Class type, Object oldInstance, Object newInstance, Encoder out) - { - // - // Get the bean and associated beanInfo for the source instance - // - ControlBean control = (ControlBean)oldInstance; - BeanInfo beanInfo; - try - { - beanInfo = Introspector.getBeanInfo(control.getClass()); - } - catch (IntrospectionException ie) - { - throw new ControlException("Unable to locate BeanInfo", ie); - } - - // - // Cast the encoding stream to an XMLEncoder (only encoding supported) and then set - // the stream owner to the bean being persisted - // - XMLEncoder xmlOut = (XMLEncoder)out; - Object owner = xmlOut.getOwner(); - xmlOut.setOwner(control); - try - { - - // - // The default implementation of property persistence will use BeanInfo to - // incrementally compare oldInstance property values to newInstance property values. - // Because the bean instance PropertyMap holds only the values that have been - // modified, this process can be optimized by directly writing out only the properties - // found in the map. - // - BeanPropertyMap beanMap = control.getPropertyMap(); - PropertyDescriptor [] propDescriptors = beanInfo.getPropertyDescriptors(); - for (PropertyKey pk : beanMap.getPropertyKeys()) - { - // - // Locate the PropertyDescriptor for the modified property, and use it to write - // the property value to the encoder stream - // - String propName = pk.getPropertyName(); - boolean found = false; - for (int i = 0; i < propDescriptors.length; i++) - { - if (propName.equals(propDescriptors[i].getName())) - { - found = true; - - // Only write the property if it is not flagged as transient - Object transientVal = propDescriptors[i].getValue("transient"); - if (transientVal == null || transientVal.equals(Boolean.FALSE)) - { - xmlOut.writeStatement( - new Statement(oldInstance, - propDescriptors[i].getWriteMethod().getName(), - new Object [] {beanMap.getProperty(pk)})); - } - } - } - if (found == false) - { - throw new ControlException("Unknown property in bean PropertyMap: " + pk); - } - } - - // - // Get the bean context associated with the bean, and persist any nested controls - // - ControlBeanContext cbc = control.getControlBeanContext(); - if (cbc.size() != 0) - { - xmlOut.setPersistenceDelegate(ControlBeanContext.class, - new ContextPersistenceDelegate()); - - Iterator nestedIter = cbc.iterator(); - while (nestedIter.hasNext()) - { - Object bean = nestedIter.next(); - if (bean instanceof ControlBean) - { - xmlOut.writeStatement( - new Statement(cbc, "add", new Object [] { bean } )); - } - } - } - - // - // Restore any listeners associated with the control - // - EventSetDescriptor [] eventSetDescriptors = beanInfo.getEventSetDescriptors(); - for (int i = 0; i < eventSetDescriptors.length; i++) - { - EventSetDescriptor esd = eventSetDescriptors[i]; - Method listenersMethod = esd.getGetListenerMethod(); - String addListenerName = esd.getAddListenerMethod().getName(); - if (listenersMethod != null) - { - // - // Get the list of listeners, and then add statements to incrementally - // add them in the same order - // - try - { - Object [] lstnrs = (Object [])listenersMethod.invoke(control, - new Object []{}); - for (int j = 0; j < lstnrs.length; j++) - { - // - // If this is a generated EventAdaptor class, then set the delegate - // explicitly - // - if (lstnrs[j] instanceof EventAdaptor) - xmlOut.setPersistenceDelegate(lstnrs[j].getClass(), - new AdaptorPersistenceDelegate()); - xmlOut.writeStatement( - new Statement(control, addListenerName, new Object [] {lstnrs[j]})); - } - } - catch (Exception iae) - { - throw new ControlException("Unable to initialize listeners", iae); - } - } - } - - // - // See if the control holds an implementation instance, if so, we need to include - // it (and any nested controls or state) in the encoding stream - // - Object impl = control.getImplementation(); - if (impl != null) - { - - // - // Set the persistence delegate for the impl class to the Impl delegate, - // set the current stream owner to the bean, and then write the implementation - // - Class implClass = impl.getClass(); - if (xmlOut.getPersistenceDelegate(implClass) instanceof DefaultPersistenceDelegate) - xmlOut.setPersistenceDelegate(implClass, new ImplPersistenceDelegate()); - - // - // HACK: This bit of hackery pushes the impl into the persistence stream - // w/out actually requiring it be used as an argument elsewhere, since there - // is no public API on the bean that takes an impl instance as an argument. - // - xmlOut.writeStatement( - new Statement(impl, "toString", null)); - } - } - finally - { - // Restore the previous encoding stream owner - xmlOut.setOwner(owner); - } - } - - /** - * PersistenceDelegate.writeObject() - */ - public void writeObject(Object oldInstance, Encoder out) - { - // Override the default FieldPersistence algorithm for the encoder, so private fields - // can also be encoded - out.setPersistenceDelegate(Field.class, new FieldPersistenceDelegate()); - super.writeObject(oldInstance, out); - } -} diff --git a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/bean/ClientInitializer.java b/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/bean/ClientInitializer.java deleted file mode 100644 index cc9b365..0000000 --- a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/bean/ClientInitializer.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.runtime.bean; - -import java.lang.reflect.AnnotatedElement; -import org.apache.beehive.controls.api.context.ControlBeanContext; -import org.apache.beehive.controls.api.properties.PropertyMap; -import org.apache.beehive.controls.api.properties.AnnotatedElementMap; -import org.apache.beehive.controls.api.versioning.VersionRequired; -import org.apache.beehive.controls.api.versioning.Version; - -/** - * The ClientInitializer class is an abstract base class that all generated Control - * client initializer classes will extend. It provides common utilities and supporting code - * for initialization, and has a shared package relationship with the base ControlBean - * class providing access to internals not available in a more general context. - */ -abstract public class ClientInitializer -{ - /** - * Enforces the VersionRequired annotation at runtime (called when an instance of a control is annotated - * with VersionRequired). Throws a ControlException if enforcement fails. - * - * @param versionRequired the value of the VersionRequired annotation on a control field - */ - protected static void enforceVersionRequired( ControlBean control, VersionRequired versionRequired ) - { - Class controlIntf = ControlUtils.getMostDerivedInterface( control.getControlInterface() ); - - Version versionPresent = (Version) controlIntf.getAnnotation( Version.class ); - if ( versionPresent != null ) - { - ControlBean.enforceVersionRequired( controlIntf.getCanonicalName(), versionPresent, versionRequired ); - } - } - - /** - * Returns the annotation map for the specified element. - */ - public static PropertyMap getAnnotationMap(ControlBeanContext cbc, AnnotatedElement annotElem) - { - if ( cbc == null ) - return new AnnotatedElementMap(annotElem); - - return cbc.getAnnotationMap(annotElem); - } -} diff --git a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/bean/ContextPersistenceDelegate.java b/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/bean/ContextPersistenceDelegate.java deleted file mode 100644 index 8c83d2d..0000000 --- a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/bean/ContextPersistenceDelegate.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.runtime.bean; - -import java.beans.DefaultPersistenceDelegate; -import java.beans.Encoder; -import java.beans.Expression; -import java.beans.XMLEncoder; - -/** - * The ContextPersistenceDelegate class supports the XML persistance of ControlBeanContext - * instances by implementing the java.beans.PersistenceDelegate API, and overriding - * the default persistance algorithm based upon the runtime structure for Controls. - *

- */ -public class ContextPersistenceDelegate extends DefaultPersistenceDelegate -{ - /** - * PersistenceDelegate.instantiate() - */ - protected Expression instantiate(Object oldInstance, Encoder out) - { - // - // Instead of directly creating a context instance, simply ask the containing - // bean to return the associated context. - // - return new Expression(((XMLEncoder)out).getOwner(), "getControlBeanContext", null); - } - - /** - * PersistenceDelegate.initialize() - */ - protected void initialize(Class type, Object oldInstance, Object newInstance, Encoder out) - { - //super.initialize(type, oldInstance, newInstance, out); - } - - /** - * PersistenceDelegate.writeObject() - */ - public void writeObject(Object oldInstance, Encoder out) - { - super.writeObject(oldInstance, out); - } -} diff --git a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/bean/ControlBean.java b/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/bean/ControlBean.java deleted file mode 100644 index d56e0fd..0000000 --- a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/bean/ControlBean.java +++ /dev/null @@ -1,1119 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.runtime.bean; - -import java.beans.beancontext.BeanContext; -import java.beans.beancontext.BeanContextServices; -import java.beans.PropertyChangeSupport; -import java.beans.VetoableChangeSupport; -import java.io.IOException; -import java.io.ObjectOutputStream; -import java.lang.reflect.AnnotatedElement; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.util.concurrent.Semaphore; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.TooManyListenersException; -import java.util.Vector; - -import org.apache.beehive.controls.api.ControlException; -import org.apache.beehive.controls.api.properties.BaseProperties; -import org.apache.beehive.controls.api.properties.AnnotatedElementMap; -import org.apache.beehive.controls.api.properties.PropertyMap; -import org.apache.beehive.controls.api.properties.BeanPropertyMap; -import org.apache.beehive.controls.api.properties.PropertyKey; -import org.apache.beehive.controls.api.properties.PropertySetProxy; -import org.apache.beehive.controls.api.versioning.VersionRequired; -import org.apache.beehive.controls.api.versioning.Version; -import org.apache.beehive.controls.api.bean.Threading; -import org.apache.beehive.controls.api.bean.ThreadingPolicy; -import org.apache.beehive.controls.api.bean.ControlImplementation; -import org.apache.beehive.controls.api.context.ControlThreadContext; -import org.apache.beehive.controls.api.events.EventRef; -import org.apache.beehive.controls.api.events.EventSet; -import org.apache.beehive.controls.spi.context.ControlBeanContextFactory; -import org.apache.beehive.controls.spi.svc.Interceptor; -import org.apache.beehive.controls.spi.svc.InterceptorPivotException; -import org.apache.commons.discovery.tools.DiscoverClass; - -/** - * The ControlBean class is an abstract base class for the JavaBean classes generated to support - * Beehive Controls. - *

- * The ControlBean class indirectly implements BeanContextProxy; the - * {@link org.apache.beehive.controls.api.context.ControlBeanContext} that it contains/scopes acts as that proxy. - *

- * All support APIs (which may be called from derived subclasses or contextual services) - * are generally marked as protected and have names that start with an underscore. This avoids the - * possibility that the name might conflict with a user-defined method on a control's public or - * extended Control interfaces. - *

- * NOTE: Adding public methods should be done with great care; any such method becomes part of the - * public API, and occupies the method namespace for all controls. - */ -abstract public class ControlBean - implements org.apache.beehive.controls.api.bean.ControlBean -{ - /** - * - * @param context the containing ControlBeanContext. May be null, in which case the bean will attempt to - * associate with an active context at runtime (via thread-locals). - * @param id the local ID for the control, scoped to the control bean context. - * @param initProperties a PropertyMap containing initial properties for the control - * @param controlIntf the control interface or extension directly implemented by the control bean - */ - protected ControlBean(org.apache.beehive.controls.api.context.ControlBeanContext context, - String id, - PropertyMap initProperties, - Class controlIntf) - { - super(); - - _localID = id; - _controlIntf = controlIntf; - - // - // If no containing context was specified during construction, see if there is a current - // active container context and implicitly associated the control with it. - // - if (context == null) - context = ControlThreadContext.getContext(); - - ControlBeanContextFactory cbcFactory = lookupControlBeanContextFactory(context); - _cbc = cbcFactory.instantiate(this); - - // - // Associate this bean with the context. Beans may run without a context! - // Note that the add() call has the side-effect of calling ControlBean.setBeanContext(), which does - // additional setup work, so we make sure we always call that anyways! - // - if (context != null) - context.add(this); - else - setBeanContext(null); - - // - // Get the default map for the control class. This contains the default property - // values for all beans of the class. - // - PropertyMap classMap = getAnnotationMap(controlIntf); - if (initProperties != null) - { - // - // If the initialization map derives its values from a Java annotated element, - // then allow container overrides on this element to be applied. This will also - // coelesce maps referencing the same element. - // - AnnotatedElement annotElem = null; - if (initProperties instanceof AnnotatedElementMap) - { - annotElem = ((AnnotatedElementMap)initProperties).getAnnotatedElement(); - initProperties = getAnnotationMap(annotElem); - } - - // - // If an initial property map was provided, set it to delegate to the default - // map, and then create a wrapper map around it for storing per instance - // properties. - // - if (annotElem != controlIntf) - initProperties.setDelegateMap(classMap); - _properties = new BeanPropertyMap(initProperties); - } - else - { - // - // If no initial map was provided, simply create an empty map wrapping the - // control class default. - // - _properties = new BeanPropertyMap(classMap); - } - - } - - /** - * Configure this bean to be thread-safe given the threading settings of the impl class and - * the outer container. - */ - private void ensureThreadingBehaviour() - { - // - // If the implementation class requires a guarantee of single-threaded behavior and the - // outer container does not guarantee it, then enable invocation locking on this - // bean instance. - // - if (hasSingleThreadedImpl() && ! _cbc.hasSingleThreadedParent()) - _invokeLock = new Semaphore(1, true); - else - _invokeLock = null; - } - /** - * Return the BeanContextService proxy associated with this bean instance - */ - final public ControlBeanContext getBeanContextProxy() - { - return _cbc; - } - - /** - * Returns the nesting BeanContext for this ControlBean. This is thread-safe even though it - * is not synchronized. - */ - final public BeanContext getBeanContext() - { - // - // Indirect through the bean proxy for this control bean and up to its parent nesting - // context. Both these calls (getBeanContextProxy() and getBeanContext()) are, and must - // remain, thread-safe. - // - return getBeanContextProxy().getBeanContext(); - } - - /** - * Called by the BeanContextProxy (_cbc) whenever the _parent_ context containing this control bean is - * changed. This is the place to do any initialization (or reinitialization) that is dependent - * upon attributes of the container for the ControlBean. - * - * Note: this is called in the ControlBean ctor, when a parent context calls add() on the nascent - * bean. - * - * @param bc the new parent context containing this control bean (not _cbc) - */ - final public synchronized void setBeanContext(BeanContext bc) - { - ensureThreadingBehaviour(); - } - - /** - * Returns the control ID for this control - */ - final public String getControlID() - { - return _cbc.getControlID(); - } - - /** - * Returns the public interface for this control. - */ - final public Class getControlInterface() - { - return _controlIntf; - } - - /** - * Returns true if the implementation class for this ControlBean requires the framework - * to ensure thread-safety for it. - */ - /*package*/ boolean hasSingleThreadedImpl() - { - return _threadingPolicy == ThreadingPolicy.SINGLE_THREADED; - } - - /** - * Obtains an instance of the appropriate ImplInitializer class - */ - protected synchronized ImplInitializer getImplInitializer() - { - if (_implInitializer == null) - { - try - { - Class initClass = _implClass.getClassLoader().loadClass( - _implClass.getName() + "Initializer"); - _implInitializer = (ImplInitializer)initClass.newInstance(); - } - catch (Exception e) - { - throw new ControlException("Control initialization failure", e); - } - } - return _implInitializer; - } - - /** - * Returns the target control instance associated with this ControlBean, performing lazy - * instantiation and initialization of the instance. - * - * REVIEW: could probably improve the granularity of locking here, but start w/ just - * synchronizing the entire fn. - */ - public synchronized Object ensureControl() - { - if (_control == null) - { - // - // See if the property map specifies an implementation class for the control; - // if not, use default binding. - // - - String implBinding = null; - BaseProperties bp = _properties.getPropertySet( BaseProperties.class ); - if ( bp != null ) - implBinding = bp.controlImplementation(); - else - implBinding = ControlUtils.getDefaultControlBinding(_controlIntf); - - try - { - _implClass = _controlIntf.getClassLoader().loadClass(implBinding); - - // - // Validate that the specified implementation class has an @ControlImplementation - // annotation, else downstream requirements (such as having a valid control init - // class) will not be met. - // - if (_implClass.getAnnotation(ControlImplementation.class) == null) - { - throw new ControlException("@" + ControlImplementation.class.getName() + " annotation is missing from control implementation class: " + _implClass.getName()); - } - } - catch (ClassNotFoundException cnfe) - { - throw new ControlException("Unable to load control implementation: " + implBinding, cnfe); - } - - // - // Cache the threading policy associated with the impl - // - Threading thr = (Threading)_implClass.getAnnotation(Threading.class); - if ( thr != null ) - _threadingPolicy = thr.value(); - else - _threadingPolicy = ThreadingPolicy.SINGLE_THREADED; // default to single-threaded - - ensureThreadingBehaviour(); - - try - { - // - // Create and initialize the new instance - // - _control = _implClass.newInstance(); - - try - { - /* - Run the ImplInitializer. This class is code generated based on metadata from a control - implementation. If a Control implementation declares event handlers for the - ControlBeanContext or for the ResourceContext, executing this code generated class - will add the appropriate LifeCycle and / or Resource event listeners. - */ - getImplInitializer().initialize(this, _control); - _hasServices = true; - } - catch (Exception e) - { - throw new ControlException("Control initialization failure", e); - } - - // - // Once the control is initialized, then allow the associated context - // to do any initialization. - // - ControlBeanContext cbcs = getBeanContextProxy(); - - /* - Implementation note: this call will run the LifeCycleListener(s) that have - been wired-up to the ControlBeanContext object associated with this ControlBean. - */ - cbcs.initializeControl(); - } - catch (RuntimeException re) { - // never mask RuntimeExceptions - throw re; - } - catch (Exception e) - { - throw new ControlException("Unable to create control instance", e); - } - } - - // - // If the implementation instance does not currently have contextual services, they - // are lazily restored here. - // - if (!_hasServices) - { - getImplInitializer().initServices(this, _control); - _hasServices = true; - } - - return _control; - } - - /** - * Returns the implementation instance associated with this ControlBean. - */ - /* package */ Object getImplementation() { - return _control; - } - - /** - * The preinvoke method is called before all operations on the control. In addition to - * providing a basic hook for logging, context initialization, resource management, - * and other common services, it also provides a hook for interceptors. - */ - protected void preInvoke(Method m, Object [] args, String [] interceptorNames) - throws InterceptorPivotException - { - // - // If the implementation expects single threaded behavior and our container does - // not guarantee it, then enforce it locally here - // - if (_invokeLock != null) - { - try { _invokeLock.acquire(); } catch (InterruptedException ie) { } - } - - // - // Process interceptors - // - if ( interceptorNames != null ) - { - for ( String n : interceptorNames ) - { - Interceptor i = ensureInterceptor( n ); - try - { - i.preInvoke( this, m, args ); - } - catch (InterceptorPivotException ipe) - { - ipe.setInterceptorName(n); - throw ipe; - } - } - } - - Vector invokeListeners = getInvokeListeners(); - if (invokeListeners.size() > 0) - { - for (InvokeListener listener : invokeListeners) - listener.preInvoke(m, args); - } - } - - /** - * The preinvoke method is called before all operations on the control. It is the basic - * hook for logging, context initialization, resource management, and other common - * services - */ - protected void preInvoke(Method m, Object [] args) - { - try - { - preInvoke(m, args, null); - } - catch (InterceptorPivotException ipe) - { - //this will never happen because no interceptor is passed. - } - } - - /** - * The postInvoke method is called after all operations on the control. In addition to - * providing the basic hook for logging, context initialization, resource management, and other common - * services, it also provides a hook for interceptors. During preInvoke, interceptors will be - * called in the order that they are in the list. During postInvoke, they will be called in the - * reverse order. Here is an example of the call sequence with I1, I2, and I3 being interceptors in the list: - * - * I1.preInvoke() -> I2.preInvoke() -> I3.preInvoke() -> invoke method - * | - * I1.postInvoke() <- I2.postInvoke() <- I3.postInvoke() <--- - * - * In the event that an interceptor in the list pivoted during preInvoke, the "pivotedInterceptor" - * parameter indicates the interceptor that had pivoted, and the interceptors succeeding it in the list will - * not be called during postInvoke. - */ - protected void postInvoke(Method m, Object [] args, Object retval, Throwable t, String [] interceptorNames, String pivotedInterceptor) - { - try - { - Vector invokeListeners = getInvokeListeners(); - if (invokeListeners.size() > 0) - { - for (InvokeListener listener : invokeListeners) - listener.postInvoke(retval, t); - } - - // - // Process interceptors - // - if ( interceptorNames != null ) - { - for (int cnt = interceptorNames.length-1; cnt >= 0; cnt-- ) - { - String n = interceptorNames[cnt]; - if (pivotedInterceptor == null || n.equals(pivotedInterceptor)) - { - pivotedInterceptor = null; - Interceptor i = ensureInterceptor( n ); - i.postInvoke( this, m, args, retval, t ); - } - } - } - } - finally - { - // - // Release any lock obtained above in preInvoke - // - if (_invokeLock != null) - _invokeLock.release(); - } - } - - /** - * The postInvoke method is called after all operations on the control. It is the basic - * hook for logging, context initialization, resource management, and other common - * services. - */ - protected void postInvoke(Method m, Object [] args, Object retval, Throwable t) - { - postInvoke(m, args, retval, t, null, null); - } - - - /** - * Sets the EventNotifier for this ControlBean - */ - protected void setEventNotifier(Class eventSet, T notifier) - { - _notifiers.put(eventSet,notifier); - - // - // Register this notifier for all EventSet interfaces up the interface inheritance - // hiearachy as well - // - List superEventSets = new ArrayList(); - getSuperEventSets(eventSet, superEventSets); - Iterator i = superEventSets.iterator(); - while (i.hasNext()) - { - Class superEventSet = i.next(); - _notifiers.put(superEventSet,notifier); - } - } - - /** - * Finds all of the EventSets extended by the input EventSet, and adds them to - * the provided list. - * @param eventSet - * @param superEventSets - */ - private void getSuperEventSets(Class eventSet, List superEventSets) - { - Class[] superInterfaces = eventSet.getInterfaces(); - if (superInterfaces != null) - { - for (int i=0; i < superInterfaces.length; i++) - { - Class superInterface = superInterfaces[i]; - if (superInterface.isAnnotationPresent(EventSet.class)) - { - superEventSets.add(superInterface); - - // Continue traversing up the EventSet inheritance hierarchy - getSuperEventSets(superInterface, superEventSets); - } - } - } - } - - /** - * Returns an EventNotifier/UnicastEventNotifier for this ControlBean for the target event set - */ - protected T getEventNotifier(Class eventSet) - { - return (T)_notifiers.get(eventSet); - } - - /** - * Returns the list of InvokeListeners for this ControlBean - */ - /* package */ Vector getInvokeListeners() - { - if (_invokeListeners == null) - _invokeListeners = new Vector(); - return _invokeListeners; - } - - /** - * Registers a new InvokeListener for this ControlBean. - */ - /* package */ void addInvokeListener(InvokeListener invokeListener) - { - getInvokeListeners().addElement(invokeListener); - } - - /** - * Deregisters an existing InvokeListener for this ControlBean. - */ - /* package */ void removeInvokeListener(InvokeListener invokeListener) - { - getInvokeListeners().removeElement(invokeListener); - } - - /** - * Returns the local (parent-relative) ID for this ControlBean - */ - protected String getLocalID() - { - return _localID; - } - - /** - * Set the local (parent-relative) ID for this ControlBean. It has package access because - * the local ID should only be set from within the associated context, and only when the - * bean is currently anonymous (hence the assertion below) - */ - /* package */ void setLocalID(String localID) - { - assert _localID == null; // should only set if not already set! - _localID = localID; - } - - /** - * Returns the bean context instance associated with the this bean, as opposed to the - * parent context returned by the public getBeanContext() API. - */ - public ControlBeanContext getControlBeanContext() - { - // - // The peer context instance is the context provider for this ControlBean - // - return getBeanContextProxy(); - } - - /** - * Locates and obtains a context service from the BeanContextServices instance - * supporting this bean. - * - * The base design for the BeanContextServicesSupport is that it will delegate up to peers - * in a nesting context, so a nested control bean will look 'up' to find a service provider. - */ - protected Object getControlService(Class serviceClass, Object selector) - throws TooManyListenersException - - { - // - // Get the associated context object, then use it to locate the (parent) bean context. - // Services are always provided by the parent context. - // - ControlBeanContext cbc = getControlBeanContext(); - BeanContext bc = cbc.getBeanContext(); - if (bc == null || !(bc instanceof BeanContextServices)) - throw new ControlException("Can't locate service context: " + bc); - - // - // Call getService on the parent context, using this bean as the requestor and the - // associated peer context instance as the child and event listener parameters. - // - return ((BeanContextServices)bc).getService(cbc, this, serviceClass, selector, cbc); - } - - /** - * Sets a property on the ControlBean instance. All generated property setter methods - * will delegate down to this method. - */ - protected void setControlProperty(PropertyKey key, Object o) - { - AnnotationConstraintValidator.validate(key, o); - _properties.setProperty(key, o); - } - - /** - * Dispatches the requested operation event on the ControlBean. - * @see org.apache.beehive.controls.runtime.bean.ControlContainerContext#dispatchEvent - */ - /* package */ Object dispatchEvent(EventRef event, Object [] args) - throws IllegalAccessException,IllegalArgumentException, - InvocationTargetException - { - ensureControl(); - - // - // Translate the EventRef back to an actual event method on the ControlInterface - // - Class controlInterface = getControlInterface(); - Method method = event.getEventMethod(controlInterface); - - // - // Locate the target of the event - // - Object eventTarget = null; - if (method.getDeclaringClass().isAssignableFrom(_control.getClass())) - { - // - // If the control implementation implements that EventSet interface, then - // dispatch the event directly to it, and allow it do make the decision about - // how/when to dispatch to any external listeners (via a @Client notifier - // instance) - // - eventTarget = _control; - } - else - { - // - // The associated control implementation does not directly handle the event, - // so find the event notifier instance for the EventSet interface associated - // with the method. - // - eventTarget = _notifiers.get(method.getDeclaringClass()); - if (eventTarget == null) - throw new IllegalArgumentException("No event notifier found for " + event); - } - - // - // Dispatch the event - // - return method.invoke(eventTarget, args); - } - - /** - * Returns a property on the ControlBean instance. This version does not coerce - * an annotation type property from a PropertyMap to a proxy instance of the - * type. - */ - protected Object getRawControlProperty(PropertyKey key) - { - return _properties.getProperty(key); - } - - /** - * Returns a property on the ControlBean instance. All generated property getter methods - * will delegate down to this method - */ - protected Object getControlProperty(PropertyKey key) - { - Object value = getRawControlProperty(key); - - // If the held value is a PropertyMap, then wrap it in an annotation proxy of - // the expected type. - if (value instanceof PropertyMap) - { - PropertyMap map = (PropertyMap)value; - value = PropertySetProxy.getProxy(map.getMapClass(), map); - } - - return value; - } - - /* this method is implemented during code generation by a ControlBean extension */ - /** - * Returns the local cache for ControlBean property maps. - */ - abstract protected Map getPropertyMapCache(); - - /** - * Returns the PropertyMap containing values associated with an AnnotatedElement. Elements - * that are associated with the bean's Control interface will be locally cached. - */ - protected PropertyMap getAnnotationMap(AnnotatedElement annotElem) - { - Map annotCache = getPropertyMapCache(); - - // If in the cache already , just return it - if (annotCache.containsKey(annotElem)) - return (PropertyMap)annotCache.get(annotElem); - - // - // Ask the associated ControlBeanContext to locate and initialize a PropertyMap, then - // store it in the local cache. - // - PropertyMap map = getControlBeanContext().getAnnotationMap(annotElem); - annotCache.put(annotElem, map); - - return map; - } - - /** - * Returns the property map containing the properties for the bean - */ - /* package */ BeanPropertyMap getPropertyMap() - { - return _properties; - } - - /** - * This protected version is only available to concrete subclasses that expose bound - * property support. This method is synchronized to enable lazy instantiation, in - * the belief that it is a bigger win to avoid allocating when there are no listeners - * than it is to introduce synchronization overhead on access. - */ - synchronized protected PropertyChangeSupport getPropertyChangeSupport() - { - if (_changeSupport == null) - _changeSupport = new PropertyChangeSupport(this); - - return _changeSupport; - } - - /** - * Delivers a PropertyChangeEvent to any registered PropertyChangeListeners associated - * with the property referenced by the specified key. - * - * This method *should not* be synchronized, as the PropertyChangeSupport has its own - * built in synchronization mechanisms. - */ - protected void firePropertyChange(PropertyKey propertyKey, Object oldValue, Object newValue) - { - // No change support instance means no listeners - if (_changeSupport == null) - return; - - _changeSupport.firePropertyChange(propertyKey.getPropertyName(), oldValue, newValue); - } - - /** - * This protected version is only available to concrete subclasses that expose bound - * property support. This method is synchronized to enable lazy instantiation, in - * the belief that is a bigger win to avoid allocating when there are no listeners - * than it is to introduce synchronization overhead on access. - */ - synchronized protected VetoableChangeSupport getVetoableChangeSupport() - { - if (_vetoSupport == null) - _vetoSupport = new VetoableChangeSupport(this); - - return _vetoSupport; - } - - /** - * Delivers a PropertyChangeEvent to any registered VetoableChangeListeners associated - * with the property referenced by the specified key. - * - * This method *should not* be synchronized, as the VetoableChangeSupport has its own - * built in synchronization mechanisms. - */ - protected void fireVetoableChange(PropertyKey propertyKey, Object oldValue, Object newValue) - throws java.beans.PropertyVetoException - { - // No veto support instance means no listeners - if (_vetoSupport == null) - return; - - _vetoSupport.fireVetoableChange(propertyKey.getPropertyName(), oldValue, newValue); - } - - /** - * Returns the parameter names for a method on the ControlBean. Actual mapping is done - * by generated subclasses, so if we reach the base ControlBean implementation, then - * no parameter names are available for the target method. - */ - protected String [] getParameterNames(Method m) - { - throw new IllegalArgumentException("No parameter name data for " + m); - } - - /** - * Computes the most derived ControlInterface for the specified ControlExtension. - * @param controlIntf - * @return the most derived ControlInterface - * @deprecated Use {@link ControlUtils#getMostDerivedInterface(Class)} instead. This method will - * be removed in the next release. - */ - public static Class getMostDerivedInterface(Class controlIntf) - { - return ControlUtils.getMostDerivedInterface(controlIntf); - } - - /** - * Enforces the VersionRequired annotation at runtime (called from each ControlBean). - * @param intfName - * @param version - * @param versionRequired - */ - protected static void enforceVersionRequired(String intfName, Version version, VersionRequired versionRequired) - { - if ( versionRequired != null ) - { - int majorRequired = versionRequired.major(); - int minorRequired = versionRequired.minor(); - - if ( majorRequired < 0 ) // no real version requirement - return; - - int majorPresent = -1; - int minorPresent = -1; - if ( version != null ) - { - majorPresent = version.major(); - minorPresent = version.minor(); - - if ( majorRequired <= majorPresent && - (minorRequired < 0 || minorRequired <= minorPresent) ) - { - // Version requirement is satisfied - return; - } - } - - // - // Version requirement failed - // - throw new ControlException( "Control extension " + intfName + " fails version requirement: requires interface version " + - majorRequired + "." + minorRequired + ", found interface version " + - majorPresent + "." + minorPresent + "." ); - } - } - - - /** - * Implementation of the Java serialization writeObject method - */ - private synchronized void writeObject(ObjectOutputStream oos) - throws IOException - { - if (_control != null) - { - // - // If the implementation class is marked as transient/stateless, then reset the - // reference to it prior to serialization. A new instance will be created by - // ensureControl() upon first use after deserialization. - // If the implementation class is not transient, then invoke the ImplInitializer - // resetServices method to reset all contextual service references to null, as - // contextual services should never be serializated and always reassociated on - // deserialization. - // - ControlImplementation implAnnot = (ControlImplementation)_implClass.getAnnotation(ControlImplementation.class); - assert implAnnot != null; - if (implAnnot.isTransient()) - { - _control = null; - } - else - { - getImplInitializer().resetServices(this, _control); - _hasServices = false; - } - } - - oos.defaultWriteObject(); - } - - /** - * Called during XMLDecoder reconstruction of a ControlBean. - */ - public void decodeImpl(Object impl) - { - if (impl != _control) - throw new ControlException("Cannot change implementation"); - } - - /** - * Internal method used to lookup a ControlBeanContextFactory. This factory is used to create the - * ControlBeanContext object for this ControlBean. The factory is discoverable from either the containing - * ControlBeanContext object or from the environment. If the containing CBC object exposes a - * contextual service of type {@link ControlBeanContextFactory}, the factory returned from this will - * be used to create a ControlBeanContext object. - * - * @param context - * @return the ControlBeanContextFactory discovered in the environment or a default one if no factory is configured - */ - private ControlBeanContextFactory lookupControlBeanContextFactory - (org.apache.beehive.controls.api.context.ControlBeanContext context) { - - // first, try to find the CBCFactory from the container - if(context != null) { - ControlBeanContextFactory cbcFactory = context.getService(ControlBeanContextFactory.class, null); - - if(cbcFactory != null) { - return cbcFactory; - } - } - - // Create the context that acts as the BeanContextProxy for this bean (the context that this bean _defines_). - try - { - DiscoverClass discoverer = new DiscoverClass(); - Class factoryClass = - discoverer.find(ControlBeanContextFactory.class, DefaultControlBeanContextFactory.class.getName()); - - return (ControlBeanContextFactory)factoryClass.newInstance(); - } - catch (Exception e) { - throw new ControlException("Exception creating ControlBeanContext", e); - } - } - - /** - * Retrieves interceptor instances, creates them lazily. - */ - protected Interceptor ensureInterceptor( String n ) - { - Interceptor i = null; - if ( _interceptors == null ) - { - _interceptors = new HashMap(); - } - else - { - i = _interceptors.get( n ); - } - - if ( i == null ) - { - try - { - i = (Interceptor) getControlService( getControlBeanContext().getClassLoader().loadClass( n ), null ); - } - catch ( Exception e ) - { - // Couldn't instantiate the desired service; usually this is because the service interface itself - // isn't present on this system at runtime (ClassNotFoundException), or if the container of the - // control didn't registers the service. - - /* TODO log a message here to that effect, but just swallow the exception for now. */ - } - finally - { - // We want to always return an interceptor, so if we can't get the one we want, we'll substitute - // a "null" interceptor that does nothing. - if ( i == null) - i = new NullInterceptor(); - - _interceptors.put( n, i ); - } - } - return i; - } - - /** - * The "null" interceptor that does nothing. Used when a specific interceptor - * is unavailable at runtime. - */ - static private class NullInterceptor - implements Interceptor - { - public void preInvoke( org.apache.beehive.controls.api.bean.ControlBean cb, Method m, Object [] args ) {} - public void postInvoke( org.apache.beehive.controls.api.bean.ControlBean cb, Method m, Object [] args, Object retval, Throwable t) {} - public void preEvent( org.apache.beehive.controls.api.bean.ControlBean cb, Class eventSet, Method m, Object [] args) {} - public void postEvent( org.apache.beehive.controls.api.bean.ControlBean cb, Class eventSet, Method m, Object [] args, Object retval, Throwable t ) {} - } - - /** BEGIN unsynchronized fields */ - - /** - * The following fields are initialized in the constructor and never subsequently changed, - * so they are safe for unsynchronized read access - */ - - /** - * The control implementation class bound to this ControlBean - */ - protected Class _implClass; - - /** - * The threading policy associated with the control implementation wrapped by this - * ControlBean. Initialized to MULTI_THREADED in order to assume multi-threadedness - * until a bean is associated with a specific (potentially single-threaded) implementation. - */ - transient private ThreadingPolicy _threadingPolicy = ThreadingPolicy.MULTI_THREADED; - - /** - * Contains the per-instance properties set for this ControlBean. - */ - private BeanPropertyMap _properties; - - /** END unsynchronized fields */ - - /* BEGIN synchronized fields */ - - /* - * The following fields must be: - * 1) only written in synchronized methods or (unsynchronized) constructors - * 2) only read in synchronized methods or methods that are safe wrt the values changing during - * execution. - */ - - /** - * The control implementation instance wrapped by this ControlBean - */ - private Object _control; - - /** - * The control bean context instance associated with this ControlBean - */ - private ControlBeanContext _cbc; - - /** - * An ImplInitializer instances used to initialize/reset the state of the associated - * implementation instance. - */ - transient private ImplInitializer _implInitializer; - - /** - * Indicates whether the contextual services associated with the bean have been - * fully initialized. - */ - transient private boolean _hasServices = false; - - /** - * Used to guarantee single threaded invocation when required. If the - * outer container provides the guarantee or the implementation itself - * is threadsafe, then the value will be null. - */ - transient private Semaphore _invokeLock; - - /** - * This field manages PropertyChangeListeners (if supporting bound properties). - */ - private PropertyChangeSupport _changeSupport; - - /** - * This field manages VetoabbleChangeListeners (if supporting constrained properties) - */ - private VetoableChangeSupport _vetoSupport; - - /** END synchronized fields */ - - /** - * The (context relative) control ID associated with this instance - */ - private String _localID; - - /** - * The public control interface associated with this ControlBean - */ - private Class _controlIntf; - - /** - * This field manages the register listener list(s) associated with event set interfaces - * for the ControlBean. The value objects are either UnicastEventNotifier or EventNotifier - * instances, depending upon whether the associated EventSet interface is unicast or - * multicast. - */ - private HashMap _notifiers = new HashMap(); - - /** - * Maintains the list of callback event listeners (if any) for this ControlBean. - */ - transient private Vector _invokeListeners; - - /** - * HashMap to hold interceptor impl instances. - * Populated lazily. Maps interceptor interface name to impl. - */ - transient private HashMap _interceptors; -} diff --git a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/bean/ControlBeanContext.java b/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/bean/ControlBeanContext.java deleted file mode 100644 index ec2db56..0000000 --- a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/bean/ControlBeanContext.java +++ /dev/null @@ -1,1120 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.runtime.bean; - -import java.beans.PropertyChangeEvent; -import java.beans.PropertyVetoException; -import java.beans.PropertyChangeListener; -import java.beans.VetoableChangeListener; -import java.beans.beancontext.BeanContext; -import java.beans.beancontext.BeanContextServiceRevokedEvent; -import java.beans.beancontext.BeanContextServiceProvider; -import java.beans.beancontext.BeanContextServices; -import java.beans.beancontext.BeanContextChild; -import java.beans.beancontext.BeanContextServiceRevokedListener; -import java.beans.beancontext.BeanContextServicesListener; -import java.beans.beancontext.BeanContextMembershipListener; -import java.beans.beancontext.BeanContextServiceAvailableEvent; -import java.lang.annotation.Annotation; -import java.lang.reflect.AnnotatedElement; -import java.lang.reflect.Field; -import java.lang.reflect.Method; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.Map; -import java.util.Set; -import java.util.TooManyListenersException; -import java.util.Vector; -import java.util.Collection; -import java.io.IOException; -import java.io.InputStream; -import java.io.ObjectOutputStream; -import java.io.ObjectInputStream; -import java.net.URL; - -import org.apache.beehive.controls.api.ControlException; -import org.apache.beehive.controls.api.context.ControlHandle; -import org.apache.beehive.controls.api.properties.AnnotatedElementMap; -import org.apache.beehive.controls.api.properties.BeanPropertyMap; -import org.apache.beehive.controls.api.properties.PropertyMap; -import org.apache.beehive.controls.api.properties.PropertySet; -import org.apache.beehive.controls.api.properties.PropertySetProxy; - -/** - * The ControlBeanContext implements the basic BeanContextServices implementation - * for ControlBeans. - * - * It provides several basic functions: - * - it defines the generic services that are available for all control containers - * - it acts as the base class for other container service implementations - * - it acts as the BeanContextServicesRevokedListener when an associated control - * bean has lost access to services. - */ -public class ControlBeanContext - implements org.apache.beehive.controls.api.context.ControlBeanContext, - java.beans.PropertyChangeListener, - java.beans.VetoableChangeListener, - java.io.Serializable -{ - /** - * Creates a new ControlBeanContext instance associated with a specific control bean. If the - * ControlBean is null, this ControlBeanContext object represents a top-level Control - * container. This constructor uses the default implementation of the - * {@link java.beans.beancontext.BeanContextServices} interface from the JDK. - * - * @param bean The control bean that contains/scopes the ControlBeanContext. If null, it means the - * ControlBeanContext is for a top-level container. - */ - protected ControlBeanContext(ControlBean bean) - { - this(bean, DEFAULT_BEAN_CONTEXT_SERVICES_FACTORY); - } - - /** - * Creates a new ControlBeanContext instance associated with a specific control bean. If the - * ControlBean is null, this ControlBeanContext object represents a top-level Control - * container. This constructor uses the beanContextServicesDelegate instance as the - * implementation of the {@link java.beans.beancontext.BeanContextServices} interface. - * - * @param bean The control bean - * @param beanContextServicesFactory A factory that can be used to create the BeanContextServicesFactory object - * that implements support for the {@link BeanContextServices} interface. - */ - protected ControlBeanContext(ControlBean bean, BeanContextServicesFactory beanContextServicesFactory) { - super(); - - _bean = bean; - - // ensure that there is a valid factory for creating the BCS delegate - if(beanContextServicesFactory == null) - beanContextServicesFactory = DEFAULT_BEAN_CONTEXT_SERVICES_FACTORY; - - _beanContextServicesDelegate = beanContextServicesFactory.instantiate(this); - initialize(); - } - - /** - * Called by BeanContextSupport superclass during construction and deserialization to - * initialize subclass transient state - */ - public void initialize() - { - // - // Register the ControlBeanContext provider on all new context instances. - // - addService(org.apache.beehive.controls.api.context.ControlBeanContext.class, CONTROL_BEAN_CONTEXT_PROVIDER); - } - - /** - * Implements the - * {@link java.beans.beancontext.BeanContextServiceRevokedListener#serviceRevoked(java.beans.beancontext.BeanContextServiceRevokedEvent)} - * method. This is called if the associated {@link ControlBean} has requested a service that is being subsequently - * revoked. - */ - public void serviceRevoked(BeanContextServiceRevokedEvent bcsre) - { - // - // This can happen, if the control is disassociated from a parent context that is - // providing services. - // - } - - /** - * Overrides the {@link java.beans.beancontext.BeanContextChild#setBeanContext(java.beans.beancontext.BeanContext)} - * method. This hook is used to perform additional processing that needs to occur when the control is associated - * with a new nesting context. - */ - public synchronized void setBeanContext(BeanContext beanContext) - throws PropertyVetoException - { - ControlBeanContext cbcs = null; - - if (beanContext != null) - { - // - // ControlBeans can only be nested in context service instances that derive - // from ControlBeanContext. - // - if (!(beanContext instanceof ControlBeanContext)) - { - PropertyChangeEvent pce = new PropertyChangeEvent(_bean, "beanContext", getBeanContext(), beanContext); - throw new PropertyVetoException("Context does not support nesting controls: " + - beanContext.getClass(), pce); - } - - cbcs = (ControlBeanContext)beanContext; - } - - - _beanContextServicesDelegate.setBeanContext(beanContext); - - resetControlID(); - - _hasSingleThreadedParent = cbcs != null ? cbcs.isSingleThreadedContainer() : false; - - // - // Notify the bean that its context (container) has been set. - // - if (_bean != null) - _bean.setBeanContext(beanContext); - } - - /** - * The NameGenerator class is a simple helper class that creates new unique names based - * upon a base prefix and an incrementing counter - */ - private static class NameGenerator implements java.io.Serializable - { - NameGenerator(String namePrefix) - { - _namePrefix = namePrefix; - } - - /** - * Get the next unique name - */ - public synchronized String next() - { - return _namePrefix + _nextIndex++; - } - - int _nextIndex = 0; - String _namePrefix; - } - - /** - * Returns a new NameGenerator instance based upon a particular naming - * prefix. - */ - private NameGenerator getNameGenerator(String namePrefix) - { - synchronized(this) - { - if (_nameGenerators == null) - _nameGenerators = new HashMap(); - - NameGenerator nameGenerator = _nameGenerators.get(namePrefix); - if (nameGenerator == null) - { - nameGenerator = new NameGenerator(namePrefix); - _nameGenerators.put(namePrefix, nameGenerator); - } - return nameGenerator; - } - } - - /** - * Generates a new unique control ID for an instance of the target class - */ - public String generateUniqueID(Class clazz) - { - String namePrefix = clazz.getName(); - int dotIndex = namePrefix.lastIndexOf('.'); - if (dotIndex > 0) - namePrefix = namePrefix.substring(dotIndex+1); - NameGenerator nameGenerator = getNameGenerator(namePrefix); - return nameGenerator.next(); - } - - /** - * Overrides the BeanContextSupport.add() method to perform additional validation - * that is unique for ControlBeans containers. - */ - public boolean add(Object targetChild) - { - // - // The context can contain ControlBeans and other types of objects, such as a control - // factory. - // - String beanID = null; - if (targetChild instanceof ControlBean) - { - ControlBean bean = (ControlBean)targetChild; - beanID = bean.getLocalID(); - - // - // The bean is anonymous, so we must generate a new unique name within this context. - // - if (beanID == null) - { - beanID = generateUniqueID(bean.getClass()); - bean.setLocalID(beanID); - } - - ControlBean existingBean = (ControlBean)_childMap.get(beanID); - if (existingBean != null && existingBean != targetChild) - { - throw new IllegalArgumentException("Attempting to add control with duplicate ID: " + - beanID); - } - } - - boolean added = _beanContextServicesDelegate.add(targetChild); - if (added && beanID != null) - _childMap.put(beanID, targetChild); - - return added; - } - - /** - * Overrides the BeanContextSupport.remove() method to perform additional post-processing - * on child removal. - */ - public boolean remove(Object targetChild) - { - assert targetChild instanceof ControlBean; // should be guaranteed above - boolean removed = _beanContextServicesDelegate.remove(targetChild); - - if (removed) - { - // - // Remove from the locally maintained child map - // - String localID = ((ControlBean)targetChild).getLocalID(); - Object removedChild = _childMap.remove(localID); - assert removedChild == targetChild; // just being safe - } - return removed; - } - - /** - * Returns a ControlBean instance nested the current BeanContext. - * @param id the identifier for the target control, relative to the current - * context. - */ - public ControlBean getBean(String id) - { - // If no control id separator found, the bean is a direct child of this context - int delim = id.indexOf(org.apache.beehive.controls.api.bean.ControlBean.IDSeparator); - if (delim < 0) // child is a direct descendent - return (ControlBean)_childMap.get(id); - - // Find the child referenced by the first element in the path - ControlBean bean = (ControlBean)_childMap.get(id.substring(0, delim)); - if (bean == null) - return bean; - - // Get the BeanContext associated with the found child, and then ask it - // to resolve the rest of the path - return bean.getBeanContextProxy().getBean(id.substring(delim+1)); - } - - /** - * Returns the ControlBean associated directly with the ControlBeanContext. If the - * context represents a top-level container, will return null. - */ - public ControlBean getControlBean() - { - return _bean; - } - - public synchronized boolean hasSingleThreadedParent() - { - return _hasSingleThreadedParent; - } - - /** - * Returns true if this container associated with this context service enforces - * single-threaded invocation, false otherwise. - * - * This MUST be overridden by container-specific subclasses in order to change - * the default behavior. If a single-threaded container intends to guarantee - * single-threaded behavior (such as the EJB container), this should return true. - */ - public synchronized boolean isSingleThreadedContainer() - { - return ( hasSingleThreadedParent() || ( _bean != null && _bean.hasSingleThreadedImpl() )); - } - - /** - * The initializeControl method is invoked when the implementation instance associated - * with the context has been instantiated and initialized. - */ - public void initializeControl() - { - // - // Deliver the onCreate event to any register lifecycle listeners - // - if (_lifeCycleListeners != null) - { - for (LifeCycle lifeCycleListener : _lifeCycleListeners) { - lifeCycleListener.onCreate(); - } - } - } - - /** - * Returns the PropertyMap containing default properties for an AnnotatedElement - * in the current context. The initialization of PropertyMap binding is always - * done by delegating to a {@link ControlContainerContext}, enabling containers to implement - * property binding mechanisms (such as external config) that may override the values - * contained within the element annotations. - */ - public PropertyMap getAnnotationMap(AnnotatedElement annotElem) - { - ControlBeanContext beanContext = this; - while (beanContext != null) - { - // REVIEW: should ControlContainerContext-derived classes override getBeanAnnotationMap? Not sure - // that name makes sense, and perhaps it shouldn't take a ControlBean. - if (beanContext instanceof ControlContainerContext) - return beanContext.getBeanAnnotationMap(_bean, annotElem); - beanContext = (ControlBeanContext)beanContext.getBeanContext(); - } - - // No ControlContainerContext was found, so just use the default implementation - return getBeanAnnotationMap(_bean, annotElem); - } - - /** - * The default implementation of getBeanAnnotationMap. This returns a map based purely - * upon annotation reflection - */ - protected PropertyMap getBeanAnnotationMap(ControlBean bean, AnnotatedElement annotElem) - { - PropertyMap map = new AnnotatedElementMap(annotElem); - - // REVIEW: is this the right place to handle the general control client case? - if ( bean != null ) - setDelegateMap( map, bean, annotElem ); - - return map; - } - - static protected void setDelegateMap( PropertyMap map, ControlBean bean, AnnotatedElement annotElem ) - { - // - // If building an annotation map for a method or field, we want to delegate back - // to the base control type. - // - Class annotClass = null; - if (annotElem instanceof Field) - { - annotClass = ((Field)annotElem).getType(); - } - else if (annotElem instanceof Method) - { - annotClass = bean.getControlInterface(); - } - - if (annotClass != null) - { - PropertyMap delegateMap = bean.getAnnotationMap(annotClass); - map.setDelegateMap(delegateMap); - } - } - - // - // ControlBeanContext.getControlInterface - // - public Class getControlInterface() - { - return _bean.getControlInterface(); - } - - // - // ControlBeanContext.getControlPropertySet - // - public T getControlPropertySet(Class propertySet) - { - PropertyMap map = _bean.getPropertyMap(); - - // - // Optional properties are not exposed to clients using traditional JavaBean - // setters/getters (because there is way to represent an 'unset' value); for - // these properties, the impl can tell if the PropertySet is unset because - // this method will return null. - // - if (!map.containsPropertySet(propertySet)) - { - PropertySet psAnnot = propertySet.getAnnotation(PropertySet.class); - if (psAnnot.optional()) - return null; - } - - // - // Construct a new PropertySet proxy instance that derives its values from - // the bean property map. - // - return PropertySetProxy.getProxy(propertySet, map); - } - - // - // ControlBeanContext.getMethodPropertySet - // - public T getMethodPropertySet(Method m, Class propertySet) - { - PropertyMap map = _bean.getAnnotationMap(m); - - // - // Optional properties are not exposed to clients using traditional JavaBean - // setters/getters (because there is way to represent an 'unset' value); for - // these properties, the impl can tell if the PropertySet is unset because - // this method will return null. - // - if (!map.containsPropertySet(propertySet)) - { - PropertySet psAnnot = propertySet.getAnnotation(PropertySet.class); - if (psAnnot.optional()) - return null; - } - - // - // Construct a new PropertySet proxy instance that derives its values from - // the method property map. - // - return PropertySetProxy.getProxy(propertySet, _bean.getAnnotationMap(m)); - } - - // - // ControlBeanContext.getParameterPropertySet - // - public T getParameterPropertySet(Method m, int i, Class propertySet) - throws IllegalArgumentException, IndexOutOfBoundsException - { - if (i >= m.getParameterTypes().length) - throw new IndexOutOfBoundsException("Invalid parameter index for method:" + m); - - // todo: Currently, there is no external override mechanism for method parameters - Annotation [] paramAnnots = m.getParameterAnnotations()[i]; - for (Annotation paramAnnot : paramAnnots) - if (propertySet.isAssignableFrom(paramAnnot.getClass())) - return (T) paramAnnot; - - return null; - } - - // - // ControlBeanContext.getParameterNames - // - public String [] getParameterNames(Method m) - throws IllegalArgumentException - { - return _bean.getParameterNames(m); - } - - // - // ControlBeanContext.getNamedParameterValue - // - public Object getParameterValue(Method m, String parameterName, Object [] parameters) - throws IllegalArgumentException - { - String [] names = getParameterNames(m); - - // Validate the input parameter array - if (parameters.length != names.length) - throw new IllegalArgumentException("Expected " + names.length + " parameters," + - "Found " + parameters.length); - - // Finding the index of the matching parameter name - int i = 0; - while (i < names.length) - { - if (names[i].equals(parameterName)) - break; - i++; - } - if (i == names.length) - throw new IllegalArgumentException("No method parameter with name: " + parameterName); - - // Return the parameter value at the matched index - return parameters[i]; - } - - // - // ControlBeanContext.getPropertyMap - // - public PropertyMap getControlPropertyMap() - { - // - // Return a wrapped copy of the original bean property map, so any edits - // don't impact the bean properties. - // - return new BeanPropertyMap(_bean.getPropertyMap()); - } - - // - // ControlBeanContext.getService - // - public T getService(Class serviceClass, Object selector) - { - // - // If the requested service is a ControlBeanContext instance, the current instance - // can be returned. - // - if (serviceClass.equals(org.apache.beehive.controls.api.context.ControlBeanContext.class)) - return (T)this; - - // - // The parent BeanContext is responsible for providing requested services. If - // no parent context is available or it is does not manage services, then no service. - // - BeanContext bc = getBeanContext(); - if (bc == null || !(bc instanceof BeanContextServices)) - return null; - - // - // Call getService on the parent context, using this bean as the requestor and the - // this context as the child context and ServicesRevoked event listener parameters. - // - try - { - return (T)((BeanContextServices)bc).getService(this, _bean, serviceClass, selector, this); - } - catch (TooManyListenersException tmle) - { - // This would be highly unusual... it implies that the registration for service - // revocation notifications failed for some reason. - throw new ControlException("Unable to register for service events", tmle); - } - } - - // - // ControlBeanContext.getControlHandle - // - public ControlHandle getControlHandle() - { - // - // Find the associated ControlContainerContext, which provides a container-specific - // implementation of ControlHandle - // - ControlBeanContext beanContext = this; - while (beanContext != null && !(beanContext instanceof ControlContainerContext)) - beanContext = (ControlBeanContext)beanContext.getBeanContext(); - - if (beanContext == null) - return null; - - // - // Ask the container for a ControlHandle instance referencing the target bean - // - return ((ControlContainerContext)beanContext).getControlHandle(_bean); - } - - // - // ControlBeanContext.getClassLoader - // - public java.lang.ClassLoader getClassLoader() - { - return getControlInterface().getClassLoader(); - } - - // - // ControlBeanContext.addLifeCycleListener - // - synchronized public void addLifeCycleListener(LifeCycle listener) - { - if (_lifeCycleListeners == null) - { - _lifeCycleListeners = new Vector(); - - // - // Since bound/constrained property changes are exposed as lifecycle events, we - // need to register ourselves as a listener for these events the first time a - // lifecycle listener is added. - // - _bean.getPropertyChangeSupport().addPropertyChangeListener(this); - _bean.getVetoableChangeSupport().addVetoableChangeListener(this); - } - _lifeCycleListeners.addElement(listener); - } - - // - // ControlBeanContext.removeLifeCycleListener - // - synchronized public void removeLifeCycleListener(LifeCycle listener) - { - if (_lifeCycleListeners != null) - _lifeCycleListeners.removeElement(listener); - } - - // - // PropertyChangeListener.propertyChange - // - public void propertyChange(PropertyChangeEvent pce) - { - if (_lifeCycleListeners != null) - { - for (LifeCycle lifeCycleListener : _lifeCycleListeners) { - lifeCycleListener.onPropertyChange(pce); - } - } - } - - // - // VetoableChangeListener.vetoableChange - // - public void vetoableChange(PropertyChangeEvent pce) throws PropertyVetoException - { - if (_lifeCycleListeners != null) - { - for (LifeCycle lifeCycleListener : _lifeCycleListeners) { - lifeCycleListener.onVetoableChange(pce); - } - } - } - - /* package */ String getControlID() - { - if (_controlID != null || _bean == null) - return _controlID; - - // Initially set to the local beans relative ID - String id = _bean.getLocalID(); - - // If there is a parent context, prepend its ID and the ID separator - BeanContext bc = getBeanContext(); - if (bc != null && bc instanceof ControlBeanContext) - { - String parentID = ((ControlBeanContext)bc).getControlID(); - if (parentID != null) - { - id = parentID + - org.apache.beehive.controls.api.bean.ControlBean.IDSeparator + - id; - } - } - - // Cache the computed value - _controlID = id; - - return id; - } - - /** - * Resets the composite control ID for this context and all children beneath it. This - * can be used to invalidate cached values when necessary (for example, when a context - * is reparented). - */ - private void resetControlID() - { - _controlID = null; - for (Object child : this) { - if (child instanceof ControlBeanContext) - ((ControlBeanContext) child).resetControlID(); - } - } - - // - // BeanContextServices.getCurrentServiceClasses - // Override the default implementation of getCurrentServiceClasses inherited from - // java.beans.beancontext.BeanContextServicesSuppport. The reason for this is a bug/ - // flaw in its underlying implementation. It does not include any services exposed - // by any nesting contexts. This is contradictory to the implementation of hasService() - // and getService() which do delegate up to a parent context to find services if not - // available on the local context. This means hasService() could return 'true' for a - // service that isn't returned by getCurrentServiceClasses(), which seems like a bug. - // - synchronized public Iterator getCurrentServiceClasses() - { - Set classSet = new HashSet(); - BeanContextServices bcs = _beanContextServicesDelegate; - - while (bcs != null) - { - Iterator iter = bcs.getCurrentServiceClasses(); - while (iter.hasNext()) - classSet.add(iter.next()); - - // Go up to the parent, if it is a service provider as well - BeanContext bc = getBeanContext(); - if (bc instanceof BeanContextServices && bcs != bc) - bcs = (BeanContextServices)bc; - else - bcs = null; - } - return classSet.iterator(); - } - - // - // BeanContextServices.getCurrentServiceSelectors - // Override getCurrentServiceSelectors for the same reason as above - // - public Iterator getCurrentServiceSelectors(Class serviceClass) - { - if (hasService(serviceClass)) - return _beanContextServicesDelegate.getCurrentServiceSelectors(serviceClass); - - BeanContext bc = getBeanContext(); - if (bc instanceof BeanContextServices) - return ((BeanContextServices)bc).getCurrentServiceSelectors(serviceClass); - - return null; - } - - private synchronized void writeObject(ObjectOutputStream oos) - throws IOException { - oos.defaultWriteObject(); - if(_beanContextServicesDelegate instanceof java.beans.beancontext.BeanContextSupport) { - ((java.beans.beancontext.BeanContextSupport)_beanContextServicesDelegate).writeChildren(oos); - } else if(_beanContextServicesDelegate instanceof org.apache.beehive.controls.runtime.webcontext.ControlBeanContextSupport) { - ((org.apache.beehive.controls.runtime.webcontext.ControlBeanContextSupport)_beanContextServicesDelegate).writeChildren(oos); - } - else assert false; - } - - private synchronized void readObject(ObjectInputStream ois) - throws IOException, ClassNotFoundException { - ois.defaultReadObject(); - - if(_beanContextServicesDelegate instanceof java.beans.beancontext.BeanContextSupport) { - ((java.beans.beancontext.BeanContextSupport)_beanContextServicesDelegate).readChildren(ois); - } else if(_beanContextServicesDelegate instanceof org.apache.beehive.controls.runtime.webcontext.ControlBeanContextSupport) { - ((org.apache.beehive.controls.runtime.webcontext.ControlBeanContextSupport)_beanContextServicesDelegate).readChildren(ois); - } - else assert false; - - // Re-initialize a deserialized control hierarchy. - initialize(); - } - - protected BeanContextServicesFactory getBeanContextServicesFactory() { - return DEFAULT_BEAN_CONTEXT_SERVICES_FACTORY; - } - - public boolean equals(Object o) { - /* todo: make sure this logic is right / sufficient */ - if (this == o) - return true; - - if(!(o instanceof org.apache.beehive.controls.api.context.ControlBeanContext)) - return false; - - return o instanceof ControlBeanContext && - _beanContextServicesDelegate.equals(((ControlBeanContext)o)._beanContextServicesDelegate); - } - - public int hashCode() { - /* todo: make sure this logic is right / sufficient */ - int result; - result = (_bean != null ? _bean.hashCode() : 0); - result = 31 * result + (_beanContextServicesDelegate != null ? _beanContextServicesDelegate.hashCode() : 0); - return result; - } - - /* -------------------------------------------------------------------------- - - Implementation of java.beans.beancontext.BeanContextServices - - -------------------------------------------------------------------------- */ - public boolean addService(Class serviceClass, BeanContextServiceProvider serviceProvider) { - return _beanContextServicesDelegate.addService(serviceClass, serviceProvider); - } - - public void revokeService(Class serviceClass, BeanContextServiceProvider serviceProvider, boolean revokeCurrentServicesNow) { - _beanContextServicesDelegate.revokeService(serviceClass, serviceProvider, revokeCurrentServicesNow); - } - - public boolean hasService(Class serviceClass) { - return _beanContextServicesDelegate.hasService(serviceClass); - } - - public Object getService(BeanContextChild child, Object requestor, Class serviceClass, Object serviceSelector, BeanContextServiceRevokedListener bcsrl) throws TooManyListenersException { - return _beanContextServicesDelegate.getService(child, requestor, serviceClass, serviceSelector, bcsrl); - } - - public void releaseService(BeanContextChild child, Object requestor, Object service) { - _beanContextServicesDelegate.releaseService(child, requestor, service); - } - - public void addBeanContextServicesListener(BeanContextServicesListener bcsl) { - _beanContextServicesDelegate.addBeanContextServicesListener(bcsl); - } - - public void removeBeanContextServicesListener(BeanContextServicesListener bcsl) { - _beanContextServicesDelegate.removeBeanContextServicesListener(bcsl); - } - - public Object instantiateChild(String beanName) throws IOException, ClassNotFoundException { - return _beanContextServicesDelegate.instantiateChild(beanName); - } - - public InputStream getResourceAsStream(String name, BeanContextChild bcc) throws IllegalArgumentException { - return _beanContextServicesDelegate.getResourceAsStream(name, bcc); - } - - public URL getResource(String name, BeanContextChild bcc) throws IllegalArgumentException { - return _beanContextServicesDelegate.getResource(name, bcc); - } - - public void addBeanContextMembershipListener(BeanContextMembershipListener bcml) { - _beanContextServicesDelegate.addBeanContextMembershipListener(bcml); - } - - public void removeBeanContextMembershipListener(BeanContextMembershipListener bcml) { - _beanContextServicesDelegate.removeBeanContextMembershipListener(bcml); - } - - public BeanContext getBeanContext() { - return _beanContextServicesDelegate.getBeanContext(); - } - - public void addPropertyChangeListener(String name, PropertyChangeListener pcl) { - _beanContextServicesDelegate.addPropertyChangeListener(name, pcl); - } - - public void removePropertyChangeListener(String name, PropertyChangeListener pcl) { - _beanContextServicesDelegate.removePropertyChangeListener(name, pcl); - } - - public void addVetoableChangeListener(String name, VetoableChangeListener vcl) { - _beanContextServicesDelegate.addVetoableChangeListener(name, vcl); - } - - public void removeVetoableChangeListener(String name, VetoableChangeListener vcl) { - _beanContextServicesDelegate.removeVetoableChangeListener(name, vcl); - } - - public int size() { - return _beanContextServicesDelegate.size(); - } - - public boolean isEmpty() { - return _beanContextServicesDelegate.isEmpty(); - } - - public boolean contains(Object o) { - return _beanContextServicesDelegate.contains(o); - } - - public Iterator iterator() { - return _beanContextServicesDelegate.iterator(); - } - - public Object[] toArray() { - return _beanContextServicesDelegate.toArray(); - } - - public Object[] toArray(Object[] a) { - return _beanContextServicesDelegate.toArray(a); - } - - public boolean containsAll(Collection c) { - return _beanContextServicesDelegate.containsAll(c); - } - - public boolean addAll(Collection c) { - return _beanContextServicesDelegate.addAll(c); - } - - public boolean removeAll(Collection c) { - return _beanContextServicesDelegate.removeAll(c); - } - - public boolean retainAll(Collection c) { - return _beanContextServicesDelegate.retainAll(c); - } - - public void clear() { - _beanContextServicesDelegate.clear(); - } - - public void setDesignTime(boolean designTime) { - _beanContextServicesDelegate.setDesignTime(designTime); - } - - public boolean isDesignTime() { - return _beanContextServicesDelegate.isDesignTime(); - } - - public boolean needsGui() { - return _beanContextServicesDelegate.needsGui(); - } - - public void dontUseGui() { - _beanContextServicesDelegate.dontUseGui(); - } - - public void okToUseGui() { - _beanContextServicesDelegate.okToUseGui(); - } - - public boolean avoidingGui() { - return _beanContextServicesDelegate.avoidingGui(); - } - - public void serviceAvailable(BeanContextServiceAvailableEvent bcsae) { - _beanContextServicesDelegate.serviceAvailable(bcsae); - } - - /* -------------------------------------------------------------------------- - - Static / deprecated methods. - - -------------------------------------------------------------------------- */ - - /** - * Applies externally defined (via INTERCEPTOR_CONFIG_FILE) ordering priority for - * controls interceptor services. - * - * @param interceptors - * @return String[] - * @deprecated Use {@link InterceptorUtils#prioritizeInterceptors(String[])} instead. This method will - * be removed in the next point release. - */ - public static String[] prioritizeInterceptors( String [] interceptors ) { - return InterceptorUtils.prioritizeInterceptors(interceptors); - } - - /** - * Returns the default binding based entirely upon annotations or naming conventions. - * @param controlIntf the control interface class - * @return the class name of the default control implementation binding - * @deprecated Use {@link ControlUtils#getDefaultControlBinding(Class)} insated. This method will be - * removed in the next point release. - */ - public static String getDefaultControlBinding(Class controlIntf) - { - return ControlUtils.getDefaultControlBinding(controlIntf); - } - - /** - * Implements the default control implementation binding algorithm ( + "Impl" ). See - * documentation for the org.apache.beehive.controls.api.bean.ControlInterface annotation. - * - * @param implBinding the value of the defaultBinding attribute returned from a ControlInterface annotation - * @param controlClass the actual name of the interface decorated by the ControlInterface annotation - * @return the resolved defaultBinding value - * @deprecated Use {@link ControlUtils#resolveDefaultBinding(String, String)} insated. This method - * will be removed in the next point release. - */ - public static String resolveDefaultBinding( String implBinding, String controlClass ) - { - return ControlUtils.resolveDefaultBinding(implBinding, controlClass); - } - - /** - * The ControlBeanContextProvider inner class acts as a single BeanContext service - * provider for the ControlBeanContext service class. The implementation is simple, - * because the runtime ControlBeanContext implementation class directly implements - * this interface. - */ - private static class ControlBeanContextProvider implements BeanContextServiceProvider - { - // - // BeanContextServiceProvider.getService() - // - public Object getService(BeanContextServices bcs, Object requestor, Class serviceClass, - Object serviceSelector) - { - // - // Contextual services for a ControlBean is provided by the peer context - // instance. - // - if (requestor instanceof ControlBean) - return ((ControlBean)requestor).getControlBeanContext(); - - return null; - } - - // - // BeanContextServiceProvider.releaseService() - // - public void releaseService(BeanContextServices bcs, Object requestor, Object service) - { - // noop, because context exists whether referenced or not - } - - // - // BeanContextServiceProvider.getContextServiceSelectors() - // - public Iterator getCurrentServiceSelectors(BeanContextServices bcs, Class serviceClass) - { - return null; // no selectors - } - } - - /*package*/ static abstract class BeanContextServicesFactory { - protected abstract BeanContextServices instantiate(ControlBeanContext controlBeanContext); - } - - private static final class DefaultBeanContextServicesFactory - extends BeanContextServicesFactory { - protected BeanContextServices instantiate(ControlBeanContext controlBeanContext) { - return new java.beans.beancontext.BeanContextServicesSupport(controlBeanContext); - } - } - - /** - * A singleton instance of the ControlBeanContextProvider class is that will be registered - * on all ControlBeanContext instances. The provider can be a singleton because it is - * completely stateless and thread-safe. - */ - private static final ControlBeanContextProvider CONTROL_BEAN_CONTEXT_PROVIDER = - new ControlBeanContextProvider(); - - /** - * A singleton instance of the BeanContextServicesFactory class that can be implemented by subclasses - * to allow top-level Control containers to provide their own implementations of the - * {@link java.beans.beancontext.BeanContextServices} interface. This field is considered an implementation - * detail and should not be referenced directly. - */ - private static final BeanContextServicesFactory DEFAULT_BEAN_CONTEXT_SERVICES_FACTORY = - new DefaultBeanContextServicesFactory(); - - /** - * The ControlBean instance that this context is providing services for. This value can - * be null, if the context instance is associated with top-level (non-control) context. - */ - private ControlBean _bean; - - /** - * Indicates whether this context's parent guarantees single-threaded behaviour. - */ - private boolean _hasSingleThreadedParent = false; - - /** - * Maps children by the local (relative) ID of the child to the actual bean instance. - * This needs to be synchronized, because adds/removes/gets are not necessarily guaranteed - * to happen within the scope of the global hierarchy lock. It would be relatively easy - * to synchronize add/remove, since setBeanContext on the child is inside this lock scope, - * but gets on the map are another story. - */ - private Map _childMap = Collections.synchronizedMap(new HashMap()); - - /** - * Maintains a set of NameGenerators (for control ID generation) keyed by a - * base prefix. The map itself is lazily constructed, so there is minimal - * overhead of no id generation is needed in this context. - */ - private Map _nameGenerators; - - /** - * Maintains the list of lifecycle event listeners (if any) for this context. - */ - private transient Vector _lifeCycleListeners; - - /** - * Caches the full composite control ID, that includes the entire path from the root - * ContainerContext to the associated bean. This value can be transient, since it - * can be easily recomputed when needed. - */ - private transient String _controlID; - - /** - * Object that implements the java.beans.beancontext APIs from the JDK to provide compliance with the - * JavaBeans BeanContext / BeanContextChild specification. The ControlBeanContext class uses - * this object as a delegate to provide this functionality rather than extending the BeanContext - * support classes directly. This allows for more flexibility in how the BeanContextServices (et al) - * API implementations evolve over time. - */ - private BeanContextServices _beanContextServicesDelegate; -} diff --git a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/bean/ControlBeanInfo.java b/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/bean/ControlBeanInfo.java deleted file mode 100644 index 931c779..0000000 --- a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/bean/ControlBeanInfo.java +++ /dev/null @@ -1,89 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.runtime.bean; - -import java.util.Locale; -import java.util.MissingResourceException; -import java.util.ResourceBundle; - -/** - * The ControlBeanInfo class is an abstract base class for the JavaBean BeanInfo classes generated - * to support Beehive controls. It is used to bundle helper code common across all generated - * BeanInfo classes. - */ -abstract public class ControlBeanInfo extends java.beans.SimpleBeanInfo -{ - /** - * Protected constructor that is called from generated BeanInfo subclasses. - * @param beanClass the JavaBean class for which BeanInfo is being provided. - */ - protected ControlBeanInfo(Class beanClass) - { - super(); - _beanClass = beanClass; - } - - /* - * Gets a possibly-localized string for the given input string. - * @param input This the the string that may be localizable. If it is of the form - * "%foo.bar.Baz%", then the resource Baz will be looked up in the foo.bar bundle using - * standard ResourceBundle rules for the default Locale using the control's classloader. - * If the input does not start and end with '%', or if the bundle is not located, the string - * will be returned verbatim. - * @return the string to be displayed, or the input string if no resource is found. - */ - final protected String localizeString(String input) - { - if (input == null || !input.startsWith("%") || !input.endsWith("%")) - return input; - String bundleName = input.substring(1, input.length()-1); - String resourceName = null; - int lastDot = bundleName.lastIndexOf('.'); - while (lastDot != -1 && lastDot != 0 && (lastDot+1 < bundleName.length())) - { - // move last element from bundle to resource. foo.bar.Baz could be the - // Baz property in foo.bar, or the bar.Baz property in foo. - if (resourceName == null) - resourceName = bundleName.substring(lastDot+1); - else - resourceName = bundleName.substring(lastDot+1) + '.' + resourceName; - bundleName = bundleName.substring(0, lastDot); - - try - { - ResourceBundle bundle = ResourceBundle.getBundle(bundleName, Locale.getDefault(), - _beanClass.getClassLoader()); - if (bundle != null) - { - String lookup = bundle.getString(resourceName); - if (lookup != null) - return lookup; - } - } - catch (MissingResourceException mre) - { } - - lastDot = bundleName.lastIndexOf('.'); - } - - return input; - } - - Class _beanClass; -} diff --git a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/bean/ControlContainerContext.java b/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/bean/ControlContainerContext.java deleted file mode 100644 index 715ee1d..0000000 --- a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/bean/ControlContainerContext.java +++ /dev/null @@ -1,190 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.runtime.bean; - -import java.lang.reflect.InvocationTargetException; -import java.util.Stack; - -import org.apache.beehive.controls.api.context.ControlHandle; -import org.apache.beehive.controls.api.context.ControlThreadContext; -import org.apache.beehive.controls.api.context.ResourceContext; -import org.apache.beehive.controls.api.events.EventDispatcher; -import org.apache.beehive.controls.api.events.EventRef; - -/** - * The ControlContainerContext class provides a base class implementation for external containers - * of ControlBeans. It provides additional services, such as: - * - * - defines a contextual service provider for the ResourceManager interface - * - defines a simplified contract for the external container to interact with resource - * management (beginContext/endContext) - */ -public class ControlContainerContext - extends ControlBeanContext - implements EventDispatcher, org.apache.beehive.controls.api.context.ControlContainerContext -{ - public ControlContainerContext() - { - super(null); - } - - protected ControlContainerContext(BeanContextServicesFactory beanContextServicesFactory) { - super(null, beanContextServicesFactory); - } - - /** - * Defines the beginning of a new control container execution context. - */ - public void beginContext() - { - ControlThreadContext.beginContext(this); - } - - /** - * Ends the current control container execution context - */ - public void endContext() - { - try - { - // - // Release all resources associated with the current execution context. - // - releaseResources(); - } - finally - { - ControlThreadContext.endContext(this); - } - } - - /** - * Called by BeanContextSupport superclass during construction and deserialization to - * initialize subclass transient state - */ - public void initialize() - { - super.initialize(); - - // - // Register the ResourceContext provider on all new ControlContainerContext instances. - // - addService(org.apache.beehive.controls.api.context.ResourceContext.class, - ResourceContextImpl.getProvider()); - } - - /** - * Adds a new managed ResourceContext to the ControlContainerContext. This method - * is used to register a resource context that has just acquired resources - * @param resourceContext the ResourceContext service that has acquired resources - * @param bean the acquiring ControlBean. Unused by the base implementation, but - * available so subclassed containers can have access to the bean. - */ - protected synchronized void addResourceContext(ResourceContext resourceContext, ControlBean bean) - { - if (!resourceContext.hasResources()) - _resourceContexts.push(resourceContext); - } - - /** - * Removes a managed ResourceContext from the ControlContainerContext. This method - * is used to unregister a resource context that has already acquired resources - * @param resourceContext the ResourceContext service to be removed - * @param bean the acquiring ControlBean. Unused by the base implementation, but - * available so subclassed containers can have access to the bean. - */ - protected synchronized void removeResourceContext(ResourceContext resourceContext, ControlBean bean) - { - // - // Ignore removal requests received within the context of global cleanup. The - // stack is already being popped, so these are just requests for resources that - // already have in-flight removal taking place. - // - if (!_releasingAll && resourceContext.hasResources()) - _resourceContexts.remove(resourceContext); - } - - /** - * Releases all ResourceContexts associated with the current ControlContainerContext. - * This method is called by the associated container whenever all managed ResourceContexts - * that have acquired resources should release them. - */ - protected synchronized void releaseResources() - { - // Set the local flag indicating global resource release is occuring - _releasingAll = true; - - // - // Iterate through the list of acquired ResourceContexts and release them - // - while (!_resourceContexts.empty()) - { - ResourceContext resourceContext = _resourceContexts.pop(); - resourceContext.release(); - } - - // Clear the local flag indicating global resource release is occuring - _releasingAll = false; - } - - /** - * Dispatch an operation or an event to a bean within this container bean context. - * @param handle the control handle identifying the target bean - * @param event the event to be invoked on the target bean - * @param args the arguments to be passed to the target method invocation - */ - public Object dispatchEvent(ControlHandle handle, EventRef event, Object [] args) - throws IllegalArgumentException, IllegalAccessException, InvocationTargetException - { - ControlBean bean = getBean(handle.getControlID()); - if (bean == null) - throw new IllegalArgumentException("Invalid bean ID: " + handle.getControlID()); - - return bean.dispatchEvent(event, args); - } - - /** - * Returns a ControlHandle to the component containing the control. This handle can be - * used to dispatch events and operations to a control instance. This method will return - * null if the containing component does not support direct dispatch. - * - * @param bean the target control bean - */ - public ControlHandle getControlHandle(org.apache.beehive.controls.api.bean.ControlBean bean) - { - // - // The base implementation doesn't support dispatch. Containers should override - // and return a valid service handle that does component-specific dispatch. - // - return null; - } - - /** - * Returns true if this container guarantees single-threaded behaviour. By default, top-level - * containers are assumed to NOT guarantee this; specific container implementations (for example, - * for EJB containers) should override this appropriately. - */ - public boolean isSingleThreadedContainer() - { - return false; - } - - boolean _releasingAll; - Stack _resourceContexts = new Stack(); -} \ No newline at end of file diff --git a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/bean/ControlUtils.java b/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/bean/ControlUtils.java deleted file mode 100644 index 94c6509..0000000 --- a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/bean/ControlUtils.java +++ /dev/null @@ -1,97 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.runtime.bean; - -import org.apache.beehive.controls.api.bean.ControlInterface; -import org.apache.beehive.controls.api.bean.ControlExtension; -import org.apache.beehive.controls.api.ControlException; - -/** - * Utilities used by the Controls runtime. - */ -public final class ControlUtils { - - private ControlUtils() {} - - /** - * Implements the default control implementation binding algorithm ( + "Impl" ). See - * documentation for the org.apache.beehive.controls.api.bean.ControlInterface annotation. - * - * @param implBinding the value of the defaultBinding attribute returned from a ControlInterface annotation - * @param controlClass the actual name of the interface decorated by the ControlInterface annotation - * @return the resolved defaultBinding value - */ - public static String resolveDefaultBinding( String implBinding, String controlClass ) - { - int intfIndex = implBinding.indexOf(ControlInterface.INTERFACE_NAME); - if (intfIndex >= 0) - { - implBinding = implBinding.substring(0,intfIndex) + controlClass + - implBinding.substring(intfIndex + - ControlInterface.INTERFACE_NAME.length()); - } - return implBinding; - } - - /** - * Returns the default binding based entirely upon annotations or naming conventions. - * @param controlIntf the control interface class - * @return the class name of the default control implementation binding - */ - static String getDefaultControlBinding(Class controlIntf) - { - controlIntf = getMostDerivedInterface(controlIntf); - - ControlInterface intfAnnot = - (ControlInterface)controlIntf.getAnnotation(ControlInterface.class); - String implBinding = intfAnnot.defaultBinding(); - implBinding = resolveDefaultBinding( implBinding, controlIntf.getName() ); - - return implBinding; - } - - /** - * Computes the most derived ControlInterface for the specified ControlExtension. - * @param controlIntf - * @return the most derived ControlInterface - */ - static Class getMostDerivedInterface(Class controlIntf) - { - while (controlIntf.isAnnotationPresent(ControlExtension.class)) - { - Class [] intfs = controlIntf.getInterfaces(); - boolean found = false; - for (int i = 0; i < intfs.length; i++) - { - if (intfs[i].isAnnotationPresent(ControlExtension.class) || - intfs[i].isAnnotationPresent(ControlInterface.class)) - { - controlIntf = intfs[i]; - found = true; - break; - } - } - if (!found) - { - throw new ControlException("Can't find base control interface for " + controlIntf); - } - } - return controlIntf; - } -} diff --git a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/bean/DefaultControlBeanContextFactory.java b/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/bean/DefaultControlBeanContextFactory.java deleted file mode 100644 index e075b36..0000000 --- a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/bean/DefaultControlBeanContextFactory.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - 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. - - $Header:$ -*/ -package org.apache.beehive.controls.runtime.bean; - -import org.apache.beehive.controls.api.bean.ControlBean; -import org.apache.beehive.controls.api.context.ControlBeanContext; -import org.apache.beehive.controls.spi.context.ControlBeanContextFactory; - -/** - * Default implementation of the {@link ControlBeanContextFactory} that simply creates an instance of a - * {@link ControlBeanContext} given the current {@link ControlBean}. - */ -/* package */ class DefaultControlBeanContextFactory - implements ControlBeanContextFactory { - - /** - * Create the {@link ControlBeanContext} for the {@link ControlBean}. - * @param controlBean - * @return the {@link ControlBeanContext} - */ - public ControlBeanContext instantiate(ControlBean controlBean) { - if(!(controlBean instanceof org.apache.beehive.controls.runtime.bean.ControlBean)) - throw new IllegalArgumentException("The ControlBean of type \"" + - controlBean.getClass().getName() + - "\" is unsupported. The ControlBean must extend " + - org.apache.beehive.controls.runtime.bean.ControlBean.class.getName()); - - /* - The provided ControlBean is a "api.bean.ControlBean"; this factory implementation only creates - ControlBeanContext implementations for "runtime.bean.ControlBean" types. Ensuare that this is - of that type. - */ - org.apache.beehive.controls.runtime.bean.ControlBean runtimeControlBean = - (org.apache.beehive.controls.runtime.bean.ControlBean)controlBean; - - /* - Create a simple new ControlBeanContext. - */ - return new org.apache.beehive.controls.runtime.bean.ControlBeanContext(runtimeControlBean); - } -} diff --git a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/bean/EventAdaptor.java b/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/bean/EventAdaptor.java deleted file mode 100644 index 2c6d481..0000000 --- a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/bean/EventAdaptor.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.runtime.bean; - -/** - * The EventAdaptor interface will be implemented by all code-generated event adaptor classes - * used to deliver control events to clients. - */ -public interface EventAdaptor -{ - /** - * Returns the client instance that will be the target of the event. - */ - Object getClient(); -} diff --git a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/bean/EventNotifier.java b/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/bean/EventNotifier.java deleted file mode 100644 index e48ac42..0000000 --- a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/bean/EventNotifier.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.runtime.bean; - -import java.util.Iterator; -import java.util.LinkedList; - -/** - * The EventNotifier class provides basic callback listener management and event delivery - * services for ControlBean instances. - */ -public class EventNotifier implements java.io.Serializable -{ - /** - * Adds a new callback event listener for this EventNotifier - */ - synchronized public void addListener(Object listener) - { - _listeners.add(listener); - } - - /** - * Remove an existing callback event listener for this EventNotifier - */ - synchronized public void removeListener(Object listener) - { - if (!_listeners.contains(listener)) - throw new IllegalStateException("Invalid listener, not currently registered"); - - _listeners.remove(listener); - } - - /** - * Returns an iterator over the full set of listeners - */ - public Iterator listenerIterator() - { - return _listeners.iterator(); - } - - /** - * Returns the number of registered listeners - */ - public int getListenerCount() - { - return _listeners.size(); - } - - /** - * Returns the listener list in array form - */ - public void getListeners(Object [] listeners) - { - _listeners.toArray(listeners); - } - - private LinkedList _listeners = new LinkedList(); -} diff --git a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/bean/ImplInitializer.java b/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/bean/ImplInitializer.java deleted file mode 100644 index 3323258..0000000 --- a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/bean/ImplInitializer.java +++ /dev/null @@ -1,75 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.runtime.bean; - -/** - * The ImplInitializer class is an abstract base class that all generated Control - * initalization classes will extend. It provides common utilities and supporting code - * for initialization, and has a shared package relationship with the base ControlBean - * class providing access to internals not available in a more general context. - */ -abstract public class ImplInitializer -{ - /** - * Initializes a new ControlImplementation instance associated with the specified bean. - */ - public void initialize(ControlBean bean, Object target) - { - initServices(bean, target); - initControls(bean, target); - initEventProxies(bean, target); - } - - /** - * Initializes all contextual services required by the target implementation instance. - * The default initializer implementation is a noop, but will be overridden by - * generated subclasses that contain contextual services. - */ - public void initServices(ControlBean bean, Object target) { }; - - /** - * Resets all contextual services on the target implementation instance to null. - * The default initializer implementation is a noop, but will be overridden by - * generated subclasses that contain contextual services. - */ - public void resetServices(ControlBean bean, Object target) { }; - - /** - * Initializes all nested controls required by the target implementation instance. - * The default initializer implementation is a noop, but will be overridden by - * generated subclasses that contain nested controls - */ - public void initControls(ControlBean bean, Object target) { }; - - /** - * Initializes all event proxies required by the target implementation instance. - * The default initializer implementation is a noop, but will be overridden by - * generated subclasses that contain event proxies - */ - public void initEventProxies(ControlBean bean, Object target) { }; - - - /** - * Returns the ControlBean event notifier for the specified eventSet - */ - public Object getEventNotifier(ControlBean bean, Class eventSet) - { - return bean.getEventNotifier(eventSet); - } -} diff --git a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/bean/ImplPersistenceDelegate.java b/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/bean/ImplPersistenceDelegate.java deleted file mode 100644 index 054a973..0000000 --- a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/bean/ImplPersistenceDelegate.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.runtime.bean; - -import java.beans.BeanInfo; -import java.beans.DefaultPersistenceDelegate; -import java.beans.Encoder; -import java.beans.Expression; -import java.beans.IntrospectionException; -import java.beans.Introspector; -import java.beans.PersistenceDelegate; -import java.beans.PropertyDescriptor; -import java.beans.Statement; -import java.beans.XMLEncoder; -import java.util.Set; - -import org.apache.beehive.controls.api.ControlException; - -/** - * The ImplPersistenceDelegate class supports the XML persistance of Control Implementation - * instances by implementing the java.beans.PersistenceDelegate API, and overriding - * the default persistance algorithm based upon the runtime structure for Controls. - *

- */ -public class ImplPersistenceDelegate extends DefaultPersistenceDelegate -{ - /** - * PersistenceDelegate.instantiate() - */ - protected Expression instantiate(Object oldInstance, Encoder out) - { - // - // An implementation instance is actually constructed at decode time by calling - // ControlBean.ensureControl on the parent bean. This will create a new impl - // instance and run the impl initializer on it. - // - return new Expression(((XMLEncoder)out).getOwner(), "ensureControl", null); - } - - /** - * PersistenceDelegate.initialize() - */ - protected void initialize(Class type, Object oldInstance, Object newInstance, Encoder out) - { - super.initialize(type, oldInstance, newInstance, out); - } - - /** - * PersistenceDelegate.writeObject() - */ - public void writeObject(Object oldInstance, Encoder out) - { - super.writeObject(oldInstance, out); - } -} diff --git a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/bean/InterceptorUtils.java b/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/bean/InterceptorUtils.java deleted file mode 100644 index 8b29d5a..0000000 --- a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/bean/InterceptorUtils.java +++ /dev/null @@ -1,118 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.runtime.bean; - -import java.util.ArrayList; -import java.util.Set; -import java.util.HashSet; -import java.io.BufferedReader; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.IOException; - -/** - * Class used to support prioritizing interceptors on methods of a {@link ControlBean}. - */ -public final class InterceptorUtils { - - private InterceptorUtils() {} - - /** - * Filename that contains ordering priority for controls interceptor services. - * Each line in the file is a fully qualified interface name. The first line in the file - * is highest priority. - */ - public static final String INTERCEPTOR_CONFIG_FILE = "controls-interceptors.config"; - - // todo: this interceptor priority list should be stored by ClassLoader instead of shared between them - /** - * List that keeps track of the interceptors in their priority order. - */ - private static ArrayList _interceptorPriorities; - - /** - * Applies externally defined (via {@link #INTERCEPTOR_CONFIG_FILE}) ordering priority for - * controls interceptor services. - * - * @param interceptors - * @return String[] - */ - public static String[] prioritizeInterceptors( String [] interceptors ) - { - if ( interceptors == null ) - return null; - - // Read external configuration to obtain desired prioritization. - if ( _interceptorPriorities == null ) - { - // Only attempt to read the external configuration once; bounce the VM if you - // want to try again. - _interceptorPriorities = new ArrayList(); - BufferedReader in = null; - try - { - InputStream configFileStream = - ControlBeanContext.class.getClassLoader().getResourceAsStream( INTERCEPTOR_CONFIG_FILE ); - - if ( configFileStream != null ) - { - in = new BufferedReader(new InputStreamReader(configFileStream)); - String str; - while ((str = in.readLine()) != null) - _interceptorPriorities.add(str); - } - } - catch (IOException e) - { - // ignore - } - finally - { - try { - if (in != null) - in.close(); - } - catch ( IOException ie ) { /* ignore */ } - } - } - - // Put input list of interceptors into a Set for easy lookup - Set input = new HashSet(); - for ( String ii : interceptors ) - input.add( ii ); - - // Scan through priorities list, building a prioritized list - ArrayList prioritized = new ArrayList(interceptors.length); - for ( String p : _interceptorPriorities ) - { - if ( input.contains(p) ) - { - input.remove(p); - prioritized.add(p); - } - } - - // Anything still left in the input set did not have a priority associated with it, - // so they just go at the end in arbitrary order. - for ( String p : input ) - prioritized.add(p); - - return prioritized.toArray(new String[prioritized.size()]); - } -} diff --git a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/bean/InvokeListener.java b/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/bean/InvokeListener.java deleted file mode 100644 index c09ba75..0000000 --- a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/bean/InvokeListener.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.runtime.bean; - -import java.lang.reflect.Method; - -/** - * The InvokeListener interface can be implemented by contextual services or helper - * classes associated with a ControlBean that want pre/post hook notifications of - * invocations occuring on a ControlBean. - * - * Hooking is "read only". An InvokeListener cannot modify the invoked method, - * arguments, return value or thrown exceptions in any way. - */ -public interface InvokeListener extends java.util.EventListener -{ - /** - * Called just prior to invoking an operation or callback event on a control. - */ - public void preInvoke(Method m, Object [] args); - - /** - * Called just after inovcation of an operation or callback event on a control - */ - public void postInvoke(Object retval, Throwable t); -} diff --git a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/bean/ResourceContextImpl.java b/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/bean/ResourceContextImpl.java deleted file mode 100644 index e0b0706..0000000 --- a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/bean/ResourceContextImpl.java +++ /dev/null @@ -1,172 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.runtime.bean; - -import java.beans.beancontext.BeanContextServiceProvider; -import java.beans.beancontext.BeanContextServices; -import java.lang.reflect.Method; -import java.util.Iterator; -import java.util.Vector; - -import org.apache.beehive.controls.api.context.ResourceContext; - -/** - * The ResourceContextImpl class provides an implementation of the ResourceContext service, - * as well as a simple singleton provider that can be used to obtain new instances. - */ -public class ResourceContextImpl implements ResourceContext, InvokeListener -{ - /** - * The ResourceContextProvider inner class acts as a single BeanContext service - * provider for the ResourceContext service class. - */ - private static class ResourceContextProvider - implements BeanContextServiceProvider { - - // - // BeanContextServiceProvider.getService() - // - public Object getService(BeanContextServices bcs, Object requestor, Class serviceClass, Object serviceSelector) - { - // - // There is an implied contract between ControlContainerContext and ControlBean - // classes required to implement the resource management contract. This cannot - // be supported for any generic BeanContextChild class. - // - if (requestor instanceof ControlBean) - { - return new ResourceContextImpl((ControlContainerContext)bcs, (ControlBean)requestor); - } - - return null; - } - - // - // BeanContextServiceProvider.releaseService() - // - public void releaseService(BeanContextServices bcs, Object requestor, Object service) - { - return; // Should not happen, service is never unregistered - } - - // - // BeanContextServiceProvider.getContextServiceSelectors() - // - public Iterator getCurrentServiceSelectors(BeanContextServices bcs, Class serviceClass) - { - return null; // no selectors - } - } - - /** - * A singleton instance of the ResourceContextProvider class is what will be registered - * on all ControlContainerContext instances. The provider can be a singleton because it is - * completely stateless and thread-safe. - */ - static private ResourceContextProvider _theProvider = new ResourceContextProvider(); - - /** - * Returns the ResourceContextProvider used to create new ResourceContext instances - */ - static /* package */ ResourceContextProvider getProvider() { return _theProvider; } - - /** - * Constructs a new ResourceContext service implementation to manage resources for - * a target ControlBean within a specific ControlContainerContext - */ - public ResourceContextImpl(ControlContainerContext containerContext, ControlBean bean) - { - _containerContext = containerContext; - _bean = bean; - - // - // Register to receive invocation notifications from the target bean - // - _bean.addInvokeListener(this); - } - - /** - * Implements the InvokeListener.preInvoke method. This hook will be called before the - * managed beans' operations are invoked - */ - public void preInvoke(Method m, Object [] args) - { - if (!_hasAcquired) - acquire(); - } - - /** - * Implements the InvokeListener.postInvoke method. - */ - public void postInvoke(Object retval, Throwable t) {} - - // ResourceContext.acquire() - public void acquire() - { - if (_hasAcquired) - return; - - // Deliver the onAcquire event to registered listeners - for (ResourceEvents resourceListener : _listeners) - resourceListener.onAcquire(); - - // Register this ResourceContext with associated container context - _containerContext.addResourceContext(this, _bean); - - // Set the flag to indicate resources have been acquired. - _hasAcquired = true; - } - - // ResourceContext.release() - public void release() - { - if (!_hasAcquired) - return; - - // Deliver the onRelease event to the registered listeners - for (ResourceEvents resourceListener : _listeners) - resourceListener.onRelease(); - - // Unregister this ResourceContext with associated container context - _containerContext.removeResourceContext(this, _bean); - - // Reset the flag to indicate resources have been released. - _hasAcquired = false; - } - - // ResourceContext.hasResources() - public boolean hasResources() { return _hasAcquired; } - - // ResourceContext.addResourceEventsListener - public void addResourceEventsListener(ResourceEvents resourceListener) - { - _listeners.add(resourceListener); - } - - // ResourceContext.removeResourceEventsListener - public void removeResourceEventsListener(ResourceEvents resourceListener) - { - _listeners.remove(resourceListener); - } - - private Vector _listeners = new Vector(); - private boolean _hasAcquired = false; - private ControlContainerContext _containerContext; - private ControlBean _bean; -} diff --git a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/bean/UnicastEventNotifier.java b/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/bean/UnicastEventNotifier.java deleted file mode 100644 index 747a045..0000000 --- a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/bean/UnicastEventNotifier.java +++ /dev/null @@ -1,80 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.runtime.bean; - -import java.util.TooManyListenersException; - -/** - * The UnicastEventNotifier class provides basic callback listener management and event delivery - * services for unicast EventSets on ControlBean instances. - */ -public class UnicastEventNotifier implements java.io.Serializable -{ - /** - * Adds a new callback event listener for this EventNotifier. This method will also - * perform a check to see if there is already a register listener, and throw a - * java.util.TooManyListenersException if there is already a registered - * listener. - */ - synchronized public void addListener(Object listener) throws TooManyListenersException - { - if (_listener != null) - throw new TooManyListenersException("Callback listener is already registered"); - _listener = listener; - } - - /** - * Remove an existing callback event listener for this EventNotifier - */ - synchronized public void removeListener(Object listener) - { - if (_listener != listener) - { - throw new IllegalStateException("Invalid listener, not currently registered"); - } - _listener = null; - } - - /** - * Returns the listener associated with this EventNotifier - */ - public Object getListener() - { - return _listener; - } - - /** - * Returns the number of registered listeners - */ - public int getListenerCount() - { - return (_listener != null) ? 1 : 0; - } - - /** - * Returns the listener list in array form - */ - public void getListeners(Object [] listeners) - { - if (_listener != null) - listeners[0] = _listener; - } - - private Object _listener; -} diff --git a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/bean/WebContextFactoryProvider.java b/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/bean/WebContextFactoryProvider.java deleted file mode 100644 index cf96e09..0000000 --- a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/bean/WebContextFactoryProvider.java +++ /dev/null @@ -1,105 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.runtime.bean; - -import java.beans.beancontext.BeanContextServices; -import java.beans.beancontext.BeanContextServiceProvider; -import java.util.Iterator; -import java.util.Collections; - -import org.apache.beehive.controls.spi.context.ControlBeanContextFactory; -import org.apache.beehive.controls.runtime.webcontext.ControlBeanContextServicesSupport; - -/** - *

- * This class acts as a ControlBeanContextFactoryProvider that exposes this factory as a contextual service - * from inside of a ControlBeanContext. - *

- *

- * Note: This class, the service provider, and the contextual service it provides are considerd an implementation - * detail and should not be used from user code. - *

- */ -public class WebContextFactoryProvider - implements BeanContextServiceProvider { - - private static final WebContextFactoryProvider theProvider = new WebContextFactoryProvider(); - private static final WebControlBeanContextFactory theFactory = new WebControlBeanContextFactory(); - - public static final ControlBeanContext.BeanContextServicesFactory WEB_CONTEXT_BCS_FACTORY = - new WebContextBeanContextServicesFactory(); - - public static BeanContextServiceProvider getProvider() { - return theProvider; - } - - private WebContextFactoryProvider() { - } - - public Object getService(BeanContextServices bcs, Object requestor, Class serviceClass, Object serviceSelector) { - return theFactory; - } - - public void releaseService(BeanContextServices bcs, Object requestor, Object service) { - } - - public Iterator getCurrentServiceSelectors(BeanContextServices bcs, Class serviceClass) { - return Collections.EMPTY_LIST.iterator(); - } - - /** - *

- * {@link ControlBeanContextFactory} implementation that provides a {@link ControlBeanContext} object - * used for web-tier control containment. - *

- *

- * Note: This factory is considerd an implementation detail and should not be referenced from user code. - *

- */ - /*package*/ static class WebControlBeanContextFactory - implements ControlBeanContextFactory { - - public org.apache.beehive.controls.api.context.ControlBeanContext instantiate - (org.apache.beehive.controls.api.bean.ControlBean controlBean) { - - if(!(controlBean instanceof ControlBean)) - throw new IllegalArgumentException("The ControlBean of type \"" + - controlBean.getClass().getName() + - "\" is unsupported. The ControlBean must extend " + - ControlBean.class.getName()); - - ControlBean runtimeControlBean = (ControlBean)controlBean; - - return new ControlBeanContext(runtimeControlBean, WEB_CONTEXT_BCS_FACTORY); - } - } - - /*package*/ static class WebContextBeanContextServicesFactory - extends ControlBeanContext.BeanContextServicesFactory { - protected BeanContextServices instantiate(ControlBeanContext controlBeanContext) { - return new ControlBeanContextServicesSupport(controlBeanContext); - - /* The java implementation of the BeanContext support classes, - not currently used by Beehive due to performance issues. - - return new java.beans.beancontext.BeanContextServicesSupport(controlBeanContext); - */ - } - } -} diff --git a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/generator/AptAnnotationHelper.java b/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/generator/AptAnnotationHelper.java deleted file mode 100644 index c0cd889..0000000 --- a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/generator/AptAnnotationHelper.java +++ /dev/null @@ -1,87 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.runtime.generator; - -import java.util.HashMap; -import java.util.Map; - -import com.sun.mirror.declaration.AnnotationMirror; -import com.sun.mirror.declaration.AnnotationTypeElementDeclaration; -import com.sun.mirror.declaration.AnnotationValue; - -/** - * The AptAnnotationHelper class is a helper class that aids in the reading of annotation - * values using APT metadata - */ -public class AptAnnotationHelper -{ - /** - * Initialize a new helper instance based upon a specific annotation declaration. - * @param annot The annotation value declaration - */ - public AptAnnotationHelper(AnnotationMirror annot) - { - // - // Build maps from the element name to its declaration and values - // - Map elemValues = - annot.getElementValues(); - - for (AnnotationTypeElementDeclaration ated : elemValues.keySet()) - { - _elementMap.put(ated.getSimpleName(), ated); - _valueMap.put(ated.getSimpleName(), elemValues.get(ated)); - } - }; - - /** - * Returns the AnnotationTypeElementDeclaration for a particular element - */ - public AnnotationTypeElementDeclaration getElementDeclaration(String elemName) - { - if (_elementMap.containsKey(elemName)) - return _elementMap.get(elemName); - return null; - } - - /** - * Returns the value of a particular element as a String - */ - public String getStringValue(String elemName) - { - if (_valueMap.containsKey(elemName)) - return _valueMap.get(elemName).toString(); - return null; - } - - /** - * Returns the value of a particular element as an Object - */ - public Object getObjectValue(String elemName) - { - if (_valueMap.containsKey(elemName)) - return _valueMap.get(elemName).getValue(); - return null; - } - - private HashMap _elementMap = - new HashMap(); - private HashMap _valueMap = - new HashMap(); -} diff --git a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/generator/AptClientField.java b/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/generator/AptClientField.java deleted file mode 100644 index df8923b..0000000 --- a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/generator/AptClientField.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.runtime.generator; - -import java.util.ArrayList; - -import com.sun.mirror.apt.AnnotationProcessorEnvironment; -import com.sun.mirror.declaration.FieldDeclaration; - -/** - * The AptClientField class describes a reference to a client callback notifier within an - * AptControlImplementation class. - */ -public class AptClientField extends AptField -{ - /** - * Base constructor, protected so only a custom subclass can invoke - * @param controlImpl the declaring AptControlImplementation - */ - public AptClientField(AptControlImplementation controlImpl, FieldDeclaration fieldDecl) - { - super(fieldDecl); - _controlImpl = controlImpl; - }; - - private AptControlImplementation _controlImpl; -} diff --git a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/generator/AptContextField.java b/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/generator/AptContextField.java deleted file mode 100644 index 211ca5f..0000000 --- a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/generator/AptContextField.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.runtime.generator; - -import com.sun.mirror.declaration.FieldDeclaration; -import com.sun.mirror.type.InterfaceType; -import com.sun.mirror.type.TypeMirror; -import org.apache.beehive.controls.runtime.generator.apt.TwoPhaseAnnotationProcessor; - -/** - * The AptContextField class contains information about a field referring to a contextual - * service with an AptControlImplementation class. - */ -public class AptContextField extends AptEventField -{ - /** - * Base constructor, protected so only a custom subclass can invoke - * @param controlImpl the declaring ControlImplementation - */ - public AptContextField(AptControlImplementation controlImpl, FieldDeclaration fieldDecl, - TwoPhaseAnnotationProcessor ap) - { - super(fieldDecl); - _controlImpl = controlImpl; - _ap = ap; - }; - - /** - * Initializes a ControlInterface associated with this context field. Because - * contextual services can expose both APIs and events, they are similar to controls. - */ - protected AptControlInterface initControlInterface() - { - TypeMirror fieldType = _fieldDecl.getType(); - if (! (fieldType instanceof InterfaceType)) - { - _ap.printError( _fieldDecl, "context.field.badinterface" ); - return null; - } - - // - // For contextual services, the declared type of the field is always the public - // interface for the contextual service. - // - return new AptControlInterface(((InterfaceType)_fieldDecl.getType()).getDeclaration(), - _ap); - } - - private AptControlImplementation _controlImpl; - private TwoPhaseAnnotationProcessor _ap; -} diff --git a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/generator/AptControlClient.java b/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/generator/AptControlClient.java deleted file mode 100644 index 5f974fa..0000000 --- a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/generator/AptControlClient.java +++ /dev/null @@ -1,406 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.runtime.generator; - -import java.util.ArrayList; -import java.util.HashSet; -import java.util.Collection; -import java.util.HashMap; -import java.util.List; -import java.io.IOException; -import java.io.Writer; - -import com.sun.mirror.apt.Filer; -import com.sun.mirror.declaration.*; -import com.sun.mirror.type.TypeMirror; -import com.sun.mirror.type.ClassType; - -import org.apache.beehive.controls.api.events.EventHandler; -import org.apache.beehive.controls.runtime.generator.apt.TwoPhaseAnnotationProcessor; - -/** - * The AptControlClient class contains metadata about a class that contains nested control - * references (AptControlField). - */ -public class AptControlClient extends AptType implements Generator -{ - /** - * Constructs a new ControlClient instance where information is derived - * from APT metadata - * @param decl the annotated declaration - */ - public AptControlClient(Declaration decl, TwoPhaseAnnotationProcessor ap) - { - _ap = ap; - if (! (decl instanceof ClassDeclaration)) - { - _ap.printError( decl, "control.illegal.usage" ); - return; - } - _clientDecl = (ClassDeclaration)decl; - setDeclaration(_clientDecl); - - _controls = initControls(); - initEventAdaptors(); - - // - // Construct a new initializer class from this implementation class - // - _init = new ClientInitializer(this); - } - - /** - * Returns true if this type of client requires that nested controls have unique identifiers - */ - protected boolean needsUniqueID() - { - // - // BUGBUG: - // Pageflows need to have a more unique ID generated for fields, because multiple pageflows - // may be shared within a single ControlContainerContext, and just using the field name could - // result in collisions. A better (and less hard-wired) approach is needed than searching for - // specific annotations. Perhaps a model that enables particular client types to subclass - // AptControlClient and override getID() would be much better. - // - for (AnnotationMirror annotMirror : _clientDecl.getAnnotationMirrors()) - { - String annotType = annotMirror.getAnnotationType().toString(); - if (annotType.equals("org.apache.beehive.netui.pageflow.annotations.Jpf.Controller") || - annotType.equals("org.apache.beehive.netui.pageflow.annotations.Jpf.Backing")) - return true; - } - return false; - } - - /** - * Returns a unique ID for a control field - */ - public String getID(AptControlField control) - { - if (!needsUniqueID()) - return "\"" + control.getName() + "\""; - - return "client.getClass() + \"@\" + client.hashCode() + \"." + control.getClassName() + "." + control.getName() + "\""; - } - - /** - * Returns the list of ControlFields declared directly by this ControlImpl - */ - public ArrayList getControls() { return _controls; } - - /** - * Returns true if the implemenation class contains any nested controls - */ - public boolean hasControls() { return _controls.size() != 0; } - - /** - * Returns true if the control client needs field initialization support - */ - public boolean needsFieldInit() - { - return hasControls(); - } - - /** - * Returns the field with the specified name - */ - public AptField getField(String name) - { - for (AptField field : _controls) - if (field.getName().equals(name)) - return field; - - return null; - } - - /** - * Returns the list of fully qualified class names for types that are derived - * from this Generator - */ - public String [] getGeneratedTypes() - { - return new String [] { _init.getClassName() }; - } - - /** - * Returns the information necessary to generate a ImplInitializer from this - * ControlImplementation. - */ - public List getCheckOutput(Filer filer) throws IOException - { - return null; - } - - /** - * Returns the information necessary to generate a ClientInitializer from this control - */ - public List getGenerateOutput(Filer filer) throws IOException - { - HashMap map = new HashMap(); - map.put("client", this); // control client - map.put("init", _init); // control client initializer - - Writer writer = new IndentingWriter(filer.createSourceFile(_init.getClassName())); - GeneratorOutput genOut = - new GeneratorOutput(writer,"org/apache/beehive/controls/runtime/generator/ClientInitializer.vm", - map); - ArrayList genList = new ArrayList(1); - genList.add(genOut); - return genList; - } - - /** - * Initializes the list of ControlFields declared directly by this ControlClient - */ - protected ArrayList initControls() - { - ArrayList controls = new ArrayList(); - - if ( _clientDecl == null || _clientDecl.getFields() == null ) - return controls; - - Collection declaredFields = _clientDecl.getFields(); - for (FieldDeclaration fieldDecl : declaredFields) - { - if (fieldDecl.getAnnotation(org.apache.beehive.controls.api.bean.Control.class) != null) - controls.add(new AptControlField(this, fieldDecl, _ap)); - } - return controls; - } - - public boolean hasSuperClient() - { - return ( getSuperClientName() != null ); - } - - /** - * Returns the fully qualified classname of the closest control client in the inheritance chain. - * @return class name of the closest control client - */ - public String getSuperClientName() - { - ClassType superType = _clientDecl.getSuperclass(); - - while ( superType != null ) - { - ClassDeclaration superDecl = superType.getDeclaration(); - - Collection declaredFields = superDecl.getFields(); - for (FieldDeclaration fieldDecl : declaredFields) - { - if (fieldDecl.getAnnotation(org.apache.beehive.controls.api.bean.Control.class) != null) - { - // Found an @control annotated field, so return this class name - return superDecl.getQualifiedName(); - } - } - - superType = superType.getSuperclass(); - } - - return null; - } - - /** - * Returns the super class for this class - */ - public AptControlClient getSuperClass() { return null; } - - /** - * Initializes the list of EventAdaptors for this ControlImpl - */ - protected void initEventAdaptors() - { - if ( _clientDecl == null || _clientDecl.getMethods() == null ) - return; - - for (MethodDeclaration clientMethod : _clientDecl.getMethods()) - { - // - // Do a quick check for the presence of the EventHandler annotation on methods - // - if (clientMethod.getAnnotation(EventHandler.class) == null || - clientMethod.toString().equals("()")) - continue; - - // - // EventHandler annotations on private methods cause compilation error. - // - if (isPrivateMethod(clientMethod)) - { - _ap.printError( clientMethod, "eventhandler.method.is.private"); - continue; - } - - // - // If found, we must actually read the value using an AnnotationMirror, since it - // contains a Class element (eventSet) that cannot be loaded - // - AnnotationMirror handlerMirror = null; - for (AnnotationMirror annot : clientMethod.getAnnotationMirrors()) - { - if ( annot == null || - annot.getAnnotationType() == null || - annot.getAnnotationType().getDeclaration() == null || - annot.getAnnotationType().getDeclaration().getQualifiedName() == null ) - return; - - if ( annot.getAnnotationType().getDeclaration().getQualifiedName().equals( - "org.apache.beehive.controls.api.events.EventHandler")) - { - handlerMirror = annot; - break; - } - } - if (handlerMirror == null) - { - throw new CodeGenerationException("Unable to find EventHandler annotation on " + - clientMethod); - } - - AptAnnotationHelper handlerAnnot = new AptAnnotationHelper(handlerMirror); - - // - // Locate the EventField based upon the field element value - // - String fieldName = (String)handlerAnnot.getObjectValue("field"); - AptEventField eventField = (AptEventField)getField(fieldName); - if (eventField == null) - { - // Deliberately not issuing a diagnostic if an event handler specifies - // a field that isn't a control. Other annotation processors also - // handle event handlers, so delegate diagnostic responsibility to them. - continue; - } - - // - // Locate the EventSet based upon the eventSet element value - // - Object tmo = handlerAnnot.getObjectValue("eventSet"); - if (!(tmo instanceof TypeMirror)) - continue; - - TypeMirror tm = (TypeMirror)tmo; - String setName = tm.toString(); - - AptControlInterface controlIntf = eventField.getControlInterface(); - AptEventSet eventSet = controlIntf.getEventSet(setName); - - // todo: remove workaround once bug has been resolved. - /* Workaround JIRA issue BEEHIVE-1143, eventset name may - contain a '$' seperator between the outer class and inner class. - Should be a '.' seperator. Only applies to Eclipse APT. This - workaround is also present in AptControlImplementation.initEventAdapters - */ - if (tm.getClass().getName().startsWith("org.eclipse.")) { - setName = setName.replace('$', '.'); - } - // end of workaround - - if (eventSet == null) - { - _ap.printError( clientMethod, "eventhandler.eventset.not.found", setName ); - continue; - } - - // - // Register a new EventAdaptor for the EventSet, if none exists already - // - EventAdaptor adaptor = eventField.getEventAdaptor(eventSet); - if (adaptor == null) - { - adaptor = new EventAdaptor(eventField, eventSet); - eventField.addEventAdaptor(eventSet, adaptor); - } - - // - // Locate the EventSet method based upon the eventName element value. Once - // found, add a new AptEventHandler to the adaptor for this event. - // - boolean found = false; - String eventName = (String)handlerAnnot.getObjectValue("eventName"); - AptMethod handlerMethod = new AptMethod(clientMethod, _ap); - - // - // Will start at the currrent event set and look up through any ones it - // extends to try and find a matching event - // - while (eventSet != null) - { - for (AptEvent controlEvent : eventSet.getEvents()) - { - if (controlEvent == null || - controlEvent.getName() == null || - !controlEvent.getName().equals(eventName)) - continue; - - if ( controlEvent.getArgTypes() == null ) - continue; - - // - // BUGBUG: If the arguments are parameterized, then the event handler - // might declare a specific bound version of the type, so a direct - // comparison will fail. If parameterized, we don't validate. - // - if (controlEvent.hasParameterizedArguments() || - (controlEvent.getArgTypes().equals(handlerMethod.getArgTypes()) && - controlEvent.getReturnType().equals(handlerMethod.getReturnType()) - ) - ) - { - HashSet throwSet = new HashSet(controlEvent.getThrowsList()); - ArrayList handlerThrows = handlerMethod.getThrowsList(); - boolean throwsMatches = true; - for ( String t : handlerThrows ) - { - if ( !throwSet.contains(t) ) - throwsMatches = false; - } - - if ( !throwsMatches ) - { - _ap.printError( clientMethod, "eventhandler.throws.mismatch", handlerMethod.getName() ); - } - - adaptor.addHandler(controlEvent, - new AptEventHandler(controlEvent, clientMethod, _ap )); - found = true; - break; - } - } - if (found) // outer loop too - break; - - // - // Look up on the super event set if not found at the current level - // - eventSet = eventSet.getSuperEventSet(); - } - if (!found) - { - _ap.printError( clientMethod, "eventhandler.method.not.found", setName ); - } - } - } - - ClassDeclaration _clientDecl; - TwoPhaseAnnotationProcessor _ap; - ArrayList _controls; - ClientInitializer _init; -} diff --git a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/generator/AptControlField.java b/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/generator/AptControlField.java deleted file mode 100644 index f226e50..0000000 --- a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/generator/AptControlField.java +++ /dev/null @@ -1,181 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.runtime.generator; - -import java.util.Collection; - -import com.sun.mirror.declaration.ClassDeclaration; -import com.sun.mirror.declaration.FieldDeclaration; -import com.sun.mirror.declaration.InterfaceDeclaration; -import com.sun.mirror.declaration.TypeDeclaration; -import com.sun.mirror.type.DeclaredType; -import com.sun.mirror.type.InterfaceType; -import com.sun.mirror.type.TypeMirror; -import com.sun.mirror.type.MirroredTypeException; - -import org.apache.beehive.controls.api.bean.ControlExtension; -import org.apache.beehive.controls.api.bean.ControlInterface; -import org.apache.beehive.controls.api.bean.Control; -import org.apache.beehive.controls.api.versioning.VersionRequired; -import org.apache.beehive.controls.runtime.generator.apt.TwoPhaseAnnotationProcessor; - -/** - * The AptControlField class contains information about a field that refers to a nested control. - */ -public class AptControlField extends AptEventField -{ - /** - * Base constructor, protected so only a custom subclass can invoke - * @param controlClient the declaring AptType - */ - public AptControlField(AptType controlClient, FieldDeclaration controlDecl, - TwoPhaseAnnotationProcessor ap) - { - super( controlDecl ); - _controlClient = controlClient; - _ap = ap; - _controlBean = new ControlBean(getControlInterface()); - } - - /** - * Does this control field have a VersionRequired annotation? - * @return true if there is a version required annotation; false otherwise - */ - public boolean hasVersionRequired() - { - return ( _fieldDecl.getAnnotation( VersionRequired.class ) != null ); - } - - /** - * Initializes the ControlInterface associated with this ControlField - */ - protected AptControlInterface initControlInterface() - { - TypeMirror controlType = _fieldDecl.getType(); - if (! (controlType instanceof DeclaredType)) - { - _ap.printError( _fieldDecl, "control.field.bad.type" ); - return null; - } - - // - // The field can either be declared as the bean type or the public interface type. - // If it is the bean type, then we need to reflect to find the public interface - // type it implements. - // - TypeDeclaration typeDecl = ((DeclaredType)controlType).getDeclaration(); - InterfaceDeclaration controlIntf = null; - - // - // It is possible that the declared type is associated with a to-be-generated - // bean type. In this case, look for the associated control interface on the - // processor input list. - // - if ( typeDecl == null ) - { - String className = controlType.toString(); - String intfName = className.substring(0, className.length() - 4); - String interfaceHint = getControlInterfaceHint(); - controlIntf = (InterfaceDeclaration)_ap.getAnnotationProcessorEnvironment().getTypeDeclaration(intfName); - - if (controlIntf == null) - { - // The specified class name may not be fully qualified. In this case, the - // best we can do is look for a best fit match against the input types - for (TypeDeclaration td :_ap.getAnnotationProcessorEnvironment().getSpecifiedTypeDeclarations()) - { - // if an interface hint was provided, use it to find the control interface, - // if not provided try to find the control interface by matching simple names. - if (interfaceHint != null) { - if (td instanceof InterfaceDeclaration && - td.getQualifiedName().equals(interfaceHint)) - { - controlIntf = (InterfaceDeclaration)td; - break; - } - } - else { - if (td instanceof InterfaceDeclaration && - td.getSimpleName().equals(intfName)) - { - controlIntf = (InterfaceDeclaration)td; - break; - } - } - } - } - } - else if (typeDecl instanceof ClassDeclaration) - { - Collection implIntfs = ((ClassDeclaration)typeDecl).getSuperinterfaces(); - for (InterfaceType intfType : implIntfs) - { - InterfaceDeclaration intfDecl = intfType.getDeclaration(); - - if ( intfDecl == null ) - return null; - - if (intfDecl.getAnnotation(ControlInterface.class) != null|| - intfDecl.getAnnotation(ControlExtension.class) != null) - { - controlIntf = intfDecl; - break; - } - } - } - else if (typeDecl instanceof InterfaceDeclaration) - { - controlIntf = (InterfaceDeclaration)typeDecl; - } - - if (controlIntf == null) - { - _ap.printError( _fieldDecl, "control.field.bad.type.2" ); - return null; - } - - return new AptControlInterface(controlIntf, _ap); - } - - /** - * Get the interface hint attribute value (as a string) from the Control annotation, - * if it wasn't specified return null. - */ - private String getControlInterfaceHint() { - - Control controlAnnotation = _fieldDecl.getAnnotation(Control.class); - String interfaceHint = null; - try { - // always excepts - controlAnnotation.interfaceHint(); - } catch (MirroredTypeException mte) { - interfaceHint = ("java.lang.Object".equals(mte.getQualifiedName())) ? null : mte.getQualifiedName(); - } - return interfaceHint; - } - - /** - * Returns the ControlBean associated with this ControlField - */ - public ControlBean getControlBean() { return _controlBean; } - - private TwoPhaseAnnotationProcessor _ap; - private AptType _controlClient; - private ControlBean _controlBean; -} diff --git a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/generator/AptControlImplementation.java b/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/generator/AptControlImplementation.java deleted file mode 100644 index 9e7986c..0000000 --- a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/generator/AptControlImplementation.java +++ /dev/null @@ -1,516 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.runtime.generator; - -import java.io.IOException; -import java.io.Writer; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.List; - - -import com.sun.mirror.apt.Filer; -import com.sun.mirror.declaration.AnnotationMirror; -import com.sun.mirror.declaration.ClassDeclaration; -import com.sun.mirror.declaration.Declaration; -import com.sun.mirror.declaration.FieldDeclaration; -import com.sun.mirror.declaration.InterfaceDeclaration; -import com.sun.mirror.declaration.MethodDeclaration; -import com.sun.mirror.type.InterfaceType; -import com.sun.mirror.type.TypeMirror; - -import org.apache.beehive.controls.api.bean.ControlImplementation; -import org.apache.beehive.controls.api.events.Client; -import org.apache.beehive.controls.api.events.EventHandler; -import org.apache.beehive.controls.api.versioning.VersionSupported; -import org.apache.beehive.controls.api.versioning.Version; -import org.apache.beehive.controls.runtime.generator.apt.TwoPhaseAnnotationProcessor; - -/** - * The AptControlImplementation class provides validation and metadata management when - * processing a ControlImplementation class. - */ -public class AptControlImplementation extends AptType implements Generator -{ - /** - * Constructs a new AptControlImplementation instance where information is derived - * from APT metadata - * @param decl the annotated declaration - */ - public AptControlImplementation(Declaration decl, TwoPhaseAnnotationProcessor ap) - { - _ap = ap; - if (! (decl instanceof ClassDeclaration)) - { - _ap.printError( decl, "control.implementation.badclass" ); - return; - } - _implDecl = (ClassDeclaration)decl; - setDeclaration(_implDecl); - - _superClass = initSuperClass(); - - _contexts = initContexts(); - - _controls = initControls(); - - _clients = initClients(); - - initEventAdaptors(); - - // - // Check serializability of the implementation class. Any non-transient implementation - // must implement the java.io.Serializable marker interface to indicate that the author - // has considered serializability. - // - ControlImplementation implAnnot = _implDecl.getAnnotation(ControlImplementation.class); - if (!implAnnot.isTransient()) - { - if (!isSerializable()) - { - _ap.printError( decl, "control.implementation.unserializable" ); - } - } - - // - // Construct a new initializer class from this implementation class - // - _init = new ImplInitializer(this); - - if ( getControlInterface() == null ) - { - _ap.printError( decl, "control.implementation.missing.interface" ); - return; - } - - _versionSupported = initVersionSupported(); - - enforceVersionSupported(); - } - - /** - * Initializes the super interface that this ControlImpl extends (or null if a - * base class) - */ - private AptControlImplementation initSuperClass() - { - if ( _implDecl == null || _implDecl.getSuperclass() == null ) - return null; - - ClassDeclaration superDecl = _implDecl.getSuperclass().getDeclaration(); - if (superDecl != null && - superDecl.getAnnotation(org.apache.beehive.controls.api.bean.ControlImplementation.class) != null) - { - return new AptControlImplementation(superDecl, _ap); - } - - return null; - } - - /** - * Returns the super interface for this interface - */ - public AptControlImplementation getSuperClass() { return _superClass; } - - /** - * Initializes the list of ContextField declared directly by this ControlImpl - */ - private ArrayList initContexts() - { - ArrayList contexts = new ArrayList(); - - if ( _implDecl == null || _implDecl.getFields() == null ) - return contexts; - - Collection declaredFields = _implDecl.getFields(); - for (FieldDeclaration fieldDecl : declaredFields) - { - if (fieldDecl.getAnnotation(org.apache.beehive.controls.api.context.Context.class) != null) - contexts.add(new AptContextField(this, fieldDecl, _ap)); - } - return contexts; - } - - /** - * Returns the list of ContextFields declared directly by this ControlImplementation - */ - public ArrayList getContexts() { return _contexts; } - - /** - * Returns true if the implemenation class contains any nested services - */ - public boolean hasContexts() { return _contexts.size() != 0; } - - /** - * Initializes the list of ControlFields for this ControlImpl - */ - private ArrayList initControls() - { - ArrayList fields = new ArrayList(); - - if ( _implDecl == null || _implDecl.getFields() == null ) - return fields; - - Collection declaredFields = _implDecl.getFields(); - for (FieldDeclaration fieldDecl : declaredFields) - { - if (fieldDecl.getAnnotation(org.apache.beehive.controls.api.bean.Control.class) != null) - fields.add(new AptControlField(this, fieldDecl, _ap)); - } - return fields; - } - - /** - * Returns true if the implemenation class contains any nested controls - */ - public boolean hasControls() { return _controls.size() != 0; } - - /** - * Initializes the list of ClientFields declared directly by this ControlImpl - */ - protected ArrayList initClients() - { - ArrayList clients = new ArrayList(); - - if ( _implDecl == null || _implDecl.getFields() == null ) - return clients; - - Collection declaredFields = _implDecl.getFields(); - for (FieldDeclaration fieldDecl : declaredFields) - { - if (fieldDecl.getAnnotation(Client.class) != null) - clients.add(new AptClientField(this, fieldDecl)); - } - return clients; - } - - /** - * Returns the list of ClientFields declared directly by this ControlImplementation - */ - public ArrayList getClients() { return _clients; } - - /** - * Returns the VersionSupported annotation, if any. - */ - public VersionSupported getVersionSupported() { return _versionSupported; } - - /** - * Returns true if the implemenation class contains any nested event proxies - */ - public boolean hasClients() { return _clients.size() != 0; } - - /** - * Returns the field with the specified name - */ - public AptField getField(String name) - { - for (AptField genField : _contexts) - if (genField.getName().equals(name)) - return genField; - for (AptField genField : _clients) - if (genField.getName().equals(name)) - return genField; - - return null; - } - - public AptEventField getControlField(String name) - { - for (AptControlField controlField : _controls) - if (controlField.getName().equals(name)) - return controlField; - - return null; - } - - /** - * Returns the list of fully qualified class names for types that are derived - * from this Generator - */ - public String [] getGeneratedTypes() - { - return new String [] { _init.getClassName() }; - } - - /** - * Returns the information necessary to generate a ImplInitializer from this - * ControlImplementation. - */ - public List getCheckOutput(Filer filer) throws IOException - { - HashMap map = new HashMap(); - map.put("impl", this); // control implementation - map.put("init", _init); // control impl initializer - - Writer writer = new IndentingWriter(filer.createSourceFile(_init.getClassName())); - GeneratorOutput genOut = - new GeneratorOutput(writer,"org/apache/beehive/controls/runtime/generator/ImplInitializer.vm", - map); - ArrayList genList = new ArrayList(1); - genList.add(genOut); - return genList; - } - - /** - * Returns the list of generated files derived from this Generator during the - * generate phase of annotation processing. - */ - public List getGenerateOutput(Filer filer) throws IOException - { - return null; - } - - /** - * Returns the ControlInterface implemented by this ControlImpl. - */ - public AptControlInterface getControlInterface() - { - if ( _implDecl == null || _implDecl.getSuperinterfaces() == null ) - return null; - - Collection superInterfaces = _implDecl.getSuperinterfaces(); - for (InterfaceType intfType : superInterfaces) - { - InterfaceDeclaration intfDecl = intfType.getDeclaration(); - if (intfDecl != null && - intfDecl.getAnnotation(org.apache.beehive.controls.api.bean.ControlInterface.class) != null) - return new AptControlInterface(intfDecl, _ap); - } - - return null; - } - - /** - * Initializes the list of EventAdaptors for this ControlImpl - */ - protected void initEventAdaptors() - { - if ( _implDecl == null || _implDecl.getMethods() == null ) - return; - - for (MethodDeclaration implMethod : _implDecl.getMethods()) - { - // - // Do a quick check for the presence of the EventHandler annotation on methods - // - if (implMethod.getAnnotation(EventHandler.class) == null || - implMethod.toString().equals("()")) - continue; - - // - // EventHandler annotations on private methods cause compilation error. - // - if (isPrivateMethod(implMethod)) - { - _ap.printError(implMethod, "eventhandler.method.is.private"); - continue; - } - - // - // If found, we must actually read the value using an AnnotationMirror, since it - // contains a Class element (eventSet) that cannot be loaded - // - AnnotationMirror handlerMirror = null; - for (AnnotationMirror annot : implMethod.getAnnotationMirrors()) - { - if ( annot == null || - annot.getAnnotationType() == null || - annot.getAnnotationType().getDeclaration() == null || - annot.getAnnotationType().getDeclaration().getQualifiedName() == null ) - return; - - if ( annot.getAnnotationType().getDeclaration().getQualifiedName().equals( - "org.apache.beehive.controls.api.events.EventHandler")) - { - handlerMirror = annot; - break; - } - } - if (handlerMirror == null) - { - throw new CodeGenerationException("Unable to find EventHandler annotation on " + - implMethod); - } - - AptAnnotationHelper handlerAnnot = new AptAnnotationHelper(handlerMirror); - - // - // Locate the EventField based upon the field element value - // - String fieldName = (String)handlerAnnot.getObjectValue("field"); - AptEventField eventField = (AptEventField)getField(fieldName); - if (eventField == null) - { - // eventField == null means this field isn't interesting for the purposes - // of this processor (control impls). However, only emit an error message - // if the field isn't on a nested control - if ( getControlField(fieldName) == null ) - _ap.printError( implMethod, "eventhandler.field.not.found", fieldName ); - - continue; - } - - // - // Locate the EventSet based upon the eventSet element value - // - TypeMirror tm = (TypeMirror)( handlerAnnot.getObjectValue("eventSet") ); - if ( tm == null ) - continue; - String setName = tm.toString(); - AptControlInterface controlIntf = eventField.getControlInterface(); - - // todo: remove workaround once bug has been resolved. - /* Workaround for JIRA issue BEEHIVE-1143, eventset name may - contain a '$' seperator between the outer class and inner class. - Should be a '.' seperator. Only applies to Eclipse APT. This - workaround is also present in AptControlClient.initEventAdapters - */ - if (tm.getClass().getName().startsWith("org.eclipse.")) { - setName = setName.replace('$', '.'); - } - // end of workaround - - AptEventSet eventSet = controlIntf.getEventSet(setName); - if (eventSet == null) - { - _ap.printError( implMethod, "eventhandler.eventset.not.found", setName ); - continue; - } - - // - // Register a new EventAdaptor for the EventSet, if none exists already - // - EventAdaptor adaptor = eventField.getEventAdaptor(eventSet); - if (adaptor == null) - { - adaptor = new EventAdaptor(eventField, eventSet); - eventField.addEventAdaptor(eventSet, adaptor); - } - - // - // Locate the EventSet method based upon the eventName element value. Once - // found, add a new AptEventHandler to the adaptor for this event. - // - boolean found = false; - String eventName = (String)handlerAnnot.getObjectValue("eventName"); - AptMethod handlerMethod = new AptMethod(implMethod, _ap); - for (AptEvent controlEvent : eventSet.getEvents()) - { - if (controlEvent == null || controlEvent.getName() == null || - !controlEvent.getName().equals(eventName)) - continue; - if ( controlEvent.getArgTypes() == null ) - continue; - - // - // BUGBUG: If the arguments are parameterized, then the event handler - // might declare a specific bound version of the type, so a direct - // comparison will fail. If parameterized, we don't validate. - // - if (controlEvent.hasParameterizedArguments() || - controlEvent.getArgTypes().equals(handlerMethod.getArgTypes())) - { - adaptor.addHandler(controlEvent, - new AptEventHandler(controlEvent, implMethod, _ap)); - found = true; - break; - } - } - if (!found) - { - _ap.printError( implMethod, "eventhandler.method.not.found", setName ); - } - } - } - - private VersionSupported initVersionSupported() - { - if ( _implDecl == null ) - return null; - return _implDecl.getAnnotation(VersionSupported.class); - } - - /** - * Enforces the VersionRequired annotation for control extensions. - */ - private void enforceVersionSupported() - { - if ( _versionSupported != null ) - { - int majorSupported = _versionSupported.major(); - int minorSupported = _versionSupported.minor(); - - if ( majorSupported < 0 ) // no real version support requirement - return; - - AptControlInterface ci = getControlInterface(); - if ( ci == null ) - return; - - int majorPresent = -1; - int minorPresent = -1; - Version ciVersion = ci.getVersion(); - if ( ciVersion != null ) - { - majorPresent = ciVersion.major(); - minorPresent = ciVersion.minor(); - - if ( majorSupported >= majorPresent && - (minorSupported < 0 || minorSupported >= minorPresent) ) - { - // Version requirement is satisfied - return; - } - } - - // - // Version requirement failed - // - - _ap.printError( _implDecl, "versionsupported.failed", _implDecl.getSimpleName(), majorSupported, minorSupported, - majorPresent, minorPresent ); - } - } - - /** - * Does this control impl on one of it superclasses implement java.io.Serializable? - * @return true if this control impl or one of its superclasses implements java.io.Serializable. - */ - protected boolean isSerializable() { - - for (InterfaceType superIntf: _implDecl.getSuperinterfaces()) { - if (superIntf.toString().equals("java.io.Serializable")) { - return true; - } - } - - // check to see if the superclass is serializable - return _superClass != null && _superClass.isSerializable(); - } - - private ClassDeclaration _implDecl; - private TwoPhaseAnnotationProcessor _ap; - private AptControlImplementation _superClass; - private ArrayList _contexts; - private ArrayList _clients; - private ArrayList _controls; - private ImplInitializer _init; - private VersionSupported _versionSupported; -} diff --git a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/generator/AptControlInterface.java b/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/generator/AptControlInterface.java deleted file mode 100644 index 399f1e1..0000000 --- a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/generator/AptControlInterface.java +++ /dev/null @@ -1,1149 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.runtime.generator; - -import java.io.*; -import java.lang.reflect.*; -import java.lang.annotation.*; -import java.net.*; -import java.util.*; - -import com.sun.mirror.apt.Filer; -import com.sun.mirror.declaration.AnnotationMirror; -import com.sun.mirror.declaration.AnnotationTypeDeclaration; -import com.sun.mirror.declaration.Declaration; -import com.sun.mirror.declaration.InterfaceDeclaration; -import com.sun.mirror.declaration.MethodDeclaration; -import com.sun.mirror.declaration.TypeDeclaration; -import com.sun.mirror.type.DeclaredType; -import com.sun.mirror.type.InterfaceType; -import com.sun.mirror.type.MirroredTypesException; - -import org.apache.beehive.controls.api.bean.ControlChecker; -import org.apache.beehive.controls.api.bean.ControlExtension; -import org.apache.beehive.controls.api.bean.ControlInterface; -import org.apache.beehive.controls.api.bean.ExternalPropertySets; -import org.apache.beehive.controls.api.events.EventSet; -import org.apache.beehive.controls.api.packaging.FeatureInfo; -import org.apache.beehive.controls.api.packaging.ManifestAttribute; -import org.apache.beehive.controls.api.packaging.ManifestAttributes; -import org.apache.beehive.controls.api.properties.PropertySet; -import org.apache.beehive.controls.api.versioning.Version; -import org.apache.beehive.controls.api.versioning.VersionRequired; -import org.apache.beehive.controls.runtime.generator.apt.TwoPhaseAnnotationProcessor; -import org.apache.beehive.controls.runtime.generator.apt.CheckerAnnotationProcessorEnvironmentImpl; - -/** - * The AptControlInterface provides validation and metadata management for a ControlInterface - * or ControlExtension class during APT processing. It is also used to model the interface - * to contextual services, since they parallel the conventions of control interfaces. - */ -public class AptControlInterface extends AptType implements Generator -{ - /** - * Constructs a new AptControlInterface instance where interface information is derived - * from an APT interface declaration - * @param decl the annotated Declaration - * @param ap the top-level annotation processor - */ - public AptControlInterface(Declaration decl, TwoPhaseAnnotationProcessor ap) - { - _ap = ap; - - // - // Verify that the @ControlInterface/@ControlExtension annotations are only used on an - // interface. - // Note: AptControlInterface is also used to construct the operation and event model - // for contextual services (see AptContextField). Becaue contextual sevices can actually - // be classes as well as interfaces, the test below has to be specific to the annotated - // use cases - // - if (! (decl instanceof InterfaceDeclaration) && - (decl.getAnnotation(ControlExtension.class) != null || - decl.getAnnotation(ControlInterface.class) != null)) - { - _ap.printError(decl, "control.interface.annotation.badlocation" ); - return; - } - - _intfDecl = (InterfaceDeclaration)decl; - setDeclaration(_intfDecl); - - _isExtension = initIsExtension(); - - _superClass = initSuperClass(); - - _operations = initOperations(); - - _intfProps = initIntfProperties(); - - _propertySets = initPropertySets(); - - _eventSets = initEventSets(); - - _featureInfo = initFeatureInfo(); - - _version = initVersion(); - _versionRequired = initVersionRequired(); - - // - // Construct a bean instance for this interface - // - _bean = new ControlBean(this); - - // - // Enforce VersionRequired semantics - // - enforceVersionRequired(); - - // - // Do work specific to control extensions - // - - if (isExtension()) - { - // - // If this is an control extension, run the control-author-specified - // checker class to perform additional validation. - // - check(); - } - } - - /** - * Returns the parent control interface or extension type from which the control - * interface is derived (or null, if it is at the root of the interface hierarchy) - */ - public InterfaceType getSuperType() - { - if ( _intfDecl.getSuperinterfaces() == null ) - return null; - - for (InterfaceType intfType : _intfDecl.getSuperinterfaces()) - { - InterfaceDeclaration superDecl = intfType.getDeclaration(); - if ( superDecl != null ) - { - if (superDecl.getAnnotation(ControlExtension.class) != null || - superDecl.getAnnotation(ControlInterface.class) != null) - { - _superDecl = superDecl; - return intfType; - } - } - } - - return null; - } - - /** - * Initializes the super interface that this ControlInterface extends (or sets it to null - * if a base interface) - */ - private AptControlInterface initSuperClass() - { - // - // Look for a super interface that is either a control interface or extension. - // If found, return it. - // - InterfaceType superType = getSuperType(); - if (superType == null) - { - // At this point, we're processing the root of the interface heirarchy, - // which is not permitted to be a ControlExtension (that would imply a - // ControlExtension that wasn't actually extending a ControlInterface). - if ( isExtension() ) - { - _ap.printError( _intfDecl, "control.extension.badinterface"); - } - - return null; - } - - InterfaceDeclaration superDecl = superType.getDeclaration(); - if ( superDecl != null ) - { - if (superDecl.getAnnotation(ControlExtension.class) != null || - superDecl.getAnnotation(ControlInterface.class) != null) - { - _superDecl = superDecl; - AptControlInterface superIntf = new AptControlInterface(_superDecl, _ap); - - if (!isExtension() && superIntf.isExtension()) - { - _ap.printError( _intfDecl, "control.interface.badinterface"); - } - return superIntf; - } - } - - return null; - } - - /** - * Returns the super interface for this interface - */ - public AptControlInterface getSuperClass() { return _superClass; } - - /** - * Initializes the list of operations declared by this AptControlInterface - */ - private AptMethodSet initOperations() - { - AptMethodSet operList = new AptMethodSet(); - - if ( _intfDecl == null ) - return operList; - - // - // Add the methods from the current interface and all super interfaces *other* - // than the one from which control inheritance or extension is defined. These - // exceptions are handled on the super ControlInterface (the return value - // of AptControlInterface.initSuperClass()) - // - // Do this by: - // - initially populate the check vector with the control interface - // - iterate through the check vector, examining each interface to: - // * ignore the super interface - // * add all declared interface methods to the operations list - // * add any super interfaces to the Vector (avoiding recursion) - // - the iteration continues until all superinterfaces have been processed - // - Vector checkIntfs = new Vector(); - checkIntfs.add(_intfDecl); - - for (int i = 0; i < checkIntfs.size(); i++) - { - InterfaceDeclaration intfDecl = checkIntfs.elementAt(i); - if (intfDecl.equals(_superDecl)) - continue; - - if ( intfDecl.getMethods() == null ) - continue; - - // Add all declared methods, but ignore the mystery methods - for (MethodDeclaration methodDecl : intfDecl.getMethods()) - if (!methodDecl.toString().equals("()")) - operList.add(new AptOperation(this, methodDecl, _ap)); - - if ( intfDecl.getSuperinterfaces() == null ) - continue; - - for (InterfaceType superType : intfDecl.getSuperinterfaces()) - { - InterfaceDeclaration superDecl = superType.getDeclaration(); - if (superDecl != null && !checkIntfs.contains(superDecl)) - checkIntfs.add(superDecl); - } - } - - return operList; - } - - /** - * Returns the list of ControlOperations declared directly by this AptControlInterface - */ - public Collection getOperations() { return _operations.getMethods(); } - - /** - * Returns the total number of operations for this control interface - */ - public int getOperationCount() - { - int count = _operations.size(); - if (_superClass != null) - count += _superClass.getOperationCount(); - - return count; - } - - /** - * Initializes the list of PropertySets declared or referenced by this AptControlInterface - */ - private ArrayList initPropertySets() - { - ArrayList propSets = new ArrayList(); - - if ( _intfDecl == null ) - return propSets; - - // TODO: enforce presence of prefixes when multiple property sets w/ the same - // property name exist - - // - // Add the intrinsic/base property set - // - - TypeDeclaration basePropsDecl = - _ap.getAnnotationProcessorEnvironment().getTypeDeclaration( "org.apache.beehive.controls.api.properties.BaseProperties" ); - if ( basePropsDecl != null ) - { - propSets.add( new AptPropertySet( null, basePropsDecl, _ap ) ); - } - - // - // Add external property sets - // - ExternalPropertySets extPropsAnnotation = _intfDecl.getAnnotation(ExternalPropertySets.class); - if ( extPropsAnnotation != null ) - { - if (isExtension()) - { - _ap.printError( _intfDecl, "extpropertyset.illegal.usage" ); - } - - try - { - Class[] extProps = extPropsAnnotation.value(); - } - catch ( MirroredTypesException mte ) - { - Collection extProps = mte.getQualifiedNames(); - for ( String extPropName : extProps ) - { - TypeDeclaration extPropDecl = _ap.getAnnotationProcessorEnvironment().getTypeDeclaration( extPropName ); - if ( extPropDecl != null ) - { - AptPropertySet extPropSet = new AptPropertySet( null, extPropDecl, _ap ); - propSets.add( extPropSet ); - } - else - { - _ap.printError( _intfDecl, "extpropertyset.type.not.found", extPropName ); - } - } - } - } - - // - // Add nested property sets - // - - if ( _intfDecl.getNestedTypes() == null ) - return propSets; - - for (TypeDeclaration innerDecl : _intfDecl.getNestedTypes()) - { - boolean fError = false; - if (innerDecl.getAnnotation(PropertySet.class) != null) - { - if (! (innerDecl instanceof AnnotationTypeDeclaration)) - { - _ap.printError( innerDecl, "propertyset.not.annotation.type" ); - fError = true; - } - - Retention ret = innerDecl.getAnnotation(Retention.class); - if (ret == null || ret.value() != RetentionPolicy.RUNTIME) - { - _ap.printError( innerDecl, "propertyset.missing.retention" ); - fError = true; - } - - if (isExtension()) - { - _ap.printError( innerDecl, "propertyset.illegal.usage.2" ); - fError = true; - } - - if ( !fError ) - propSets.add( - new AptPropertySet(this, (AnnotationTypeDeclaration)innerDecl, _ap)); - } - } - - // - // Detect the presence of locally declared bound or constrained properties - // Enforce property name (including prefix) uniqueness across all propertysets on this interface. - // - - Set propertyNames = new HashSet(); - - for (AptPropertySet propSet : propSets) - { - for (AptProperty prop : propSet.getProperties()) - { - if (prop.isBound()) - _hasBoundProperties = true; - - if (prop.isConstrained()) - _hasConstrainedProperties = true; - - String propName = prop.getAccessorName(); - - if ( propertyNames.contains( propName ) ) - { - _ap.printError( _intfDecl, "propertyset.duplicate.property.names", propName, propSet.getShortName() ); - } - else - { - propertyNames.add( propName ); - } - } - } - - return propSets; - } - - /** - * Returns the list of PropertySets declared directly by this AptControlInterface - */ - public Collection getPropertySets() { return _propertySets; } - - /** - * Returns the total number of properties for this control interface - */ - public int getPropertyCount() - { - int count; - if (_superClass == null) - count = 0; - else - count = _superClass.getPropertyCount(); - - for (AptPropertySet propertySet : _propertySets) { - // if a property set is set to optional and hasSetters is set to false, - // there isn't a getter or setter available for that property - if (propertySet.hasSetters() || !propertySet.isOptional()) { - count += propertySet.getProperties().size(); - } - } - - count += _intfProps.size(); - return count; - } - - /** - * Returns the list of properties defined by getter and setter methods in this control interface. - */ - public Collection getInterfaceProperties() { return _intfProps; } - - /** - * Returns true if the interface has any bound properties associated with it. - */ - public boolean hasBoundProperties() - { - if (_superClass != null && _superClass.hasBoundProperties()) - return true; - - return _hasBoundProperties; - } - - /** - * Returns true if this interface is the first interface in the inheritance hierarchy - * to declare support for bound properties. This is used to declared PropertyChangeListener - * registration methods for the bean once (and only once). - */ - public boolean addsBoundPropertySupport() - { - // - // If a super interface has already added support, then not added here - // - if (_superClass != null && _superClass.addsBoundPropertySupport()) - return false; - - return hasBoundProperties(); - } - - /** - * Returns true if any properties declared directly by this control interface are constrained - * properties. This will not reflect the attributes of properties declared on - * an interface from which this interface derives. - */ - public boolean hasConstrainedProperties() - { - if (_superClass != null && _superClass.hasConstrainedProperties()) - return true; - - return _hasConstrainedProperties; - } - - /** - * Returns true if this interface is the first interface in the inheritance hierarchy - * to declare support for constrained properties. This is used to declared - * VetoableChangeListener registration methods for the bean once (and only once). - */ - public boolean addsConstrainedPropertySupport() - { - // - // If a super interface has already added support, then not added here - // - if (_superClass != null && _superClass.addsConstrainedPropertySupport()) - return false; - - return hasConstrainedProperties(); - } - - /** - * Initializes the list of EventSets declared by this AptControlInterface - */ - private ArrayList initEventSets() - { - ArrayList eventSets = new ArrayList(); - - if ( _intfDecl == null || _intfDecl.getNestedTypes() == null ) - return eventSets; - - for (TypeDeclaration innerDecl : _intfDecl.getNestedTypes()) - { - // HACKHACK: There appear to be mirror API bugs where calling getAnnotation() - // on certain entity types will result in an endless loop. For now, work around - // this by a priori filtering... but this mechanism will drop errors that appear - // on an inapropriate type (see check below) - if (! (innerDecl instanceof InterfaceDeclaration)) - continue; - - if (innerDecl.getAnnotation(EventSet.class) != null) - { - - if (! (innerDecl instanceof InterfaceDeclaration)) - { - _ap.printError( innerDecl, "eventset.illegal.usage" ); - } - else - { - eventSets.add( - new AptEventSet(this, (InterfaceDeclaration)innerDecl, _ap)); - } - } - } - return eventSets; - } - - /** - * Returns the list of AptEventSet declared directly by this AptControlInterface - */ - public Collection getEventSets() { return _eventSets; } - - /** - * Returns the total number of operations for this control interface - */ - public int getEventSetCount() - { - int count = _eventSets.size(); - if (_superClass != null) - count += _superClass.getEventSetCount(); - - return count; - } - - /** - * Returns the number of event sets declared in this control interface. - * Does not include eventset's declared in super class(es). - */ - public int getLocalEventSetCount() - { - return _eventSets.size(); - } - - /** - * Returns the AptEventSet with the specified name - */ - public AptEventSet getEventSet(String name) - { - for (AptEventSet eventSet: getEventSets()) - if (eventSet.getClassName().equals(name)) - return eventSet; - - if (_superClass != null) - return _superClass.getEventSet(name); - - return null; - } - - /** - * Returns the FeatureInfo attributes for this control interface - */ - public FeatureInfo getFeatureInfo() { return _featureInfo; } - - /** - * Returns the list of fully qualified class names for types that are derived - * from this Generator - */ - public String [] getGeneratedTypes() - { - return new String [] { _bean.getClassName() }; - } - - /** - * Returns the Version annotation, if any. - */ - public Version getVersion() - { - return _version; - } - - /** - * Returns the VersionRequired annotation, if any. - */ - public VersionRequired getVersionRequired() - { - return _versionRequired; - } - - /** - * Returns the information necessary to generate a ControlBean from this AptControlInterface - */ - public List getCheckOutput(Filer filer) throws IOException - { - HashMap map = new HashMap(); - - map.put("intf", this); // the control interface - map.put("bean", _bean); - - ArrayList genList = new ArrayList(); - - // - // the ControlBean class - // - Writer beanWriter = new IndentingWriter(filer.createSourceFile(_bean.getClassName())); - GeneratorOutput beanSource = - new GeneratorOutput(beanWriter, - "org/apache/beehive/controls/runtime/generator/ControlBean.vm", map); - genList.add(beanSource); - - // - // the ControlBean BeanInfo class - // - Writer beanInfoWriter = new IndentingWriter(filer.createSourceFile(_bean.getBeanInfoName())); - GeneratorOutput beanInfoSource = - new GeneratorOutput(beanInfoWriter, - "org/apache/beehive/controls/runtime/generator/ControlBeanInfo.vm", map); - genList.add(beanInfoSource); - - return genList; - } - - /** - * Returns the information necessary to generate a packaging information from this - * AptControlInterface. Since this information is not needed during type validation, - * it can be delated until the generate phase. - */ - public List getGenerateOutput(Filer filer) throws IOException - { - HashMap map = new HashMap(); - - map.put("intf", this); // the control interface - map.put("bean", _bean); - - ArrayList genList = new ArrayList(); - - // - // the ControlBean MANIFEST.MF section - // - Writer manifestWriter = filer.createTextFile(Filer.Location.CLASS_TREE, _bean.getPackage(), - new File(_bean.getShortName() + ".class.manifest"), - null); - GeneratorOutput beanManifest = - new GeneratorOutput(manifestWriter, - "org/apache/beehive/controls/runtime/generator/ControlManifest.vm", - map); - genList.add(beanManifest); - - return genList; - } - - /** - * Returns true if this interface is a ControlExtension (jcx) interface, false - * otherwise. - */ - public boolean isExtension() - { - return _isExtension; - } - - /** - * Returns the most-derived interface in the inheritance chain that is annotated - * with @ControlInterface. It represents the point in the inheritance chain - * where @ControlInterface becomes @ControlExtension (i.e., anything interface derived from - * the 'most-derived interface' is annotated with @ControlExtension). May return - * null if the inheritance chain is malformed. - */ - public AptControlInterface getMostDerivedInterface() - { - // - // Walk up ControlInterface chain looking for the 1st instance annotated - // w/ @ControlInterface (as opposed to @ControlExtension) - // - // REVIEW: TBD rules for inheritance of @ControlInterface will affect this. - // Probably need to keep walking and examine each @ControlInterface in the chain. - // Run all checkers in chain? Make checkers responsible for invoking their base - // class-defined checkers? - // - - AptControlInterface ancestor = getSuperClass(); - while (ancestor != null) - { - if (!ancestor.isExtension()) - break; - - ancestor = ancestor.getSuperClass(); - } - - return ancestor; - } - - /** - * Returns a classloader that can be used to load external classes - */ - public ClassLoader getExternalClassLoader() - { - Map opts = _ap.getAnnotationProcessorEnvironment().getOptions(); - String classpath = opts.get("-classpath"); - - if ( classpath != null ) - { - String [] cpEntries = classpath.split( File.pathSeparator ); - ArrayList a = new ArrayList(); - for ( String e : cpEntries ) - { - try - { - File f = (new File(e)).getCanonicalFile(); - URL u = f.toURL(); - a.add(u); - } - catch (Exception ex) - { - System.err.println( "getExternalClassLoader(): bad cp entry=" + e ); - System.err.println( "Exception processing e=" + ex ); - } - } - URL [] urls = new URL[a.size()]; - urls = (URL[]) a.toArray(urls); - - return new URLClassLoader( urls, ControlChecker.class.getClassLoader() ); - } - - return null; - } - - // - // These are defined by the JAR spec, Name-value pair section - // - static final String alphaNum = "ABCDEFGHIJKLMNOPQRSUVWXYZabcdefghijklmnopqrstuvwyz0123456789"; - static final String headerChar = alphaNum + "_-"; - - /** - * Validates a manifest attribute. If the attribute is invalid, it will generate - * appropriate APT messager entries and return false, else return true. - */ - private boolean isValidManifestAttribute(ManifestAttribute attr) - { - String name = attr.name(); - String value = attr.value(); - boolean isValid = true; - - /* - Note, the null-check for "name" is necessary when the annotation processor is hosted inside - of an IDE where the name attribute of the ManifestAttribute metadata can be null - temporarily. In order to "keep going", just report a warning and proceed. - */ - if (name == null || name.length() == 0) - { - _ap.printError( _intfDecl, "manifestattribute.illegal.name.1" ); - isValid = false; - } - else - { - if (alphaNum.indexOf(name.charAt(0)) < 0) - { - _ap.printError( _intfDecl, "manifestattribute.illegal.name.2" ); - isValid = false; - } - for (int i = 1; i < name.length(); i++) - { - if (headerChar.indexOf(name.charAt(i)) < 0) - { - _ap.printError( _intfDecl, "manifestattribute.illegal.name.3", name.charAt(i) ); - isValid = false; - break; - } - } - } - - /* - Note, the null-check for "value" is necessary when the annotation processor is hosted inside - of an IDE where the value attribute of the ManifestAttribute metadata can be null - temporarily. In order to "keep going", just report a warning and proceed. - */ - if (value == null || value.length() == 0) - { - _ap.printError( _intfDecl, "manifestattribute.illegal.name.4" ); - isValid = false; - } - else - { - // TODO: validate string contents are valid UTF-8? - } - - return isValid; - } - - /** - * Returns the array of ManifestAttributes associated with the AptControlInterface - */ - public HashMap getManifestAttributes() - { - HashMap attributes = new HashMap(); - - if ( _intfDecl == null ) - return attributes; - - try - { - ManifestAttributes annotAttrs =_intfDecl.getAnnotation(ManifestAttributes.class); - if (annotAttrs != null) - { - ManifestAttribute [] attrs = (ManifestAttribute [])annotAttrs.value(); - for (int i = 0; i < attrs.length; i++) - { - if (isValidManifestAttribute(attrs[i])) - attributes.put(attrs[i].name(), attrs[i].value()); - } - } - ManifestAttribute annotAttr = _intfDecl.getAnnotation(ManifestAttribute.class); - if (annotAttr != null) - { - if (isValidManifestAttribute(annotAttr)) - attributes.put(annotAttr.name(), annotAttr.value()); - } - return attributes; - } - catch (Exception e) { e.printStackTrace(); return attributes; } - } - - /** - * Computes whether this interface is a ControlInterface or a ControlExtension - */ - private boolean initIsExtension() - { - if ( _intfDecl == null ) - return false; - - return _intfDecl.getAnnotation(ControlExtension.class) != null; - } - - /** - * Returns the FeatureInfo annotation for this control interface, or null if there is none. - */ - private FeatureInfo initFeatureInfo() - { - if ( _intfDecl == null ) - return null; - return _intfDecl.getAnnotation(FeatureInfo.class); - } - - /** - * Returns the Version annotation for this control interface, or null if there is none. - */ - private Version initVersion() - { - if ( _intfDecl == null ) - return null; - return _intfDecl.getAnnotation(Version.class); - } - - /** - * Returns the VersionRequired annotation for this control interface, or null if there is none. - */ - private VersionRequired initVersionRequired() - { - if ( _intfDecl == null ) - return null; - return _intfDecl.getAnnotation(VersionRequired.class); - } - - /** - * Enforces the VersionRequired annotation for control extensions. - */ - private void enforceVersionRequired() - { - if ( _versionRequired != null ) - { - if ( !isExtension() ) - { - _ap.printError( _intfDecl, "versionrequired.illegal.usage" ); - return; - } - - int majorRequired = _versionRequired.major(); - int minorRequired = _versionRequired.minor(); - - if ( majorRequired < 0 ) // no real version requirement - return; - - AptControlInterface ci = getMostDerivedInterface(); - if ( ci == null ) - return; - - int majorPresent = -1; - int minorPresent = -1; - Version ciVersion = ci._version; - if ( ciVersion != null ) - { - majorPresent = ciVersion.major(); - minorPresent = ciVersion.minor(); - - if ( majorRequired <= majorPresent && - (minorRequired < 0 || minorRequired <= minorPresent) ) - { - // Version requirement is satisfied - return; - } - } - - // - // Version requirement failed - // - _ap.printError( _intfDecl, "versionrequired.failed", _intfDecl.getSimpleName(), - majorRequired, minorRequired, majorPresent, minorPresent ); - } - } - - /** - * Runs control-specific checker class (if specified) - */ - public void check() - { - // - // Find the nearest @ControlInterface, which is where the relevant control checker - // annotation will be found. - // - - AptControlInterface mostDerived = (AptControlInterface) getMostDerivedInterface(); - if ( mostDerived == null ) - return; - - InterfaceDeclaration intfDecl = mostDerived._intfDecl; - - if ( intfDecl == null ) - return; - - AnnotationMirror controlMirror = null; - - for (AnnotationMirror annot : intfDecl.getAnnotationMirrors()) - { - if (annot.getAnnotationType().getDeclaration().getQualifiedName().equals( - "org.apache.beehive.controls.api.bean.ControlInterface")) - { - controlMirror = annot; - break; - } - } - - assert ( controlMirror != null ) : "Found a control interface that isn't annotated properly: " + intfDecl; - - AptAnnotationHelper controlAnnot = new AptAnnotationHelper(controlMirror); - - // - // Read the name of the checker class from the @ControlInterface annotation, - // dynamically load and run it. - // - - DeclaredType checkerMirror = (DeclaredType)controlAnnot.getObjectValue("checker"); - if ( checkerMirror == null ) - { - // try the deprecated 'checkerClass' attribute - checkerMirror = (DeclaredType)controlAnnot.getObjectValue("checkerClass"); - } - - if ( checkerMirror != null && checkerMirror.getDeclaration() != null ) - { - // TODO: optimize to not invoke default checker? - String checkerName = checkerMirror.toString(); - - try - { - ClassLoader loader = getExternalClassLoader(); - - Class checkerClass = loader.loadClass( checkerName ); - if ( !ControlChecker.class.isAssignableFrom(checkerClass) ) - { - _ap.printError( intfDecl, "control.interface.illegal.checker", intfDecl.getSimpleName(), checkerName ); - } - else - { - - Constructor ctor = checkerClass.getConstructor(); - - ControlChecker checker = (ControlChecker) ctor.newInstance(); - CheckerAnnotationProcessorEnvironmentImpl ape = - new CheckerAnnotationProcessorEnvironmentImpl(_ap); - checker.check( _intfDecl, ape ); - } - } - catch ( Exception e ) { - _ap.printError( intfDecl, "control.interface.checker.load.failed", intfDecl.getSimpleName(), checkerName ); - } - } - } - - /** - * Build a list of properties defined by getter/setter methods on this control interface. - */ - private ArrayList initIntfProperties() { - - HashMap intfPropMap = new HashMap(); - - Collection ops = getOperations(); - for (AptOperation op : ops) { - String opName = op.getName(); - if (!op.isPublic()) { - continue; - } - - if (isGetter(op)) { - String propertyName = getIntfPropertyName(op); - if (intfPropMap.containsKey(propertyName)) { - intfPropMap.get(propertyName).setGetterName(opName); - } - else { - intfPropMap.put(propertyName, new AptControlInterfaceProperty(propertyName, opName, null)); - } - } - else if (isSetter(op)) { - String propertyName = getIntfPropertyName(op); - if (intfPropMap.containsKey(propertyName)) { - intfPropMap.get(propertyName).setSetterName(opName); - } - else { - intfPropMap.put(propertyName, new AptControlInterfaceProperty(propertyName, null, opName)); - } - } - else if (isIsGetter(op)) { - String propertyName = getIntfPropertyName(op); - if (intfPropMap.containsKey(propertyName)) { - intfPropMap.get(propertyName).setGetterName(opName); - } - else { - intfPropMap.put(propertyName, new AptControlInterfaceProperty(propertyName, opName, null)); - } - } - } - return new ArrayList(intfPropMap.values()); - } - - /** - * Does the method have a Java Beans getter method signature. - * @param method AptMethod instance - * @return true if getter - */ - private boolean isGetter(AptMethod method) { - String methodName = method.getName(); - - if (methodName.length() < 4) - return false; - - if (!methodName.startsWith("get")) - return false; - - if (method.getArgList().length() > 0) - return false; - - if ("void".equals(method.getReturnType())) - return false; - - return true; - } - - /** - * Does the method have a Java Beans getter method signature (is varient). - * @param method AptMethod instance. - * @return true if 'is' getter. - */ - private boolean isIsGetter(AptMethod method) { - String methodName = method.getName(); - - if (methodName.length() < 3) - return false; - - if (!methodName.startsWith("is")) - return false; - - if (method.getArgList().length() > 0) - return false; - - if (!"boolean".equals(method.getReturnType())) - return false; - - return true; - } - - /** - * Does the method have a Java Beans setter method signature (is varient). - * @param method AptMethod instance. - * @return true if setter. - */ - private boolean isSetter(AptMethod method) { - String methodName = method.getName(); - - if (methodName.length() < 4) - return false; - - if (!methodName.startsWith("set")) - return false; - - String argList = method.getArgList(); - if (argList.length() == 0) - return false; - - if (argList.indexOf(',') > -1) - return false; - - if (!"void".equals(method.getReturnType())) - return false; - - return true; - } - - /** - * Generate a property name from a method name. - * @param method AptMethod instance. - * @return property name. - */ - private String getIntfPropertyName(AptMethod method) { - String opName = method.getName(); - - int prefixIdx = 3; - if (opName.startsWith("is")) - prefixIdx = 2; - - if (opName.length() == prefixIdx + 1) - return "" + Character.toLowerCase(opName.charAt(prefixIdx)); - - return Character.toLowerCase(opName.charAt(prefixIdx)) + opName.substring(prefixIdx+1); - } - - private ArrayList _intfProps; - private AptControlInterface _superClass; - private AptMethodSet _operations; - private ArrayList _propertySets; - private boolean _isExtension; // true if ControlExtension, else ControlInterface - private boolean _hasBoundProperties; - private boolean _hasConstrainedProperties; - private ArrayList _eventSets; - private ControlBean _bean; - private FeatureInfo _featureInfo; - private Version _version; - private VersionRequired _versionRequired; - private InterfaceDeclaration _intfDecl; - private InterfaceDeclaration _superDecl; - private TwoPhaseAnnotationProcessor _ap; -} diff --git a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/generator/AptControlInterfaceProperty.java b/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/generator/AptControlInterfaceProperty.java deleted file mode 100644 index 9d31f78..0000000 --- a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/generator/AptControlInterfaceProperty.java +++ /dev/null @@ -1,87 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.runtime.generator; - -/** - * A property derived from a getter/setter method of the control interface. - */ -public final class AptControlInterfaceProperty { - private final String _name; - private String _setterName; - private String _getterName; - - /** - * Constructs a new AptControlInterfaceProperty instance. - * - * @param name Property name, may not be null. - * @param getterName Getter method name, may be null. - * @param setterName Setter method name, may be null. - */ - public AptControlInterfaceProperty(String name, String getterName, String setterName) { - assert name != null; - _name = name; - _getterName = getterName; - _setterName = setterName; - } - - /** - * Set the setter method name. - * - * @param setterName - */ - protected void setSetterName(String setterName) { - _setterName = setterName; - } - - /** - * Set the getter method name. - * - * @param getterName - */ - protected void setGetterName(String getterName) { - _getterName = getterName; - } - - /** - * Get the setter method name. - * - * @return setter method name, may be null. - */ - public String getSetterName() { - return _setterName; - } - - /** - * Get the getter method name. - * - * @return getter method name, may be null. - */ - public String getGetterName() { - return _getterName; - } - - /** - * Get the property name. - * - * @return Property name. - */ - public String getName() { - return _name; - } -} diff --git a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/generator/AptEvent.java b/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/generator/AptEvent.java deleted file mode 100644 index eee1cc7..0000000 --- a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/generator/AptEvent.java +++ /dev/null @@ -1,82 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.runtime.generator; - -import com.sun.mirror.declaration.MethodDeclaration; -import com.sun.mirror.type.VoidType; - -import org.apache.beehive.controls.runtime.generator.apt.TwoPhaseAnnotationProcessor; - -/** - * The AptEvent class represents a control Property where the event attributes - * are derived using APT metadata - */ -public class AptEvent extends AptMethod -{ - /** - * Constructs a new AptEvent instance from APT metadata - * @param eventSet the declaring EventSet - * @param eventDecl the event annotation type element declaration - */ - public AptEvent(AptEventSet eventSet, MethodDeclaration eventDecl, TwoPhaseAnnotationProcessor ap) - { - super(eventDecl, ap); - _eventSet = eventSet; - _eventDecl = eventDecl; - - // - // If the event is in multicast event set but does not return 'void', then generate - // an error. Only unicast events can have a return value, to avoid ambiguity over - // which listener gets to provide the value. - // - if (!eventSet.isUnicast() && !(eventDecl.getReturnType() instanceof VoidType)) - { - ap.printError( eventDecl, "eventset.illegal.multicast" ); - } - } - - /** - * Returns the name of the static field that holds the name of this method. - */ - public String getMethodField() - { - // - // Both the event set and event name must be used for the generated field to avoid - // conflicts between same-named events in different event sets. - // - StringBuffer sb = new StringBuffer(); - sb.append("_"); - sb.append(_eventSet.getShortName()); - sb.append("_"); - sb.append(getName()); - int methodIndex = getIndex(); - if (methodIndex != -1) - sb.append(methodIndex); - sb.append("Event"); - return sb.toString(); - } - - /** - * Returns the EventSet associated with the event - */ - public AptEventSet getEventSet() { return _eventSet; } - - MethodDeclaration _eventDecl; - private AptEventSet _eventSet; -} diff --git a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/generator/AptEventField.java b/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/generator/AptEventField.java deleted file mode 100644 index d5ed712..0000000 --- a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/generator/AptEventField.java +++ /dev/null @@ -1,162 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.runtime.generator; - -import java.util.Collection; -import java.util.HashMap; -import java.util.Iterator; - -import com.sun.mirror.declaration.FieldDeclaration; -import com.sun.mirror.declaration.TypeDeclaration; -import com.sun.mirror.declaration.TypeParameterDeclaration; -import com.sun.mirror.type.DeclaredType; -import com.sun.mirror.type.ReferenceType; -import com.sun.mirror.type.TypeMirror; - -/** - * The AptEventField class represents a field type that is also an event source - */ -abstract public class AptEventField extends AptField -{ - public AptEventField(FieldDeclaration fieldDecl) - { - super(fieldDecl); - } - - /** - * Inits the ControlInterface associated with this event field. The public interface - * for controls and contextual services, and their associated events can be modeled in the - * same way. Subclasses will override this to assign an appropriate interface. - */ - abstract protected AptControlInterface initControlInterface(); - - /** - * Computes the binding from any formal type parameters declared on the control interface - * to bound types on the field declaration. - */ - private void initTypeParameterBindings() - { - // - // Get an iterator to both the declared type arguments and the original type - // declaration on the associated control interface - // - DeclaredType fieldType = (DeclaredType)_fieldDecl.getType(); - Iterator paramBoundIter = fieldType.getActualTypeArguments().iterator(); - - TypeDeclaration intfDecl = (TypeDeclaration)_controlIntf.getTypeDeclaration(); - Iterator paramDeclIter = - intfDecl.getFormalTypeParameters().iterator(); - - // - // Iterate through them in parallel, creating a mapping from the original formal - // type parameter name to the actual bound type. In parallel, also build up a - // representation of the bound type declaration. - // - // NOTE: If no type binding is done on the field declaration, then loop below - // will not execute and no mappings/empty bound decl will be the result. - // - StringBuffer sb = new StringBuffer(); - boolean isFirst = true; - while (paramBoundIter.hasNext()) - { - TypeMirror paramBound = paramBoundIter.next(); - TypeParameterDeclaration paramDecl = paramDeclIter.next(); - - // - // Save a mapping from the formal type name to the bound mirror type - // - _typeBindingMap.put(paramDecl.getSimpleName(), paramBound); - - if (isFirst) - { - sb.append("<"); - isFirst = false; - } - else - sb.append(", "); - sb.append(paramBound); - } - if (!isFirst) - sb.append(">"); - - _boundParameterDecl = sb.toString(); - } - - /** - * Returns the ControlInterface associated with this event field - */ - public AptControlInterface getControlInterface() - { - if (_controlIntf == null) - { - _controlIntf = initControlInterface(); - if (_controlIntf != null) - initTypeParameterBindings(); - } - return _controlIntf; - } - - /** - * Gets the EventAdaptor for a particular EventSet - */ - public EventAdaptor getEventAdaptor(AptEventSet eventSet) - { - return _eventAdaptors.get(eventSet); - } - - /** - * Adds a EventAdaptor for a particular EventSet - */ - public void addEventAdaptor(AptEventSet eventSet, EventAdaptor eventAdaptor) - { - assert !_eventAdaptors.containsKey(eventSet); - _eventAdaptors.put(eventSet, eventAdaptor); - } - - /** - * Returns all EventAdaptors for this EventField - */ - public Collection getEventAdaptors() - { - return _eventAdaptors.values(); - } - - /** - * Returns the bound parameter declaration for this event field - */ - public String getBoundParameters() - { - return _boundParameterDecl; - } - - /** - * Returns the formal type binding map (from name to bound type) for the event field - */ - public HashMap getTypeBindingMap() - { - return _typeBindingMap; - } - - HashMap _eventAdaptors = - new HashMap(); - - String _boundParameterDecl; - HashMap _typeBindingMap = new HashMap(); - private AptControlInterface _controlIntf; -} diff --git a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/generator/AptEventHandler.java b/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/generator/AptEventHandler.java deleted file mode 100644 index 7a8e44e..0000000 --- a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/generator/AptEventHandler.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.runtime.generator; - -import com.sun.mirror.declaration.MethodDeclaration; - -import org.apache.beehive.controls.runtime.generator.apt.TwoPhaseAnnotationProcessor; - -/** - * The AptEventHandler class represents a control EventHandler where the event attributes - * are derived using APT metadata - */ -public class AptEventHandler extends AptMethod -{ - /** - * Constructs a new AptEventHandler instance - * from APT metadata - * @param event the handled ControlEvent - * @param handlerDecl the handler method declaration - */ - public AptEventHandler(AptEvent event, MethodDeclaration handlerDecl, TwoPhaseAnnotationProcessor ap) - { - super(handlerDecl, ap); - _event = event; - _handlerDecl = handlerDecl; - } - - /** - * Returns the ControlEvent associated with the ControlEventHandler - */ - public AptEvent getEvent() { return _event; } - - MethodDeclaration _handlerDecl; - private AptEvent _event; -} diff --git a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/generator/AptEventSet.java b/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/generator/AptEventSet.java deleted file mode 100644 index 24afb26..0000000 --- a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/generator/AptEventSet.java +++ /dev/null @@ -1,352 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.runtime.generator; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashSet; - -import com.sun.mirror.declaration.InterfaceDeclaration; -import com.sun.mirror.declaration.MethodDeclaration; -import com.sun.mirror.declaration.TypeDeclaration; -import com.sun.mirror.declaration.TypeParameterDeclaration; -import com.sun.mirror.type.InterfaceType; - -import org.apache.beehive.controls.api.events.EventSet; -import org.apache.beehive.controls.api.packaging.EventSetInfo; -import org.apache.beehive.controls.runtime.generator.apt.TwoPhaseAnnotationProcessor; - -/** - * The AptEventSet class represents a control EventSet where the events - * are derived using APT metadata. - */ -public class AptEventSet extends AptType -{ - /** - * Constructs a new AptEventSet instance from APT metadata - * @param controlIntf the declaring control interface - * @param eventSet the EventSet class - * @param ap the associated AnnotationProcessor - */ - public AptEventSet(AptControlInterface controlIntf, InterfaceDeclaration eventSet, - TwoPhaseAnnotationProcessor ap) - { - _controlIntf = controlIntf; - _eventSet = eventSet; - _ap = ap; - setDeclaration(eventSet); - - EventSet eventSetAnnot = eventSet.getAnnotation(EventSet.class); - if (eventSetAnnot != null) - _unicast = eventSetAnnot.unicast(); - - // - // If an EventSet interface has formal type parameters, they must be a subset of - // the original formal type parameters declared on the original control interface. - // This is required because it must be possible to bind the types of events immediately - // upon construction of the bean... there is no opportunity to separately specify - // parameterization for the event set for the purpose of creating listeners, client - // notifiers, etc. - // - TypeDeclaration intfDecl = controlIntf.getTypeDeclaration(); - for (TypeParameterDeclaration estpd : _eventSet.getFormalTypeParameters()) - { - boolean found = false; - for (TypeParameterDeclaration citpd : intfDecl.getFormalTypeParameters()) - { - if (estpd.getSimpleName().equals(citpd.getSimpleName())) - { - found = true; - break; - } - } - if (! found) - { - // - // BUGBUG: Ideally, this would be estpd.getPosition, but this seems to return - // 0,0 for the current APT implementation, so we use the event set position - // instead. - // Once this works, the 'break' below can also be removed to present errors - // for multiple invalid parameters - // - _ap.printError( eventSet, "eventset.formal.parameter.mismatch" ); - break; - } - } - - _superEventSet = initSuperEventSet(); - - _events = initEvents(); - } - - /** - * Checks to see if this EventSet extends an EventSet declared on a parent control interface. If - * found it will return the parent EventSet, or return null if not found. - */ - public AptEventSet initSuperEventSet() - { - // This will be common, so short circuit quickly - AptControlInterface superControl = _controlIntf.getSuperClass(); - if (superControl == null) - return null; - - // Compute a hash set containing the qualified names of all super interfaces - // for this EventSet - HashSet extendNames = new HashSet(); - for (InterfaceType superType: _eventSet.getSuperinterfaces()) - { - InterfaceDeclaration superDecl = superType.getDeclaration(); - if (superDecl != null) - extendNames.add(superDecl.getQualifiedName()); - } - - // Starting with the parent of the ControlInterface declaring this EventSet, look - // for a parent interface that declares ones of these super interfaces as an event - // set - while (superControl != null) - { - Collection superEventSets = superControl.getEventSets(); - for (AptEventSet superEventSet : superEventSets) - { - if (extendNames.contains(superEventSet.getClassName())) - return superEventSet; - } - - superControl = superControl.getSuperClass(); - } - - // Nothing found, so no super event set - return null; - } - - /** - * Returns any EventSet from which this event set derives (or null if none) - */ - public AptEventSet getSuperEventSet() { return _superEventSet; } - - /** - * Initializes the list of Events associated with this EventSet - */ - protected AptMethodSet initEvents() - { - AptMethodSet events = new AptMethodSet(); - if ( _eventSet == null || _eventSet.getMethods() == null ) - return events; - - // - // Add all of the public methods directly declared and inherited from extended - // interfaces, except for the EventSet super interface (if any) - // - ArrayList intfList = new ArrayList(); - intfList.add(_eventSet); - for (int i = 0; i < intfList.size(); i++) - { - InterfaceDeclaration intfDecl = intfList.get(i); - - // - // Don't add events that are derived from a super event set. These are not added because - // this class picks a single super interface to extend from when building a hierarchy - // of callback notifiers (etc). So, the super event set that was chosen first is left out - // of the list of event methods since they're captured in superclasses in the Control's implementation - // - if (_superEventSet != null && _superEventSet.getClassName().equals(intfDecl.getQualifiedName())) - continue; - - // Add all declared methods, but ignore the mystery methods - for (MethodDeclaration methodDecl : intfDecl.getMethods()) - if (!methodDecl.toString().equals("()")) - events.add(new AptEvent(this, methodDecl, _ap)); - - // - // Add all superinterfaces of the target interface to the list - // - for (InterfaceType superType: intfDecl.getSuperinterfaces()) - { - InterfaceDeclaration superDecl = superType.getDeclaration(); - if (superDecl != null && !intfList.contains(superDecl)) - intfList.add(superDecl); - } - } - - return events; - } - - /** - * Returns the list of Events associated with this EventSet - */ - public Collection getEvents() { return _events.getMethods(); } - - /** - * Returns 'true' if the event set support only unicast (single listener) events, - * false otherwise. - */ - public boolean isUnicast() - { - return _unicast; - } - - /** - * Returns the number of Events for this EventSet and any super event set - */ - public int getEventCount() - { - int count = _events.size(); - if (_superEventSet != null) - count += _superEventSet.getEventCount(); - return count; - } - - /** - * Returns the programmatic descriptor name to be returned by the EventDescriptor - * for the event set. - */ - public String getDescriptorName() - { - // - // The javadocs for java.beans.EventSetDescriptor suggest that the programmatic name - // should start w/ a lowercase letter. So we use the unqualified event set interface - // name w/ the first character lowercased. - // - String name = getShortName(); - return Character.toLowerCase(name.charAt(0)) + name.substring(1); - } - - /** - * Returns the name of the generated notifier class for this ControlEventSet - */ - public String getNotifierClass() - { - StringBuffer sb = new StringBuffer(getShortName()); - sb.append("Notifier"); - - // - // If the event set declaration has any parameterized types, then include them on - // the notifier class as well. Currently, these can only be parameterized types - // from the outer (control interface), since there is no other mechanism for specifying - // type values at notifier construction (other than propagation from the outer type). - // - sb.append(getFormalTypeParameterNames()); - return sb.toString(); - } - - /** - * Returns any 'extends' clause that should be placed on the generated notifier class - */ - public String getNotifierExtends() - { - // - // All EventNotifiers are rooted from a common utility class, so if there is no - // super event set, then extend the utility notifier class. - // - if (_superEventSet == null) - { - if (_unicast) - return "org.apache.beehive.controls.runtime.bean.UnicastEventNotifier"; - else - return "org.apache.beehive.controls.runtime.bean.EventNotifier"; - } - - // - // Otherwise, a generated notifier will extend the notifier of any parent event set - // - return _superEventSet.getNotifierClass(); - } - - /** - * Returns the short name for this notifier's base class. - */ - public String getNotifierExtendsShortName() { - - if (_superEventSet == null) - { - if (_unicast) - return "UnicastEventNotifier"; - else - return "EventNotifier"; - } - - return _superEventSet.getNotifierClass(); - } - - /** - * Return true if this notifier extends the UnicastEventNotifier or EventNotifier base class. - */ - public boolean isExtendsNotifierBase() { - return _superEventSet == null; - } - - /** - * Returns the name of the method used to register a new EventSet listener - */ - public String getAddListenerMethod() - { - return "add" + getShortName() + "Listener"; - } - - /** - * Returns the name of the method used to register a new EventSet listener - */ - public String getRemoveListenerMethod() - { - return "remove" + getShortName() + "Listener"; - } - - /** - * Returns the name of the method used to retrieve the (unicast) EventSet listener - */ - public String getGetListenersMethod() - { - return "get" + getShortName() + "Listeners"; - } - - /** - * Returns the name of a custom-generated method to initialize MethodDescriptor bean - * info for the events in this EventSet - */ - public String getInfoInitializer() - { - return "init" + getShortName() + "Events"; - } - - /** - * Returns any EventSetInfo associated with the event set (or null if none) - */ - public EventSetInfo getEventSetInfo() - { - if ( _eventSet == null ) - return null; - - return _eventSet.getAnnotation(EventSetInfo.class); - } - - /** - * Returns the underlying APT InterfaceDeclaration associated with this event set - */ - public InterfaceDeclaration getDeclaration() - { - return _eventSet; - } - - private TwoPhaseAnnotationProcessor _ap; - private InterfaceDeclaration _eventSet; - private AptEventSet _superEventSet; - private AptControlInterface _controlIntf; - private AptMethodSet _events; - private boolean _unicast; -} diff --git a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/generator/AptField.java b/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/generator/AptField.java deleted file mode 100644 index cf3992b..0000000 --- a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/generator/AptField.java +++ /dev/null @@ -1,109 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.runtime.generator; - -import java.util.Collection; - -import com.sun.mirror.declaration.FieldDeclaration; -import com.sun.mirror.declaration.Modifier; - -/** - * The AptField class is a helper class that knows how to generate useful information - * about a Field using APT metadata - */ -public class AptField -{ - AptField(FieldDeclaration fieldDecl) - { - _fieldDecl = fieldDecl; - } - - /** - * Returns the name of the method - */ - public String getName() - { - if ( _fieldDecl == null ) - return ""; - return _fieldDecl.getSimpleName(); - } - - /** - * Returns a local variable used when setting the field value - */ - public String getLocalName() { return "_" + getName(); } - - /** - * Returns the type of the field - */ - public String getType() - { - if ( _fieldDecl == null || _fieldDecl.getType() == null ) - return ""; - - return _fieldDecl.getType().toString(); - } - - /** - * Returns the class name of the field (does not include any formal type parameters - */ - public String getClassName() - { - if ( _fieldDecl == null || _fieldDecl.getType() == null ) - return ""; - - // - // This is lazily... but much easier than navigating the APT type system and just - // as effective ;) - String typeName = _fieldDecl.getType().toString(); - int formalIndex = typeName.indexOf('<'); - if (formalIndex > 0) - return typeName.substring(0, formalIndex); - return typeName; - } - - /** - * Returns the access modifier associated with the field - */ - public String getAccessModifier() - { - if ( _fieldDecl == null ) - return ""; - - Collection modifiers = _fieldDecl.getModifiers(); - if (modifiers.contains(Modifier.PRIVATE)) - return "private"; - if (modifiers.contains(Modifier.PROTECTED)) - return "protected"; - if (modifiers.contains(Modifier.PUBLIC)) - return "public"; - - return ""; - } - - /** - * Returns the name of a static local field using to refer to this Field - */ - public String getReflectField() - { - return "_" + getName() + "Field"; - } - - protected FieldDeclaration _fieldDecl; -} diff --git a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/generator/AptMethod.java b/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/generator/AptMethod.java deleted file mode 100644 index 2238f7c..0000000 --- a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/generator/AptMethod.java +++ /dev/null @@ -1,464 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.runtime.generator; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Collection; - -import com.sun.mirror.declaration.AnnotationMirror; -import com.sun.mirror.declaration.AnnotationTypeDeclaration; -import com.sun.mirror.declaration.MethodDeclaration; -import com.sun.mirror.declaration.ParameterDeclaration; -import com.sun.mirror.declaration.TypeParameterDeclaration; -import com.sun.mirror.declaration.Modifier; -import com.sun.mirror.type.AnnotationType; -import com.sun.mirror.type.DeclaredType; -import com.sun.mirror.type.PrimitiveType; -import com.sun.mirror.type.ReferenceType; -import com.sun.mirror.type.TypeMirror; -import com.sun.mirror.type.WildcardType; - -import org.apache.beehive.controls.api.packaging.FeatureInfo; -import org.apache.beehive.controls.runtime.generator.apt.TwoPhaseAnnotationProcessor; - - -/** - * The AptMethod class defines a base set of utility methods for acessing method attributes - * based upon an APT method declaration. - */ -public class AptMethod -{ - // - // Maps primitive type names to a default value string - // - private static HashMap _defaultReturnValues = new HashMap(); - - static final HashMap _primToObject = - new HashMap(); - - static - { - _defaultReturnValues.put("void", ""); - _defaultReturnValues.put("boolean", "false"); - _defaultReturnValues.put("char", "'\0'"); - _defaultReturnValues.put("byte", "0"); - _defaultReturnValues.put("short", "0"); - _defaultReturnValues.put("int", "0"); - _defaultReturnValues.put("long", "0"); - _defaultReturnValues.put("float", "0.0f"); - _defaultReturnValues.put("double", "0.0d"); - - _primToObject.put(PrimitiveType.Kind.BOOLEAN, "Boolean"); - _primToObject.put(PrimitiveType.Kind.BYTE, "Byte"); - _primToObject.put(PrimitiveType.Kind.CHAR, "Character"); - _primToObject.put(PrimitiveType.Kind.DOUBLE, "Double"); - _primToObject.put(PrimitiveType.Kind.FLOAT, "Float"); - _primToObject.put(PrimitiveType.Kind.INT, "Integer"); - _primToObject.put(PrimitiveType.Kind.LONG, "Long"); - _primToObject.put(PrimitiveType.Kind.SHORT, "Short"); - } - - - /** - * Constructs a new AptMethod instance associated with a specific method declaration - */ - public AptMethod(MethodDeclaration methodDecl, TwoPhaseAnnotationProcessor ap ) - { - _methodDecl = methodDecl; - _interceptorServiceNames = initInterceptorServiceNames(); - _ap = ap; - } - - /** - * Returns the name of the method - */ - public String getName() - { - if ( _methodDecl == null ) - return ""; - - return _methodDecl.getSimpleName(); - } - - /** - * Returns the argument declaration of the method, applying the bindings in the provided - * type map to any parameter types - */ - public String getArgDecl(HashMap bindingMap) - { - StringBuffer sb = new StringBuffer(); - - if ( _methodDecl.getParameters() == null ) - return ""; - - int i = 0; - for (ParameterDeclaration paramDecl : _methodDecl.getParameters()) - { - TypeMirror paramType = paramDecl.getType(); - if ( paramType == null ) - return ""; - - if (bindingMap != null && bindingMap.containsKey(paramType.toString())) - paramType = bindingMap.get(paramType.toString()); - - if (i != 0) - sb.append(", "); - - sb.append(paramType.toString()); - - sb.append(' '); - - // BUGBUG: when the MethodDeclaration is derived from Reflection, this seems - // to return 'arg0' for all arguments! - String argName = paramDecl.getSimpleName(); - if (argName.equals("arg0")) - sb.append("arg" + i); - else - sb.append(argName); - - i++; - } - return sb.toString(); - } - - /** - * Returns the arguments declarations for the method, with no formal parameter binding applied - */ - public String getArgDecl() - { - return getArgDecl(null); - } - - /** - * Returns the the method argument names, in a comma separated list - */ - public String getArgList(boolean quoteDelimit) - { - StringBuffer sb = new StringBuffer(); - int i = 0; - - if ( _methodDecl.getParameters() == null ) - return ""; - - for (ParameterDeclaration paramDecl : _methodDecl.getParameters()) - { - if (i != 0) - sb.append(", "); - - // BUGBUG: when the MethodDeclaration is derived from Reflection, this seems - // to return 'arg0' for all arguments! - String argName = paramDecl.getSimpleName(); - if (quoteDelimit) sb.append('"'); - if (argName.equals("arg0")) - sb.append("arg" + i); - else - sb.append(argName); - if (quoteDelimit) sb.append('"'); - i++; - } - return sb.toString(); - } - - /** - * Default form of getArgList, that does not quote delimit arguments - */ - public String getArgList() { return getArgList(false); } - - /** - * Returns the the method argument classes, in a comma separated list - */ - public String getArgTypes() - { - StringBuffer sb = new StringBuffer(); - int i = 0; - - if ( _methodDecl == null || _methodDecl.getParameters() == null ) - return ""; - - for (ParameterDeclaration paramDecl : _methodDecl.getParameters()) - { - if (i++ != 0) - sb.append(", "); - - TypeMirror paramType = paramDecl.getType(); - if (paramType == null) - return ""; - - // - // Use the erasure here, because we only want the raw type, not the reference - // type - // - sb.append(_ap.getAnnotationProcessorEnvironment().getTypeUtils().getErasure(paramType)); - sb.append(".class"); - } - return sb.toString(); - } - - /** - * Returns 'true' if the method uses any parameterized types as parameters - */ - public boolean hasParameterizedArguments() - { - for (ParameterDeclaration paramDecl : _methodDecl.getParameters()) - { - TypeMirror paramType = paramDecl.getType(); - if (paramType instanceof ReferenceType || paramType instanceof WildcardType) - return true; - } - return false; - } - - /** - * Returns the declaration of any generic formal types associated with the method - */ - public String getFormalTypes() - { - if ( _methodDecl == null || _methodDecl.getReturnType() == null ) - return ""; - - Collection formalTypes = _methodDecl.getFormalTypeParameters(); - if (formalTypes.size() == 0) - return ""; - - StringBuffer sb = new StringBuffer("<"); - boolean isFirst = true; - for (TypeParameterDeclaration tpd: formalTypes) - { - if (isFirst) - isFirst = false; - else - sb.append(", "); - - sb.append(tpd.toString()); - } - sb.append(">"); - return sb.toString(); - } - - /** - * Returns the method return type, applying any formal type parameter bindings defined - * by the provided map. - */ - public String getReturnType(HashMap bindingMap) - { - if ( _methodDecl == null || _methodDecl.getReturnType() == null ) - return ""; - - String returnType = _methodDecl.getReturnType().toString(); - if (bindingMap != null && bindingMap.containsKey(returnType)) - return bindingMap.get(returnType).toString(); - - return returnType; - } - - /** - * Returns the method return type with no type bindings applied - */ - public String getReturnType() - { - return getReturnType(null); - } - - /** - * Returns the throws clause of the operation - */ - public String getThrowsClause() - { - if ( _methodDecl == null || _methodDecl.getThrownTypes() == null ) - return ""; - - Collection thrownTypes = _methodDecl.getThrownTypes(); - if (thrownTypes.size() == 0) - return ""; - - StringBuffer sb = new StringBuffer("throws "); - int i = 0; - for (ReferenceType exceptType : thrownTypes) - { - if (i++ != 0) - sb.append(", "); - sb.append(exceptType.toString()); - } - return sb.toString(); - } - - /** - * Returns an ArrayList of thrown exceptions - */ - public ArrayList getThrowsList() - { - ArrayList throwsList = new ArrayList(); - - if ( _methodDecl == null || - _methodDecl.getThrownTypes() == null || - _methodDecl.getThrownTypes().size() == 0 ) - return throwsList; - - Collection thrownTypes = _methodDecl.getThrownTypes(); - for (ReferenceType exceptType : thrownTypes) - throwsList.add(exceptType.toString()); - - return throwsList; - } - - /** - * Returns a default return value string for the method, based upon bound return type - */ - public String getDefaultReturnValue(HashMap typeBinding) - { - String returnType = getReturnType(typeBinding); - if (_defaultReturnValues.containsKey(returnType)) - return _defaultReturnValues.get(returnType); - return "null"; - } - - /** - * Returns a default return value string for the method, with no type binding applied - */ - public String getDefaultReturnValue() - { - return getDefaultReturnValue(null); - } - - /** - * Returns any FeatureInfo associated with the method (or null if none) - */ - public FeatureInfo getFeatureInfo() - { - if ( _methodDecl == null ) - return null; - - return _methodDecl.getAnnotation(FeatureInfo.class); - } - - /** - * Sets the unique index value for this method. If a particular method is overloaded, - * then each associated AptMethod will have a unique index; otherwise, the index is -1. - */ - public void setIndex(int index) - { - _index = index; - } - - /** - * Returns the unique index value for this method. - */ - public int getIndex() { return _index; } - - /** - * Is this a public method? - * @return true if public - */ - protected boolean isPublic() { - Collection modifiers = _methodDecl.getModifiers(); - return modifiers.contains(Modifier.PUBLIC); - } - - MethodDeclaration _methodDecl; - int _index = -1; - TwoPhaseAnnotationProcessor _ap; - - /** - * Returns the names of interceptor service interfaces associated with this operation - * @return the names of the interceptor service interfaces associated with this operation - */ - public Collection getInterceptorServiceNames() - { - return _interceptorServiceNames; - } - - /** - * Returns the names of interceptor service interfaces associated with this operation, formatted as a - * constant initializer string. - * @return the names of the interceptor service interfaces associated with this operation - */ - public String getInterceptorDecl() - { - Collection names = getInterceptorServiceNames(); - if ( names == null || names.size() == 0 ) - return null; - - StringBuffer ret = new StringBuffer("{"); - - String [] n = names.toArray(new String[0]); - for (int i=0 ; i < n.length ; ++i) - { - ret.append('"'); ret.append( n[i] ); ret.append('"'); - if ( i != n.length-1 ) - ret.append(", "); - } - ret.append( "}" ); - - return ret.toString(); - } - - private Collection initInterceptorServiceNames() - { - ArrayList ret = new ArrayList(); - - if (_methodDecl == null) - return ret; - - // Iterate over annotations on operation, looking for interceptor-based ones - Collection annotations = _methodDecl.getAnnotationMirrors(); - for ( AnnotationMirror a : annotations ) - { - AnnotationType at = a.getAnnotationType(); - AnnotationTypeDeclaration atd = at.getDeclaration(); - - /* - When performing annotation processing, the ATD here might be null if the apt.exe runtime - is unable to resolve the type to something specific. This will happen when a type referenced - in a source file is invalid because of a bad / missing import, mis-spelling, etc. When - this happens, annotation processing should merilly continue and let javac.exe report - the type errors. Better to do that than to throw an NPE here. - */ - if (atd == null) - continue; - - Collection metaAnnotations = atd.getAnnotationMirrors(); - - /* - Look for annotations that are meta-annotated with @InterceptorAnnotation - */ - for ( AnnotationMirror ma : metaAnnotations ) - { - if ( ma.getAnnotationType().getDeclaration().getQualifiedName(). - equals( "org.apache.beehive.controls.spi.svc.InterceptorAnnotation" ) ) - { - /* - found an interceptor-based annotation, add it! - */ - AptAnnotationHelper ia = new AptAnnotationHelper( ma ); - DeclaredType serviceType = (DeclaredType) ia.getObjectValue("service"); - String intf = serviceType.toString(); - ret.add( intf ); - - break; - } - } - } - - return ret; - } - - Collection _interceptorServiceNames; - -} diff --git a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/generator/AptMethodSet.java b/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/generator/AptMethodSet.java deleted file mode 100644 index 7784540..0000000 --- a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/generator/AptMethodSet.java +++ /dev/null @@ -1,103 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.runtime.generator; - -import java.util.HashMap; -import java.util.Collection; - -/** - * The AptMethodSet method represents a collection of AptMethod objects. It contains special - * support for method overloading, to ensure that overloaded method objects contained within - * the set will each have a unique index value. - * - * @see org.apache.beehive.controls.runtime.generator.AptMethod#setIndex - */ -public class AptMethodSet -{ - /** - * Adds a new method to the list. Also detects overloaded methods and ensures that they - * will receive a unique index value. - */ - public void add(T method) - { - // check for overridden method - if (isOverrideMethod(method)) { - return; - } - - // Add to the list of managed methods - _methods.put(method.getName() + method.getArgTypes(), method); - - // Ensure that all added methods have a unique index - Object nameValue = _nameMap.get(method.getName()); - if (nameValue == null) - { - // first method with this name, considered unique (for now) - _nameMap.put(method.getName(), method); - } - else - { - int nextIndex; - if (nameValue instanceof AptMethod) - { - // 2nd method with this name, add index to original and start indexing - ((AptMethod)nameValue).setIndex(0); - nextIndex = 1; - } - else - { - // 3rd (or later) method with this name, continue indexing - nextIndex = ((Integer)nameValue).intValue(); - } - - method.setIndex(nextIndex++); - _nameMap.put(method.getName(), nextIndex); - } - } - - /** - * Get the collection of methods in this set. - */ - public Collection getMethods() - { - return _methods.values(); - } - - /** - * Get the number of methods in this set. - */ - public int size() - { - return _methods.size(); - } - - /** - * Determine of the method overrides a previously added method. - * @param method Method to check. - * @return true if method is an override to an existing method and does not need to be added - * to this method set. - */ - private boolean isOverrideMethod(T method) - { - return _methods.containsKey(method.getName() + method.getArgTypes()); - } - - private HashMap _nameMap = new HashMap(); // method name -> a single (unique) AptMethod or next index - private HashMap _methods = new HashMap(); // method name + arg types -> AptMethod -} diff --git a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/generator/AptOperation.java b/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/generator/AptOperation.java deleted file mode 100644 index b94acdf..0000000 --- a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/generator/AptOperation.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.runtime.generator; - -import com.sun.mirror.declaration.*; -import org.apache.beehive.controls.runtime.generator.apt.TwoPhaseAnnotationProcessor; - -/** - * The AptOperation class represents a control operation where the operation attributes - * are derived using APT metadata. - */ -public class AptOperation extends AptMethod -{ - /** - * Constructs a new ControlOperation instance where interface information is derived - * from APT metadata - * @param controlIntf the declaring ControlInterface - * @param methodDecl the method associated with the operation - */ - public AptOperation(AptControlInterface controlIntf, MethodDeclaration methodDecl, TwoPhaseAnnotationProcessor ap) - { - super(methodDecl, ap); - _controlIntf = controlIntf; - _operDecl = methodDecl; - } - - - /** - * Returns the name of the static field that holds the name of this method. - */ - public String getMethodField() - { - StringBuffer sb = new StringBuffer(); - sb.append("_"); - sb.append(getName()); - int methodIndex = getIndex(); - if (methodIndex != -1) - sb.append(methodIndex); - sb.append("Method"); - return sb.toString(); - } - - /** - * Returns the AptControlInterface associated with this ControlOperation - */ - public AptControlInterface getControlInterface() { return _controlIntf; } - - MethodDeclaration _operDecl; - AptControlInterface _controlIntf; -} diff --git a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/generator/AptProperty.java b/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/generator/AptProperty.java deleted file mode 100644 index 49ae657..0000000 --- a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/generator/AptProperty.java +++ /dev/null @@ -1,244 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.runtime.generator; - -import java.util.Collection; -import java.util.Map; - -import com.sun.mirror.declaration.AnnotationTypeElementDeclaration; -import com.sun.mirror.declaration.AnnotationMirror; -import com.sun.mirror.declaration.AnnotationValue; -import com.sun.mirror.type.AnnotationType; -import com.sun.mirror.type.PrimitiveType; - -import org.apache.beehive.controls.api.packaging.FeatureInfo; -import org.apache.beehive.controls.api.packaging.PropertyInfo; -import org.apache.beehive.controls.runtime.generator.apt.TwoPhaseAnnotationProcessor; - -/** - * The AptProperty class represents a control Property where the property attributes - * are derived using APT metadata - */ -public class AptProperty -{ - /** - * Constructs a new AptProperty instance - * from APT metadata - * @param propertySet the declaring PropertySet - * @param propDecl the declration of the property annotation type element - */ - public AptProperty(AptPropertySet propertySet, AnnotationTypeElementDeclaration propDecl, - TwoPhaseAnnotationProcessor ap) - { - _propertySet = propertySet; - _propDecl = propDecl; - _ap = ap; - - // - // Primitive properties must specify a default value, to provide consistent semantics - // in cases where no value has been set by annotation, client, or configuration. Object - // typed properties have an optional default, and 'null' in this context means that the - // property value has not been set. - // - if (propDecl.getReturnType() instanceof PrimitiveType && - propDecl.getDefaultValue() == null) - { - _ap.printError( propDecl, "property.primitive.without.default", propDecl.getSimpleName() ); - } - } - - /** - * Returns the PropertySet associated with the Property - */ - public AptPropertySet getPropertySet() { return _propertySet; } - - /** - * Returns the base property name. The associated accessor methods will have the - * form set{name} and get{name} - */ - public String getAccessorName() - { - StringBuffer sb = new StringBuffer(); - sb.append(_propertySet.getPrefix()); - - String name = getName(); - sb.append(Character.toUpperCase(name.charAt(0))); - if (name.length() > 0) - sb.append(name.substring(1)); - return sb.toString(); - } - - /** - * Returns the name of the property reading accessor method - */ - public String getReadMethod() - { - StringBuffer sb = new StringBuffer(); - if (getType().equals("boolean")) - sb.append("is"); - else - sb.append("get"); - sb.append(getAccessorName()); - return sb.toString(); - } - - /** - * Returns the name of the property writing accessor method - */ - public String getWriteMethod() - { - return "set" + getAccessorName(); - } - - /** - * Returns the name associated with this Property in the PropertySet - */ - public String getName() - { - if ( _propDecl == null ) - return ""; - - // - // Use the member name of the property method in the property set - // - return _propDecl.getSimpleName(); - } - - /** - * Returns the static final field name containing the key for this Property - */ - public String getKeyName() - { - return getAccessorName() + "Key"; - } - - /** - * Returns the type of the Property - */ - public String getType() - { - if ( _propDecl == null || _propDecl.getReturnType() == null ) - return ""; - - return _propDecl.getReturnType().toString(); - } - - /** - * Returns true if the property is an annotation type, false otherwise - */ - public boolean isAnnotation() - { - if ( _propDecl == null ) - return false; - - return _propDecl.getReturnType() instanceof AnnotationType; - } - - /** - * Returns any PropertyInfo associated with the property (or null if none) - */ - public PropertyInfo getPropertyInfo() - { - if ( _propDecl == null ) - return null; - - return _propDecl.getAnnotation(PropertyInfo.class); - } - - /** - * Returns any FeatureInfo associated with the property (or null if none) - */ - public FeatureInfo getFeatureInfo() - { - if ( _propDecl == null ) - return null; - - return _propDecl.getAnnotation(FeatureInfo.class); - } - - /** - * Returns 'true' is the property is a bound property that will support registration of - * a PropertyChangeListener for change notifications. - */ - public boolean isBound() - { - // - // Constrained properties are implicitly bound. Refer to section 7.4.3 of the JavaBeans - // spec for the rationale. - // - PropertyInfo propInfo = getPropertyInfo(); - return propInfo != null && (propInfo.bound() || propInfo.constrained()); - } - - /** - * Returns 'true' is the property is a constrained property that will support registration of - * a VetoableChangeListener for vetoable change notifications. - */ - public boolean isConstrained() - { - PropertyInfo propInfo = getPropertyInfo(); - return propInfo != null && propInfo.constrained(); - } - - /** - * Returns the class name of the property editor class, or null - */ - public String getEditorClass() - { - PropertyInfo pi = getPropertyInfo(); - if (pi == null) - return null; - - // - // This is trickier, because APT doesn't allow access to Class-valued annotations, - // because the type may not yet have been compiled. - // - Collection annotMirrors = _propDecl.getAnnotationMirrors(); - for (AnnotationMirror am: annotMirrors) - { - if (am.getAnnotationType().toString().equals( - "org.apache.beehive.controls.api.packaging.PropertyInfo")) - { - Map avs = - am.getElementValues(); - for (AnnotationTypeElementDeclaration ated: avs.keySet()) - { - if (ated.toString().equals("editorClass()")) - { - // - // Get the annotation value, and ignore the default value which implies - // no editor class (because 'null' cannot be a default value) - // - String editorClass = avs.get(ated).getValue().toString(); - if (editorClass.equals("org.apache.beehive.controls.api.packaging.PropertyInfo.NoEditor.class")) - return null; - - return editorClass; - } - } - break; - } - } - return null; - } - - AnnotationTypeElementDeclaration _propDecl; - private AptPropertySet _propertySet; - TwoPhaseAnnotationProcessor _ap; -} diff --git a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/generator/AptPropertySet.java b/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/generator/AptPropertySet.java deleted file mode 100644 index 8ba0c39..0000000 --- a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/generator/AptPropertySet.java +++ /dev/null @@ -1,154 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.runtime.generator; - -import java.util.ArrayList; -import java.util.Collection; - -import com.sun.mirror.declaration.AnnotationTypeDeclaration; -import com.sun.mirror.declaration.AnnotationTypeElementDeclaration; -import com.sun.mirror.declaration.MethodDeclaration; -import com.sun.mirror.declaration.Declaration; - -import org.apache.beehive.controls.api.properties.PropertySet; -import org.apache.beehive.controls.runtime.generator.apt.TwoPhaseAnnotationProcessor; - -/** - * The AptPropertySet class represents a control PropertySet where the property list - * is derived using APT metadata - */ -public class AptPropertySet -{ - /** - * Constructs a new AptPropertySet instance from APT metadata - * @param controlIntf the declaring bean interface. May be null (external property set) - * @param propertySet the PropertySet declaration - * @param ap the annotation processor - */ - public AptPropertySet(AptControlInterface controlIntf, - Declaration propertySet, - TwoPhaseAnnotationProcessor ap) - { - _ap = ap; - _controlIntf = controlIntf; - - if (!(propertySet instanceof AnnotationTypeDeclaration)) - { - _ap.printError( propertySet, "propertyset.illegal.usage" ); - return; - } - _propertySet = (AnnotationTypeDeclaration)propertySet; - - _isOptional = _propertySet.getAnnotation(PropertySet.class).optional(); - _hasSetters = _propertySet.getAnnotation(PropertySet.class).hasSetters(); - - _properties = initProperties(); - } - - /** - * Initializes the list of ControlProperties associated with this ControlPropertySet - */ - protected ArrayList initProperties() - { - ArrayList properties = new ArrayList(); - - if (_propertySet == null || _propertySet.getMethods() == null ) - return properties; - - // Add all declared method, but ignore the mystery methods - for (MethodDeclaration methodDecl : _propertySet.getMethods()) - if (!methodDecl.toString().equals("()")) - properties.add( - new AptProperty(this,(AnnotationTypeElementDeclaration)methodDecl,_ap)); - - return properties; - } - - /** - * Returns the list of ControlProperties associated with this ControlPropertySet - */ - public Collection getProperties() { return _properties; } - - /** - * Returns the fully qualified package name of this property set - */ - public String getPackage() - { - if (_propertySet == null || _propertySet.getPackage() == null ) - return ""; - - return _propertySet.getPackage().getQualifiedName(); - } - - /** - * Returns the unqualified classname of this property set - */ - public String getShortName() - { - if (_propertySet == null ) - return ""; - - return _propertySet.getSimpleName(); - } - - /** - * Returns the fully qualified class name of the property set - */ - public String getClassName() - { - if (_propertySet == null ) - return ""; - - return _propertySet.getQualifiedName(); - } - - /** - * Returns the property name prefix for properties in this PropertySet - */ - public String getPrefix() - { - if (_propertySet == null || _propertySet.getAnnotation(PropertySet.class) == null ) - return ""; - - return _propertySet.getAnnotation(PropertySet.class).prefix(); - } - - /** - * Returns whether or not this propertyset exposes setters - */ - public boolean isOptional() - { - return _isOptional; - } - - /** - * Returns whether or not this propertyset exposes setters - */ - public boolean hasSetters() - { - return _hasSetters; - } - - private AnnotationTypeDeclaration _propertySet; - private AptControlInterface _controlIntf; // may be null if an external property set - private ArrayList _properties; - private TwoPhaseAnnotationProcessor _ap; - private boolean _isOptional; - private boolean _hasSetters; -} diff --git a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/generator/AptTask.java b/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/generator/AptTask.java deleted file mode 100644 index a26c73f..0000000 --- a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/generator/AptTask.java +++ /dev/null @@ -1,358 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.runtime.generator; - -import org.apache.tools.ant.BuildException; -import org.apache.tools.ant.DirectoryScanner; -import org.apache.tools.ant.taskdefs.Javac; -import org.apache.tools.ant.types.Commandline; -import org.apache.tools.ant.types.Path; -import org.apache.tools.ant.util.FileUtils; -import org.apache.tools.ant.util.GlobPatternMapper; -import org.apache.tools.ant.util.JavaEnvUtils; -import org.apache.tools.ant.util.SourceFileScanner; - -import java.io.File; -import java.io.IOException; -import java.util.StringTokenizer; -import java.util.Vector; - -/** - * The AptTask class defines a custom ANT task for invoking APT-based code generation. It - * derives from the built-in task, so all of the attributes and nested elements of that - * task are supported, for source list selection, classpath selection, compiler arguments, - * etc. Each of these options will be passed onto APT for processing. - *

- * AptTask also adds some new attributes: - *

    - *
  • gendir - specifies the directory where temporary source files that are produced during - * generation will be kept. - *
  • srcExtensions - provides a comma-separated list of source file extensions that are - * considered valid input to APT. The default value is "*.java". - *
  • - */ -public class AptTask extends Javac -{ - /** - * The srcExtensions attribute can be set to a comma-separated list of source filename - * extensions that are considered to be valid inputs to APT processing. - * The default value is "*.java". - */ - public void setSrcExtensions(String srcExts) - { - StringTokenizer tok = new StringTokenizer(srcExts, ","); - while (tok.hasMoreTokens()) - _srcExts.add(tok.nextToken()); - } - - /** - * The srcExtensions attribute can be set to a comma-separated list of processor options - * (of the form option or option=value) to be passed to - * APT. - */ - public void setProcessorOptions(String processorOptions) - { - StringTokenizer tok = new StringTokenizer(processorOptions, ","); - while (tok.hasMoreTokens()) - _processorOptions.add(tok.nextToken()); - } - - /** - * The gendir attribute specifies the name of the output directory for any files generated - * as a result of calling APT. - */ - public void setGendir(File genDir) - { - _genDir = genDir; - } - - /** - * The nocompile attribute disables compilation of the input source file list and any - * generated sources that are derived from them. The default value is 'false'. - */ - public void setNocompile(boolean nocompile) - { - _nocompile = nocompile; - } - - /** - * The compileByExtension attribute causes each input source extension to be compiled - * independently (and sequentially). This is useful when one type of extensio can - * possibly depend upon the generation output from another. The default value 'false'. - */ - public void setCompileByExtension(boolean compileByExt) - { - _compileByExt = compileByExt; - } - - public void setFactory(String factory) { - _factory = factory; - } - - public void setFactorypath(String factorypath) { - _factorypath = factorypath; - } - - /** - * Override the implementation of scanDir, to look for additional files based upon any - * specified source extensions - */ - protected void scanDir(File srcDir, File destDir, String[] files, String ext) - { - // If no source path was specified, we effectively created one by adding the generation - // path. Because of this, we need to be sure and add all source dirs to the path too. - if (!_hasSourcepath) - { - Path srcPath = new Path(getProject()); - srcPath.setLocation(srcDir); - setSourcepath(srcPath); - } - - GlobPatternMapper m = new GlobPatternMapper(); - m.setFrom(ext); - m.setTo("*.class"); - SourceFileScanner sfs = new SourceFileScanner(this); - if (ext.equals("*.java")) - { - File[] newFiles = sfs.restrictAsFiles(files, srcDir, destDir, m); - if (newFiles.length > 0) - { - File[] newCompileList = new File[compileList.length + newFiles.length]; - System.arraycopy(compileList, 0, newCompileList, 0, compileList.length); - System.arraycopy(newFiles, 0, newCompileList, compileList.length, - newFiles.length); - compileList = newCompileList; - } - } - else - { - String [] newSources = sfs.restrict(files, srcDir, destDir, m); - int extLen = ext.length() - 1; // strip wildcard - if (newSources.length > 0) - { - File[] newCompileList = new File[compileList.length + newSources.length]; - System.arraycopy(compileList, 0, newCompileList, 0, compileList.length); - try - { - FileUtils fileUtils = FileUtils.newFileUtils(); - for (int j = 0; j < newSources.length; j++) - { - String toName = - newSources[j].substring(0, newSources[j].length() - extLen) + - ".java"; - - File srcFile = new File(srcDir, newSources[j]); - File dstFile = new File(_genDir, toName); - fileUtils.copyFile(srcFile, dstFile, null, true, true); - newCompileList[compileList.length + j] = dstFile; - } - } - catch (IOException ioe) - { - throw new BuildException("Unable to copy " + ext + " file", ioe, - getLocation()); - } - compileList = newCompileList; - } - } - } - - public void execute() throws BuildException - { - // Ensure that the gendir attribute was specified - if (_genDir == null) - throw new BuildException("Missing genDir attribute: must be set to codegen output directory", getLocation()); - - - // If no source extension specified, then just process .java files - if (_srcExts.size() == 0) - _srcExts.add("*.java"); - - // Save whether a user sourcepath was provided, and if so, the paths - String[] userSourcepaths = null; - _hasSourcepath = getSourcepath() != null; - if ( _hasSourcepath ) - userSourcepaths = getSourcepath().list(); - - // The generation dir is always added to the source path for compilation - Path genPath = new Path(getProject()); - genPath.setLocation(_genDir); - setSourcepath(genPath); - - // If the user sourcepath specifies subdirs underneath the srcdir, then we need to add - // the corresponding subdirs under the gendir to the source path for compilation. - // For example, if the user sourcepath is ";\WEB-INF\src", - // then the sourcepath for compilation should include ";\WEB-INF\src". - if ( _hasSourcepath ) - { - String srcDirPath = (getSrcdir().list())[0]; // TODO: handle multiple srcdirs - for ( String p: userSourcepaths ) - { - if ( p.startsWith( srcDirPath ) && p.length() > srcDirPath.length() ) - { - File genDirElem = new File( _genDir, p.substring( srcDirPath.length()+1 )); - Path gp = new Path(getProject()); - gp.setLocation( genDirElem ); - setSourcepath(gp); - } - } - } - - // Select the executable (apt) and set fork = true - if(getExecutable() == null) - setExecutable(JavaEnvUtils.getJdkExecutable("apt")); - setFork(true); - - // Specify the code generation output directory to APT - Commandline.Argument arg = createCompilerArg(); - arg.setValue("-s"); - arg = createCompilerArg(); - arg.setFile(_genDir); - - // Add the -nocompile flag if set to true - if(_nocompile) - { - Commandline.Argument ncarg = createCompilerArg(); - ncarg.setValue("-nocompile"); - } - - // Add processor options. - for (Object i : _processorOptions) - { - Commandline.Argument optionArg = createCompilerArg(); - optionArg.setValue("-A" + i); - } - - checkParameters(); - resetFileLists(); - - // - // Allow user to define apt specific options for the name of an - // annotation processor (AP) factory to use or the factory path - // for finding the AP factories. This allows apt to bypass the - // default discovery process or specify where to find AP factories. - // - // This can help resolve build issues users may experience when - // multiple annotation processors conflict. For example,... - // A project may contain JAX-RPC 1.1 Web Services annotations. - // Starting with JDK1.6, JDK bundles the JAX-WS 2.0 AP in its - // tool jar. JAX-RPC and JAX-WS use the same JSR 181 annotations - // but the JAX-WS 2.0 AP doesn't support the earlier JAX-RPC use - // of the RPC/ENCODED soapbinding annotation on an endpoint. - // A user running the build through the Beehive AptTask and using - // Java 6, would see APT fail on JAX-RPC services thinking they are - // invalid JAX-WS services. - // - // In this example, using the -factorypath option does not disable the - // built-in annotation processor because tools.jar is always in APT's - // class path. However, exposing the option to use a specific factory - // can solve this problem. There can only be one factory name when - // invoking APT, so a user of this task may want to pass a wrapper - // factory that is an aggregated annotation processor factory. - // - if (_factorypath != null && _factorypath.trim().length() > 0) { - Commandline.Argument factoryArg = createCompilerArg(); - factoryArg.setValue("-factorypath"); - factoryArg = createCompilerArg(); - factoryArg.setValue(_factorypath); - } - - if (_factory != null && _factory.trim().length() > 0) { - Commandline.Argument factoryArg = createCompilerArg(); - factoryArg.setValue("-factory"); - factoryArg = createCompilerArg(); - factoryArg.setValue(_factory); - } - - // Iterate through the list of input extensions, matching/dependency - // checking based upon the input list. - for (int j = 0; j < _srcExts.size(); j++) - { - String ext = (String)_srcExts.get(j); - Vector inputFiles = new Vector(); - - // scan source directories and dest directory to build up - // compile lists - String[] list = getSrcdir().list(); - File destDir = getDestdir(); - for (int i = 0; i < list.length; i++) - { - File srcFile = getProject().resolveFile(list[i]); - if (!srcFile.exists()) { - throw new BuildException("srcdir \"" - + srcFile.getPath() - + "\" does not exist!", getLocation()); - } - - // - // The base algorithm is tweaked here, to allow elements - // to contain a list of files _or_ a list of directories to scan. - // - if (srcFile.isDirectory()) - { - DirectoryScanner ds = this.getDirectoryScanner(srcFile); - String[] files = ds.getIncludedFiles(); - scanDir(srcFile, destDir != null ? destDir : srcFile, files, ext); - } - else - { - // - // BUGBUG: Because these bypass scanning, they also bypass dependency chks :( - // - if (srcFile.getPath().endsWith(ext.substring(1))) - inputFiles.add(srcFile); - } - } - - if (inputFiles.size() != 0) - { - File[] newCompileList = new File[compileList.length + inputFiles.size()]; - inputFiles.toArray(newCompileList); - System.arraycopy(compileList, 0, newCompileList, inputFiles.size(), - compileList.length); - compileList = newCompileList; - } - - // - // If processing/compiling on a per-extension basis, then handle the current list, - // then reset the list fo files to compile before moving to the next extension - // - if (_compileByExt) - { - compile(); - resetFileLists(); - } - } - - // - // If not processing on a per-extension basis, then compile the entire aggregated list - // - if (!_compileByExt) - compile(); - } - - protected boolean _nocompile = false; - protected boolean _compileByExt = false; - protected boolean _hasSourcepath; - protected File _genDir; - protected Vector/**/ _srcExts = new Vector/**/(); - protected Vector/**/ _processorOptions = new Vector/**/(); - protected String _factory = null; - protected String _factorypath = null; -} diff --git a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/generator/AptType.java b/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/generator/AptType.java deleted file mode 100644 index 0393343..0000000 --- a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/generator/AptType.java +++ /dev/null @@ -1,168 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.runtime.generator; - -import java.util.Collection; - -import com.sun.mirror.declaration.TypeDeclaration; -import com.sun.mirror.declaration.TypeParameterDeclaration; -import com.sun.mirror.declaration.MethodDeclaration; -import com.sun.mirror.declaration.Modifier; - -/** - * The AptType abstract class defines a base set of methods that are generally available - * for template usage on type declaration objects - */ -public class AptType -{ - /** - * Sets the TypeDeclaration associated with this AptType. - */ - protected void setDeclaration(TypeDeclaration typeDecl) - { - _typeDecl = typeDecl; - } - - /** - * Checks a MethodDeclaration for a 'private' modifier. - * - * @param md MethodDeclaration to check. - * @return true if private modifier is present. - */ - protected boolean isPrivateMethod(MethodDeclaration md) - { - Collection modifiers = md.getModifiers(); - for (Modifier m : modifiers) - { - if (m.compareTo(Modifier.PRIVATE) == 0) - return true; - } - return false; - } - - /** - * Returns the fully qualified classname of this AptType - */ - public String getClassName() - { - if ( _typeDecl == null) - return ""; - - return _typeDecl.getQualifiedName(); - } - - /** - * Returns the base package name associated with the AptType - */ - public String getPackage() - { - if ( _typeDecl == null) - return ""; - - return _typeDecl.getPackage().getQualifiedName(); - } - - /** - * Returns the unqualified class name associated with the AptType - */ - public String getShortName() - { - if ( _typeDecl == null ) - return ""; - - return _typeDecl.getSimpleName(); - } - - /** - * Helper method to return type parameter information - */ - private String getFormalTypeParameters(boolean namesOnly) - { - Collection ftColl = _typeDecl.getFormalTypeParameters(); - if (ftColl.size() == 0) - return ""; - - StringBuffer sb = new StringBuffer("<"); - boolean isFirst = true; - for (TypeParameterDeclaration tpDecl : ftColl) - { - if (!isFirst) - sb.append(","); - else - isFirst = false; - - if (namesOnly) - sb.append(tpDecl.getSimpleName()); - else - sb.append(tpDecl.toString()); - } - sb.append(">"); - return sb.toString(); - } - - /** - * Returns the full formal type parameter declaration associated with the type declaration - */ - public String getFormalTypeParameters() - { - return getFormalTypeParameters(false); - } - - /** - * Returns the name of any formal type parameter names associated with the type declaration. - */ - public String getFormalTypeParameterNames() - { - return getFormalTypeParameters(true); - } - - /** - * Returns the short name and the names of any formal type parameters associated with - * the type. The format is suitable for use in location (such as variable declarations - * or extends clauses) where you want formal type parameters listed. - */ - public String getFormalShortName() - { - StringBuffer sb = new StringBuffer(getShortName()); - sb.append(getFormalTypeParameterNames()); - return sb.toString(); - } - - /** - * Returns the class name and the names of any formal type parameters associated with - * the type. The format is suitable for use in location (such as variable declarations - * or extends clauses) where you want formal type parameters listed. - */ - public String getFormalClassName() - { - StringBuffer sb = new StringBuffer(getClassName()); - sb.append(getFormalTypeParameterNames()); - return sb.toString(); - } - - /** - * Returns the underlying type declaration name - */ - public TypeDeclaration getTypeDeclaration() - { - return _typeDecl; - } - - TypeDeclaration _typeDecl; -} diff --git a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/generator/ClientInitializer.java b/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/generator/ClientInitializer.java deleted file mode 100644 index 0d44df3..0000000 --- a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/generator/ClientInitializer.java +++ /dev/null @@ -1,112 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.runtime.generator; - -import java.util.ArrayList; - -/** - * The ClientInitializer represents a generated class that contains the code - * necessary to initialize a client that uses controls declaratively (via Control and - * EventHandler annotations). - */ -public class ClientInitializer -{ - /** - * Constructs a new ClientInitializer class - * @param controlClient the control client this initializer will target - */ - protected ClientInitializer(AptControlClient controlClient) - { - super(); - - assert controlClient != null; - - _controlClient = controlClient; - _packageName = _controlClient.getPackage(); - _shortName = _controlClient.getShortName() + "ClientInitializer"; - _className = isRootPackage() ? _shortName : _packageName + "." + _shortName; - - // - // Compute the list of impl fields that will require reflected Fields. This is - // done unconditionally for all @Control fields (to support PropertyMap initialization) - // - - _reflectFields = new ArrayList(); - for (AptField genField : _controlClient.getControls()) - _reflectFields.add(genField); - } - - /** - * Returns the package name of the ClientInitializer - */ - public String getPackage() { return _packageName; } - - /** - * Is the ClientInitializer in the root package? - */ - public boolean isRootPackage() { return getPackage() == null || getPackage().equals(""); } - - /** - * Returns the unqualified classname of the ClientInitializer - */ - public String getShortName() { return _shortName; } - - /** - * Returns the fully qualfied classname of the ClientInitializer - */ - public String getClassName() { return _className; } - - /** - * Returns the ControlBean implementation instance - */ - public AptControlClient getControlClient() { return _controlClient; } - - public ClientInitializer getSuperClass() { return null; } - - /** - * Returns true if the initializer will use Reflection to initialize the field, false - * otherwise. - */ - static public boolean needsReflection(AptField genField) - { - // - // Since initializers are generated into the same package as the initialized class, - // only private access fields require reflection - // - String accessModifier = genField.getAccessModifier(); - if (accessModifier.equals("private")) - return true; - - return false; - } - - /** - * Returns the list of impl class fields that must be initialized using Reflection - */ - public ArrayList getReflectFields() - { - return _reflectFields; - } - - String _packageName; - String _shortName; - String _className; - AptControlClient _controlClient; - ArrayList _reflectFields; -} diff --git a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/generator/CodeGenerationException.java b/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/generator/CodeGenerationException.java deleted file mode 100644 index eba6226..0000000 --- a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/generator/CodeGenerationException.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.runtime.generator; - -/** - * A simple exception wrapper class used for code generation failures. These is a runtime - * exception, because user errors that result in code generation failures are reported - * through the APT messager class. - */ -public class CodeGenerationException extends RuntimeException -{ - public CodeGenerationException() { - super(); - } - - public CodeGenerationException(String msg, Exception e) { - super(msg, e); - } - - public CodeGenerationException(String msg) { - super(msg); - } - - public CodeGenerationException(Exception e) { - super("Code Generation Exception", e); - } -} - diff --git a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/generator/CodeGenerator.java b/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/generator/CodeGenerator.java deleted file mode 100644 index 0ee23d8..0000000 --- a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/generator/CodeGenerator.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.runtime.generator; - -/** - * The CodeGenerator class is an abstract base class that encapsulates the invocation - * Apache Velocity or other code generation tools that generate source artifacts. - *

    - * This primary motivation for this abstraction is to decouple the loading and invocation - * of Velocity from the mainline control generation process. - */ -abstract public class CodeGenerator -{ - public CodeGenerator() { - } - - abstract public void generate(GeneratorOutput genOut) throws CodeGenerationException; -} diff --git a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/generator/ControlBean.java b/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/generator/ControlBean.java deleted file mode 100644 index 486c372..0000000 --- a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/generator/ControlBean.java +++ /dev/null @@ -1,132 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.runtime.generator; - -import com.sun.mirror.type.InterfaceType; - -/** - * The ControlBean class is an class representing a generated JavaBean class that can host - * control implementation types associated with a particular control public or extension - * interface. - */ -public class ControlBean -{ - /** - * Constructs a new ControlBean class supporting a particular bean interface - * @param controlIntf the public interface associated with the bean - */ - protected ControlBean(AptControlInterface controlIntf) - { - super(); - _controlIntf = controlIntf; - if (_controlIntf != null) - { - _packageName = _controlIntf.getPackage(); - _shortName = _controlIntf.getShortName() + "Bean"; - _className = isRootPackage() ? _shortName : _packageName + "." + _shortName; - - _superClass = new ControlBean(_controlIntf.getSuperClass()); - } - else - { - Class c = org.apache.beehive.controls.runtime.bean.ControlBean.class; - _packageName = c.getPackage().getName(); - _className = c.getName(); - _shortName = _className.substring(_packageName.length() + 1); - } - } - - /** - * Return whether the ControlBean is contained in a package. - */ - public boolean isRootPackage() { - return _packageName == null || _packageName.trim().equals(""); - } - - /** - * Returns the fully qualified package name of the ControlBean - */ - public String getPackage() { return _packageName; } - - /** - * Returns the unqualified classname of the ControlBean - */ - public String getShortName() { return _shortName; } - - /** - * Returns the fully qualified classname of the ControlBean - */ - public String getClassName() { return _className; } - - /** - * Returns the class declaration for the ControlBean - */ - public String getClassDeclaration() - { - StringBuffer sb = new StringBuffer(_shortName); - sb.append(_controlIntf.getFormalTypeParameters()); - return sb.toString(); - } - - /** - * Returns the fully qualified classname of the ControlBean BeanInfo class. The - * standard JavaBean naming convention is used to enable automatic location by - * the JavaBean introspector. - */ - public String getBeanInfoName() { return _className + "BeanInfo"; } - - - /** - * Returns the class as a Jar Manifest Name attribute - */ - public String getManifestName() { return _className.replace('.','/') + ".class"; } - - /** - * Returns the public or extension interface associated with the ControlBean - */ - public AptControlInterface getControlInterface() { return _controlIntf; } - - /** - * Returns the super class for this ControlBean - */ - public ControlBean getSuperClass() { return _superClass; } - - /** - * Returns any formal type parameters that should be bound for the bean's superclass, - * based upon any type bindings that occur on the original interface. - */ - public String getSuperTypeBinding() - { - InterfaceType superType = _controlIntf.getSuperType(); - if (superType != null) - { - String typeStr = superType.toString(); - int paramIndex = typeStr.indexOf('<'); - if (paramIndex > 0) - return typeStr.substring(paramIndex); - } - return ""; - } - - String _packageName; - String _shortName; - String _className; - AptControlInterface _controlIntf; - ControlBean _superClass; -} diff --git a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/generator/EventAdaptor.java b/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/generator/EventAdaptor.java deleted file mode 100644 index 119a507..0000000 --- a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/generator/EventAdaptor.java +++ /dev/null @@ -1,154 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.runtime.generator; - -import java.util.HashMap; - -import com.sun.mirror.type.TypeMirror; -import com.sun.mirror.declaration.TypeParameterDeclaration; - -/** - * The EventAdaptor class represents the generated class that is necessary to route - * events for a EventSet onto implemented EventHandlers on an implementation class. - */ -public class EventAdaptor -{ - /** - * Constructs a new EventAdaptor for events declared on an EventSet - */ - public EventAdaptor(AptEventField eventField, AptEventSet eventSet) - { - _eventField = eventField; - _eventSet = eventSet; - _className = initClassName(); - } - - /** - * Computes a unique adaptor class name - */ - private String initClassName() - { - StringBuffer sb = new StringBuffer(); - String fieldName = _eventField.getName(); - String setName = _eventSet.getClassName(); - sb.append(Character.toUpperCase(fieldName.charAt(0))); - if (fieldName.length() > 1) - sb.append(fieldName.substring(1)); - sb.append(setName.substring(setName.lastIndexOf('.') + 1)); - sb.append("EventAdaptor"); - return sb.toString(); - } - - /** - * Returns the name of the generated class for this adaptor. - */ - public String getClassName() - { - return _className; - } - - /** - * Returns the name of the generated class for this adaptor, including any formal type - * declarations from the associate event set. - */ - public String getFormalClassName() - { - StringBuffer sb = new StringBuffer(_className); - sb.append(_eventSet.getFormalTypeParameters()); - return sb.toString(); - } - - /** - * Returns the event field associated with this event adaptor - */ - public AptEventField getEventField() { return _eventField; } - - /** - * Returns the EventSet associated with this Adaptor - */ - public AptEventSet getEventSet() { return _eventSet; } - - /** - * Adds a new EventHandler for a Event to the EventAdaptor - */ - public void addHandler(AptEvent event, AptMethod eventHandler) - { - assert event.getEventSet() == _eventSet; - _handlerMap.put(event, eventHandler); - } - - /** - * Returns true if there is an EventHandler for ControlEvent on this EventAdaptor - */ - public boolean hasHandler(AptEvent event) - { - return _handlerMap.containsKey(event); - } - - /** - * Returns the EventHandler for a ControlEvent on this EventAdaptor - */ - public AptMethod getHandler(AptEvent event) - { - return _handlerMap.get(event); - } - - /** - * Returns any formal type parameter declaration for EventSet interface associated with - * the adaptor class. This will bind the formal types of the interface based on any type - * binding from the event field declaration - */ - public String getEventSetBinding() - { - // Get the type bindings for the associated event field. - HashMap typeBinding = _eventField.getTypeBindingMap(); - - StringBuffer sb = new StringBuffer(); - boolean isFirst = true; - for (TypeParameterDeclaration tpd : - _eventSet.getDeclaration().getFormalTypeParameters()) - { - if (isFirst) - { - sb.append("<"); - isFirst = false; - } - else - sb.append(", "); - - // Map from the declared formal type name to the bound type name - // If no map entry exists (i.e. not bindings were specified on the field - // declaration, then the implied binding is to Object.class - String typeName = tpd.getSimpleName(); - if (typeBinding.containsKey(typeName)) - sb.append(typeBinding.get(tpd.getSimpleName())); - else - sb.append("java.lang.Object"); - } - if (!isFirst) - sb.append(">"); - - return sb.toString(); - } - - private String _className; - private AptEventField _eventField; - private AptEventSet _eventSet; - private HashMap _handlerMap = new HashMap(); -} diff --git a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/generator/GenClass.java b/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/generator/GenClass.java deleted file mode 100644 index dfac951..0000000 --- a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/generator/GenClass.java +++ /dev/null @@ -1,89 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.runtime.generator; - -import java.io.IOException; -import java.util.List; - -import com.sun.mirror.apt.Filer; - -/** - * The GenClass abstract class defines a base set of methods that are generally available - * for template usage on class-type objects - *

    - * This is done with an abstract class (instead of an interface) so derived abstract classes - * can be subclassed from it w/out requiring all of the methods to be declared there. - */ -abstract public class GenClass -{ - /** - * Returns the fully qualified classname associated with the GenClass - */ - abstract public String getClassName(); - - /** - * Returns the base package name associated with the GenClass - */ - abstract public String getPackage(); - - /** - * Returns the unqualified class name associated with the GenClass - */ - abstract public String getShortName(); - - /** - * Returns the super class for this class - */ - abstract public GenClass getSuperClass(); - - /** - * Returns true if the GenClass extends another class - */ - public boolean hasSuperClass() - { - return getSuperClass() != null; - } - - /** - * Returns the list of fully qualified class names for types that are derived - * from this GenClass - */ - public String [] getGeneratedTypes() - { - return null; - } - - /** - * Returns the list of generated files derived from this GenClass during the - * check phase of annotation processing. - */ - public List getCheckOutput(Filer filer) throws IOException - { - return null; - } - - /** - * Returns the list of generated files derived from this GenClass during the - * generate phase of annotation processing. - */ - public List getGenerateOutput(Filer filer) throws IOException - { - return null; - } -} diff --git a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/generator/Generator.java b/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/generator/Generator.java deleted file mode 100644 index e9b9dfb..0000000 --- a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/generator/Generator.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.runtime.generator; - -import java.io.IOException; -import java.util.List; - -import com.sun.mirror.apt.Filer; - -/** - * The Generator interface will be implemented by APT data types that result in the generation - * of new source or text artifacts. - * for template usage on class-type objects - *

    - * This is done with an abstract class (instead of an interface) so derived abstract classes - * can be subclassed from it w/out requiring all of the methods to be declared there. - */ -public interface Generator -{ - /** - * Returns the list of fully qualified class names for types that are derived - * from this Generator - */ - public String [] getGeneratedTypes(); - - /** - * Returns the list of generated files derived from this Generator during the - * check phase of annotation processing. - */ - public List getCheckOutput(Filer filer) throws IOException; - - /** - * Returns the list of generated files derived from this Generator during the - * generate phase of annotation processing. - */ - public List getGenerateOutput(Filer filer) throws IOException; -} diff --git a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/generator/GeneratorOutput.java b/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/generator/GeneratorOutput.java deleted file mode 100644 index f311fb7..0000000 --- a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/generator/GeneratorOutput.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.runtime.generator; - -import java.io.Writer; -import java.util.HashMap; - -/** - * The GeneratorOutput class represents a single file output by the code generation process, - * as well as the template and context information necessary to generate it. - */ -public class GeneratorOutput -{ - public GeneratorOutput(Writer outWriter, String templateName, HashMap context) - { - _outWriter = outWriter; - _templateName = templateName; - _context = context; - } - - public String getTemplateName() { - return _templateName; - } - - public HashMap getContext() { - return _context; - } - - public Writer getWriter() { - return _outWriter; - } - - String _templateName; - Writer _outWriter; - HashMap _context; -} diff --git a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/generator/ImplInitializer.java b/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/generator/ImplInitializer.java deleted file mode 100644 index 59363b6..0000000 --- a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/generator/ImplInitializer.java +++ /dev/null @@ -1,148 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.runtime.generator; - -import java.util.ArrayList; - -/** - * The ImplInitializer class is a generated class that contains the code necessary to initialize - * a ControlBean implementation instance. - */ -public class ImplInitializer -{ - /** - * Constructs a new ImplInitializer class supporting a particular control bean implementation - * @param controlImpl the control implementation to be initialized - */ - protected ImplInitializer(AptControlImplementation controlImpl) - { - super(); - _controlImpl = controlImpl; - _controlIntf = _controlImpl.getControlInterface(); - if (_controlImpl != null) - { - _packageName = _controlImpl.getPackage(); - _shortName = _controlImpl.getShortName() + "Initializer"; - _className = _packageName + "." + _shortName; - if (_controlImpl.getSuperClass() != null) - _superClass = new ImplInitializer(_controlImpl.getSuperClass()); - } - else - { - Class c = org.apache.beehive.controls.runtime.bean.ImplInitializer.class; - _packageName = c.getPackage().getName(); - _className = c.getName(); - _shortName = _className.substring(_packageName.length() + 1); - } - - // - // Compute the list of impl fields that will require reflected Fields. - // - _reflectFields = new ArrayList(); - for (AptField genField : _controlImpl.getContexts()) - if (needsReflection(genField)) - _reflectFields.add(genField); - for (AptField genField : _controlImpl.getClients()) - if (needsReflection(genField)) - _reflectFields.add(genField); - } - - /* - * Return whether the ControlBean is contained in a package. - */ - public boolean isRootPackage() { - return _packageName == null || _packageName.trim().equals(""); - } - - /** - * Returns the package name of the ImplInitializer - */ - public String getPackage() { return _packageName; } - - /** - * Returns the unqualified classname of the ImplInitializer - */ - public String getShortName() { return _shortName; } - - /** - * Returns the fully qualfied classname of the ImplInitializer - */ - public String getClassName() { return _className; } - - /** - * Returns the fully qualified classname of any associated ClientInitializer - */ - public String getClientInitializerName() - { - return _controlImpl.getClassName() + "ClientInitializer"; - } - - /** - * Returns the ControlBean implementation instance - */ - public AptControlImplementation getControlImplementation() { return _controlImpl; } - - /** - * Returns the public or extension interface associated with the ControlBean implementation - */ - public AptControlInterface getControlInterface() { return _controlIntf; } - - /** - * Returns the ImplInitializer super class for this ImplInitializer - */ - public ImplInitializer getSuperClass() { return _superClass; } - - /** - * Returns true if the ImplInitializer has a super class - */ - public boolean hasSuperClass() { return _superClass != null; } - - /** - * Returns true if the initializer will use Reflection to initialize the field, false - * otherwise. - */ - static public boolean needsReflection(AptField genField) - { - // - // Since initializers are generated into the same package as the initialized class, - // only private access fields require reflection - // - String accessModifier = genField.getAccessModifier(); - if (accessModifier.equals("private")) - return true; - - return false; - } - - /** - * Returns the list of impl class fields that must be initialized using Reflection - */ - public ArrayList getReflectFields() - { - return _reflectFields; - } - - String _packageName; - String _shortName; - String _className; - AptControlImplementation _controlImpl; - AptControlInterface _controlIntf; - ImplInitializer _superClass; - ArrayList _reflectFields; -} diff --git a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/generator/IndentingWriter.java b/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/generator/IndentingWriter.java deleted file mode 100644 index d4adaaf..0000000 --- a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/generator/IndentingWriter.java +++ /dev/null @@ -1,122 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.runtime.generator; - -import java.io.IOException; -import java.io.Writer; - -/** - * The IndentingWriter class is a simple implementation of an indenting code writer - */ -public class IndentingWriter extends Writer -{ - /** current depth: - *

    -     * // depth = 0;
    -     * {
    -     *   // depth now is 2
    -     *   {
    -     *     // depth now is 4
    -     *   }
    -     *   // depth now is 2
    -     * }
    -     * // depth now is 0
    -     * 
    - */ - protected int depth = 0; - - public IndentingWriter(Writer delegate) - { - this(delegate, - Integer.getInteger("org.apache.beehive.controls.runtime.generator.indentLevel", 4).intValue()); - } - - public IndentingWriter(Writer delegate, int indentLevel) - { - _out = delegate; - this._indentLevel = indentLevel; - } - - public void write(char cbuf[], int off, int len) throws IOException - { - if (off < 0 || off + len > cbuf.length) - throw new ArrayIndexOutOfBoundsException(); - - for (int i = off; i < off + len; i++) - { - char c = cbuf[i]; - if (c == '}') - { - decrDepth(); - } - else if ((c == ' ' || c == '\t') && _needIndent) - { - continue; - } - - if (_needIndent) - indent(); - _out.write(c); - - if (c == '\n') - { - _needIndent = true; - } - else if (c == '{') - { - incrDepth(); - } - } - } - - public void flush() throws IOException - { - _out.flush(); - } - - public void close() throws IOException - { - _out.close(); - } - - private void indent() throws IOException - { - for (int i = 0; i < depth; i++) - { - _out.write(' '); - } - _needIndent = false; - } - - private void incrDepth() - { - depth += _indentLevel; - } - - private void decrDepth() - { - depth -= _indentLevel; - if (depth < 0) - depth = 0; - } - - protected Writer _out; - protected int _indentLevel; - private boolean _needIndent = false; -} diff --git a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/generator/VelocityAptLogSystem.java b/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/generator/VelocityAptLogSystem.java deleted file mode 100644 index 43b4488..0000000 --- a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/generator/VelocityAptLogSystem.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.runtime.generator; - -import org.apache.velocity.runtime.RuntimeServices; -import org.apache.velocity.runtime.log.LogSystem; - -import com.sun.mirror.apt.Messager; - -/** - * The VelocityAptLogSystem implements the org.apache.velocity.runtime.LogSystem - * interface for logging messages from Velocity and routes warnings and errors to the log - * system of APT. - */ -public class VelocityAptLogSystem implements LogSystem -{ - /** - * This is the name of the Velocity configuration property that will be used to pass - * the APT environment from the execution environment into the logger instance. This - * property must be set on the VelocityEngine instance, and the value should be the - * com.sun.mirror.apt.Messager instance that should be used to log messages. - */ - static final String APT_ENV_PROPERTY = VelocityAptLogSystem.class + "." + "environment"; - - /** - * The prefix to apply to Velocity error and warnings before passing to APT, to make it - * easier to identify Velocity output - */ - static final private String MESSAGE_PREFIX = "VELOCITY: "; - - /** - * This can be set to true when debugging Velocity codegen templates to have all output - * from Velocity sent to the APT logger - */ - static final private boolean _debugging = false; - - public VelocityAptLogSystem(Messager messager) - { - _messager = messager; - } - - public void init(RuntimeServices rs) throws java.lang.Exception - { - } - - public void logVelocityMessage(int level, java.lang.String message) - { - if (level == LogSystem.ERROR_ID) - _messager.printError(MESSAGE_PREFIX + message); - else if (level == LogSystem.WARN_ID) - _messager.printWarning(MESSAGE_PREFIX + message); - else if (_debugging) - _messager.printNotice(MESSAGE_PREFIX + message); - } - - Messager _messager; -} diff --git a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/generator/VelocityGenerator.java b/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/generator/VelocityGenerator.java deleted file mode 100644 index 81be05a..0000000 --- a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/generator/VelocityGenerator.java +++ /dev/null @@ -1,106 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.runtime.generator; - -import java.io.Writer; -import java.util.HashMap; - -import org.apache.velocity.VelocityContext; -import org.apache.velocity.Template; -import org.apache.velocity.app.VelocityEngine; -import org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader; - -import com.sun.mirror.apt.AnnotationProcessorEnvironment; - -/** - * The VelocityGenerator class is an implementation of CodeGenerator that uses standard - * Apache Velocity classes from the system classpath. - */ -public class VelocityGenerator extends CodeGenerator -{ - public VelocityGenerator(AnnotationProcessorEnvironment env) throws Exception - { - super(); - - // Create a Velocity engine instance to support codgen - _ve = new VelocityEngine(); - _ve.setProperty(VelocityEngine.RESOURCE_LOADER, "class"); - _ve.setProperty("class." + VelocityEngine.RESOURCE_LOADER + ".class", - ClasspathResourceLoader.class.getName()); - _ve.setProperty("velocimacro.library", - "org/apache/beehive/controls/runtime/generator/ControlMacros.vm"); - - // Use the VelocityAptLogSystem to bridge Velocity warnings and errors back to APT - VelocityAptLogSystem logger = new VelocityAptLogSystem(env.getMessager()); - _ve.setProperty(VelocityEngine.RUNTIME_LOG_LOGSYSTEM, logger); - - _ve.init(); - } - - /** - * Implementation of the CodeGenerator.generate() method, using standard Velocity - * package naming conventions and the system class loader - */ - public void generate(GeneratorOutput genOut) throws CodeGenerationException - { - // - // Create a new VelocityContext - // - VelocityContext vc = new VelocityContext(); - - // - // Transfer any code generation properties excepted by the templates into the context - // - HashMap genContext = genOut.getContext(); - for(String key : genContext.keySet()) - vc.put(key, genContext.get(key)); - - try - { - Writer genWriter = genOut.getWriter(); - Template template = getTemplate(genOut.getTemplateName()); - template.merge(vc, genWriter); - genWriter.close(); - } - // never wrap RuntimeException - catch (RuntimeException re) { - throw re; - } - catch (Exception e) { - throw new CodeGenerationException(e); - } - } - - // - // Returns the requested template, and caches the result for subsequent requests using the - // same template. - // - public Template getTemplate(String templateName) throws Exception - { - if (_templateMap.containsKey(templateName)) - return _templateMap.get(templateName); - - Template t = _ve.getTemplate(templateName); - _templateMap.put(templateName, t); - return t; - } - - private HashMap _templateMap = new HashMap(); - private VelocityEngine _ve; -} diff --git a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/generator/apt/AnnotationConstraintAptValidator.java b/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/generator/apt/AnnotationConstraintAptValidator.java deleted file mode 100644 index 0a3d2a7..0000000 --- a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/generator/apt/AnnotationConstraintAptValidator.java +++ /dev/null @@ -1,187 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.runtime.generator.apt; - -import java.io.File; -import java.lang.annotation.Annotation; -import java.lang.reflect.Method; -import java.net.MalformedURLException; -import java.net.URI; -import java.net.URL; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Date; -import java.util.Iterator; -import java.util.Map; -import java.util.Map.Entry; - -import org.apache.beehive.controls.api.bean.AnnotationMemberTypes; -import org.apache.beehive.controls.api.bean.AnnotationConstraints.MembershipRule; -import org.apache.beehive.controls.api.bean.AnnotationConstraints.MembershipRuleValues; -import org.apache.beehive.controls.api.properties.PropertyKey; -import org.apache.beehive.controls.api.properties.PropertySet; -import org.apache.beehive.controls.runtime.bean.AnnotationConstraintValidator; - -import com.sun.mirror.declaration.AnnotationMirror; -import com.sun.mirror.declaration.AnnotationTypeDeclaration; -import com.sun.mirror.declaration.AnnotationTypeElementDeclaration; -import com.sun.mirror.declaration.AnnotationValue; -import com.sun.mirror.declaration.Declaration; -import com.sun.mirror.declaration.MethodDeclaration; -import com.sun.mirror.declaration.TypeDeclaration; -import com.sun.mirror.type.AnnotationType; - -/** - * This class is for validating control property values at build time - * It calls {@link org.apache.beehive.controls.runtime.bean.AnnotationConstraintValidator - * AnnotationConstraintValidator} to do the validation. - */ -public class AnnotationConstraintAptValidator extends AnnotationConstraintValidator -{ - - public AnnotationConstraintAptValidator() - { - super(); - } - - /** - * This method ensures that any control property value assignment satisfies - * all property constraints. This method should be called from an annotation - * processor to ensure declarative control property assignment using - * annotations are validated at build time. This method is currently called - * from ControlAnnotationProcessor and ControlClientAnnotationProcessor. - * - * @param d - * a declaration which may contain a control property value - * assignment - * @throws IllegalArgumentException - * when the declaration contains a control property value - * assignment that does not satisfy a property constraint. - */ - public static void validate(Declaration d) throws IllegalArgumentException - { - Collection mirrors = d.getAnnotationMirrors(); - - // for each annotations defined on the declaration, if the annotation - // is a PropertySet, ensure the values assigned to the properties - // satisfy all PropertySet and PropertyType constraints. - for (AnnotationMirror m : mirrors) - { - AnnotationTypeDeclaration decl = m.getAnnotationType().getDeclaration(); - /* - when embedding this annotation processor in an IDE, the declaration - could be null when it doesn't resolve to a valid type. In this case, - just continue processing declarations. - */ - if(decl == null) { - continue; - } - else if (decl.getAnnotation(PropertySet.class) != null) - { - Iterator> i = - m.getElementValues().entrySet().iterator(); - while (i.hasNext()) - { - Map.Entry entry = - i.next(); - Collection annotations = getMemberTypeAnnotations(entry.getKey()); - if (annotations.size() > 0) - { - Annotation[] anArray = new Annotation[annotations.size()]; - annotations.toArray(anArray); - validate(anArray, entry.getValue().getValue()); - } - } - - //If a membership rule is defined on the property set, ensure the rule is satisfied. - if (decl.getAnnotation(MembershipRule.class) != null) - { - try - { - String declClassName = decl.getQualifiedName(); - - TypeDeclaration owningClass = decl.getDeclaringType(); - if (owningClass != null) - declClassName = owningClass.getQualifiedName() + "$" + decl.getSimpleName(); - - Class clazz = Class.forName(declClassName); - Annotation a = d.getAnnotation(clazz); - validateMembership(a); - } - catch (ClassNotFoundException cnfe) - { - //should not happen - } - } - } - } - - // If the declaration is a class or interface, validate its methods - // and fields. - if (d instanceof TypeDeclaration) - { - TypeDeclaration td = ((TypeDeclaration) d); - for (Declaration md : td.getMethods()) - validate(md); - for (Declaration fd : td.getFields()) - validate(fd); - } - // If the delcaration is a method, validate its parameters. - else if (d instanceof MethodDeclaration) - { - for (Declaration pd : ((MethodDeclaration) d).getParameters()) - validate(pd); - } - - } - - private static Collection getMemberTypeAnnotations(Declaration decl) - { - Collection annotations = new ArrayList(); - for (AnnotationMirror am : decl.getAnnotationMirrors()) - { - AnnotationType at = am.getAnnotationType(); - try - { - if (at.getContainingType() == null) - continue; - String containingClassName = at.getContainingType() - .getDeclaration().getQualifiedName(); - if (containingClassName.equals(AnnotationMemberTypes.class - .getName())) - { - String memberTypeName = at.getDeclaration().getSimpleName(); - Class clazz = Class.forName(containingClassName + "$" - + memberTypeName); - Annotation a = decl.getAnnotation(clazz); - if (null != a) - { - annotations.add(a); - } - } - } - catch (ClassNotFoundException e) - { - } - } - return annotations; - } -} diff --git a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/generator/apt/CheckerAnnotationProcessorEnvironmentImpl.java b/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/generator/apt/CheckerAnnotationProcessorEnvironmentImpl.java deleted file mode 100644 index e993fce..0000000 --- a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/generator/apt/CheckerAnnotationProcessorEnvironmentImpl.java +++ /dev/null @@ -1,116 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.runtime.generator.apt; - -import com.sun.mirror.apt.AnnotationProcessorEnvironment; -import com.sun.mirror.apt.AnnotationProcessorListener; -import com.sun.mirror.apt.Filer; -import com.sun.mirror.apt.Messager; -import com.sun.mirror.declaration.AnnotationTypeDeclaration; -import com.sun.mirror.declaration.Declaration; -import com.sun.mirror.declaration.PackageDeclaration; -import com.sun.mirror.declaration.TypeDeclaration; -import com.sun.mirror.util.Declarations; -import com.sun.mirror.util.Types; - -import java.util.Collection; -import java.util.Map; - -/** - * Wrapper for an AnnotationProcessorEnvironment instance. - * Keeps track of errors / warnings logged. - */ -public final class CheckerAnnotationProcessorEnvironmentImpl implements AnnotationProcessorEnvironment { - private final AnnotationProcessorEnvironment _aptEnv; - private final CheckerMessagerImpl _messager; - - /** - * @param aptDiagnostics - */ - public CheckerAnnotationProcessorEnvironmentImpl(Diagnostics aptDiagnostics) { - _aptEnv = aptDiagnostics.getAnnotationProcessorEnvironment(); - _messager = new CheckerMessagerImpl(_aptEnv.getMessager(), aptDiagnostics); - } - - /** - * Get the number of errors sent to the messager. - * - * @return Number of errors. - */ - public int getErrorCount() { - return _messager.getErrorCount(); - } - - /** - * Get the number of warnings sent to the messager. - * - * @return Number of warnings. - */ - public int getWarningCount() { - return _messager.getWarningCount(); - } - - public Messager getMessager() { - return _messager; - } - - public Filer getFiler() { - return _aptEnv.getFiler(); - } - - public Map getOptions() { - return _aptEnv.getOptions(); - } - - public Collection getSpecifiedTypeDeclarations() { - return _aptEnv.getSpecifiedTypeDeclarations(); - } - - public PackageDeclaration getPackage(String string) { - return _aptEnv.getPackage(string); - } - - public TypeDeclaration getTypeDeclaration(String string) { - return _aptEnv.getTypeDeclaration(string); - } - - public Collection getTypeDeclarations() { - return _aptEnv.getTypeDeclarations(); - } - - public Declarations getDeclarationUtils() { - return _aptEnv.getDeclarationUtils(); - } - - public Types getTypeUtils() { - return _aptEnv.getTypeUtils(); - } - - public void addListener(AnnotationProcessorListener listener) { - _aptEnv.addListener(listener); - } - - public void removeListener(AnnotationProcessorListener listener) { - _aptEnv.removeListener(listener); - } - - public Collection getDeclarationsAnnotatedWith(AnnotationTypeDeclaration typeDeclaration) { - return _aptEnv.getDeclarationsAnnotatedWith(typeDeclaration); - } -} diff --git a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/generator/apt/CheckerMessagerImpl.java b/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/generator/apt/CheckerMessagerImpl.java deleted file mode 100644 index daacdba..0000000 --- a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/generator/apt/CheckerMessagerImpl.java +++ /dev/null @@ -1,92 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.runtime.generator.apt; - -import com.sun.mirror.apt.Messager; -import com.sun.mirror.util.SourcePosition; - -/** - * Wrap a com.sun.mirror.apt.Messager instance to track errors and warnings. - */ -public final class CheckerMessagerImpl implements Messager { - private final Messager _messager; - private final Diagnostics _aptDiagnostics; - private int _errorCount; - private int _warningCount; - - - /** - * Constructor. - * - * @param messager Messager to wrap. - */ - CheckerMessagerImpl(Messager messager, Diagnostics aptDiagnostics) { - _messager = messager; - _aptDiagnostics = aptDiagnostics; - _errorCount = _warningCount = 0; - } - - /** - * Get the number of errors sent to this messager. - * - * @return Number of errors. - */ - int getErrorCount() { - return _errorCount; - } - - /** - * Get the number of warnings sent to this messager. - * - * @return Number of warnings. - */ - int getWarningCount() { - return _warningCount; - } - - public void printError(String string) { - _errorCount++; - _aptDiagnostics.setHasErrors(true); - _messager.printError(string); - } - - public void printError(SourcePosition sourcePosition, String string) { - _errorCount++; - _aptDiagnostics.setHasErrors(true); - _messager.printError(sourcePosition, string); - } - - public void printWarning(String string) { - _warningCount++; - _messager.printWarning(string); - } - - public void printWarning(SourcePosition sourcePosition, String string) { - _warningCount++; - _messager.printWarning(sourcePosition, string); - } - - public void printNotice(String string) { - _messager.printNotice(string); - } - - public void printNotice(SourcePosition sourcePosition, String string) { - _messager.printNotice(sourcePosition, string); - } -} diff --git a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/generator/apt/ControlAnnotationProcessor.java b/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/generator/apt/ControlAnnotationProcessor.java deleted file mode 100644 index aee20ff..0000000 --- a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/generator/apt/ControlAnnotationProcessor.java +++ /dev/null @@ -1,166 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.runtime.generator.apt; - -import java.io.IOException; -import java.util.HashMap; -import java.util.List; -import java.util.Set; - -import com.sun.mirror.apt.AnnotationProcessorEnvironment; -import com.sun.mirror.declaration.AnnotationTypeDeclaration; -import com.sun.mirror.declaration.Declaration; - -import org.apache.beehive.controls.api.bean.ControlExtension; -import org.apache.beehive.controls.api.bean.ControlImplementation; -import org.apache.beehive.controls.api.bean.ControlInterface; -import org.apache.beehive.controls.api.properties.PropertySet; - -import org.apache.beehive.controls.runtime.generator.*; - -public class ControlAnnotationProcessor extends TwoPhaseAnnotationProcessor -{ - public ControlAnnotationProcessor(Set atds, - AnnotationProcessorEnvironment env) - { - super(atds, env); - } - - @Override - public void check(Declaration decl) - { - AnnotationProcessorEnvironment env = getAnnotationProcessorEnvironment(); - Generator genClass = null; - if (decl.getAnnotation(ControlInterface.class) != null) - { - genClass = new AptControlInterface(decl, this); - } - else if (decl.getAnnotation(ControlExtension.class) != null) - { - genClass = new AptControlInterface(decl, this); - - // When a control extension is declared, values may be assigned to - // the properties of the parent controls. The property constraint - // validator is called here to ensure all values assigned satisfy any - // constraints declared in the properties. - try - { - AnnotationConstraintAptValidator.validate(decl); - } - catch (IllegalArgumentException iae) - { - printError(decl, "propertyset.illegal.argument.error", iae.getMessage()); - } - - } - else if (decl.getAnnotation(ControlImplementation.class) != null) - { - genClass = new AptControlImplementation(decl, this); - } - else if (decl.getAnnotation(PropertySet.class) != null) - { - new AptPropertySet(null, decl, this); - } - - if ( genClass != null && !hasErrors() ) - { - try - { - List genList = genClass.getCheckOutput(env.getFiler()); - if (genList == null || genList.size() == 0) - return; - - for (GeneratorOutput genOut : genList) - { - getGenerator().generate(genOut); - } - } - catch (IOException ioe) - { - throw new CodeGenerationException("Code generation failure: ", ioe); - } - } - } - - @Override - public void generate(Declaration decl) - { - AnnotationProcessorEnvironment env = getAnnotationProcessorEnvironment(); - Generator genClass = null; - if (decl.getAnnotation(ControlInterface.class) != null) - { - genClass = new AptControlInterface(decl, this); - } - if (decl.getAnnotation(ControlExtension.class) != null) - { - genClass = new AptControlInterface(decl, this); - } - else if (decl.getAnnotation(ControlImplementation.class) != null) - { - genClass = new AptControlImplementation(decl, this); - } - - if ( genClass != null ) - { - try - { - List genList = genClass.getGenerateOutput(env.getFiler()); - if (genList == null || genList.size() == 0) - return; - - for (GeneratorOutput genOut : genList) - { - getGenerator().generate(genOut); - } - } - catch (IOException ioe) - { - throw new CodeGenerationException("Code generation failure: ", ioe); - } - } - } - - /** - * Returns the CodeGenerator instance supporting this processor, instantiating a new - * generator instance if necessary. - */ - protected CodeGenerator getGenerator() - { - if (_generator == null) - { - // - // Locate the class that wraps the Velocity code generation process - // - AnnotationProcessorEnvironment env = getAnnotationProcessorEnvironment(); - - try - { - _generator = new VelocityGenerator(env); - } - catch (Exception e) - { - throw new CodeGenerationException("Unable to create code generator", e); - } - } - return _generator; - } - - HashMap _typeMap = new HashMap(); - CodeGenerator _generator; -} diff --git a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/generator/apt/ControlAnnotationProcessorFactory.java b/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/generator/apt/ControlAnnotationProcessorFactory.java deleted file mode 100644 index 0f047f7..0000000 --- a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/generator/apt/ControlAnnotationProcessorFactory.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.runtime.generator.apt; - -import java.util.Arrays; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.Set; - -import com.sun.mirror.apt.AnnotationProcessor; -import com.sun.mirror.apt.AnnotationProcessorFactory; -import com.sun.mirror.apt.AnnotationProcessorEnvironment; -import com.sun.mirror.declaration.AnnotationTypeDeclaration; - -public class ControlAnnotationProcessorFactory implements AnnotationProcessorFactory -{ - private static final Collection _supportedAnnotations = - Collections.unmodifiableCollection( - Arrays.asList(new String[] { - org.apache.beehive.controls.api.bean.ControlInterface.class.getName(), - org.apache.beehive.controls.api.bean.ControlExtension.class.getName(), - org.apache.beehive.controls.api.bean.ControlImplementation.class.getName(), - org.apache.beehive.controls.api.properties.PropertySet.class.getName() - })); - - private static final Collection _supportedOptions = - Collections.unmodifiableCollection( - Arrays.asList(new String[] { - "-AcontrolGenerator", // sets CodeGenerator class - })); - - public Collection supportedOptions() - { - return _supportedOptions; - } - - public Collection supportedAnnotationTypes() - { - return _supportedAnnotations; - } - - public AnnotationProcessor getProcessorFor(Set atds, - AnnotationProcessorEnvironment env) - { - return new ControlAnnotationProcessor(atds, env); - } -} diff --git a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/generator/apt/ControlClientAnnotationProcessor.java b/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/generator/apt/ControlClientAnnotationProcessor.java deleted file mode 100644 index b6837c4..0000000 --- a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/generator/apt/ControlClientAnnotationProcessor.java +++ /dev/null @@ -1,663 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.runtime.generator.apt; - -import java.util.Set; -import java.util.Map; -import java.util.HashSet; -import java.util.HashMap; -import java.util.Collection; -import java.util.List; -import java.util.LinkedList; -import java.util.Queue; -import java.io.File; -import java.io.IOException; -import com.sun.mirror.apt.AnnotationProcessorEnvironment; -import com.sun.mirror.apt.Filer; -import com.sun.mirror.declaration.AnnotationTypeDeclaration; -import com.sun.mirror.declaration.FieldDeclaration; -import com.sun.mirror.declaration.TypeDeclaration; -import com.sun.mirror.declaration.Declaration; -import com.sun.mirror.declaration.Modifier; -import com.sun.mirror.declaration.ClassDeclaration; -import com.sun.mirror.declaration.AnnotationValue; -import com.sun.mirror.declaration.AnnotationMirror; -import com.sun.mirror.declaration.InterfaceDeclaration; -import com.sun.mirror.type.TypeMirror; -import com.sun.mirror.type.ClassType; -import com.sun.mirror.type.InterfaceType; -import com.sun.mirror.type.DeclaredType; - -import org.apache.beehive.controls.runtime.bean.ControlUtils; -import org.apache.beehive.controls.runtime.generator.CodeGenerationException; -import org.apache.beehive.controls.runtime.generator.AptAnnotationHelper; -import org.apache.beehive.controls.runtime.generator.AptControlClient; -import org.apache.beehive.controls.runtime.generator.GeneratorOutput; -import org.apache.beehive.controls.runtime.generator.Generator; -import org.apache.beehive.controls.runtime.generator.VelocityGenerator; -import org.apache.beehive.controls.runtime.generator.CodeGenerator; -import org.apache.beehive.controls.api.versioning.Version; -import org.apache.beehive.controls.api.versioning.VersionRequired; -import org.apache.beehive.controls.api.bean.ControlInterface; -import org.apache.beehive.controls.api.bean.ControlExtension; - -public class ControlClientAnnotationProcessor - extends TwoPhaseAnnotationProcessor { - - public ControlClientAnnotationProcessor(Set atds, AnnotationProcessorEnvironment env ) { - super( atds,env ); - } - - @Override - public void check( Declaration d ) - { - if ( d instanceof FieldDeclaration ) - checkControlField( (FieldDeclaration)d ); - - // if @Control is used on something other than a field, the Java lang - // checker should produce an error due to the @Target violation. - - if ( d instanceof TypeDeclaration ) - checkControlClientType( (TypeDeclaration)d ); - - // When a control is instantiated declaratively, values may be assigned to - // the control's properties declaratively as well. The property constraint - // validator is called here to ensure all values assigned satisfy any - // constraints declared in the properties. - try - { - AnnotationConstraintAptValidator.validate(d); - } - catch (IllegalArgumentException iae) - { - printError(d, "propertyset.illegal.argument.error", iae.getMessage()); - } - } - - private static void addControlType(Map> clientsMap, TypeDeclaration clientType, - TypeMirror controlFieldType) - { - Set controlTypes = clientsMap.get( clientType ); - - if ( controlTypes == null ) - { - controlTypes = new HashSet(); - clientsMap.put( clientType, controlTypes ); - } - - controlTypes.add( controlFieldType ); - } - - /** - * Each control client requires a manifest that documents the controls that it references. - * - * @throws CodeGenerationException - */ - @Override - public void generate() throws CodeGenerationException - { - super.generate(); - - /* - The annotation processor may be passed multiple control client types. Build a map that - links each control client type with the set of control types that it uses. - */ - - Map> clientsMap = new HashMap>(); - - for (AnnotationTypeDeclaration atd : _atds) - { - if (atd.getSimpleName().equals("Control") ) - { - AnnotationProcessorEnvironment env = getAnnotationProcessorEnvironment(); - Collection decls = env.getDeclarationsAnnotatedWith(atd); - for (Declaration decl : decls) - { - if ( decl instanceof FieldDeclaration ) - { - FieldDeclaration fd = (FieldDeclaration)decl; - TypeDeclaration clientType = fd.getDeclaringType(); - TypeMirror controlFieldType = fd.getType(); - addControlType( clientsMap, clientType, controlFieldType ); - - /* - Add the control type to any derived class. Fields with - private and default (package) access are also included - here as the controls in superclasses may be exposed - through public or protected methods to subclasses. - */ - Collection specifiedTypeDeclartions = env.getSpecifiedTypeDeclarations(); - for (TypeDeclaration td : specifiedTypeDeclartions) - { - if (td instanceof ClassDeclaration) - { - ClassType superclass = ((ClassDeclaration) td).getSuperclass(); - while (superclass != null) - { - if (superclass.getDeclaration().equals(clientType)) - { - addControlType(clientsMap, td, controlFieldType); - break; - } - - superclass = superclass.getSuperclass(); - } - } - } - } - } - } - else if (atd.getSimpleName().equals("ControlReferences")) - { - Collection decls = getAnnotationProcessorEnvironment().getDeclarationsAnnotatedWith(atd); - for (Declaration decl : decls) - { - if ( decl instanceof TypeDeclaration ) - { - TypeDeclaration clientType = (TypeDeclaration)decl; - Set controlTypes = clientsMap.get( clientType ); - if ( controlTypes == null ) - { - controlTypes = new HashSet(); - clientsMap.put( clientType, controlTypes ); - } - - // Read ControlReferences annotation - AnnotationMirror controlMirror = null; - for (AnnotationMirror annot : clientType.getAnnotationMirrors()) - { - if (annot.getAnnotationType().getDeclaration().getQualifiedName().equals( - "org.apache.beehive.controls.api.bean.ControlReferences")) - { - controlMirror = annot; - break; - } - } - - assert( controlMirror != null ); - - // Add each control type listed in the ControlReferences annotation - AptAnnotationHelper controlAnnot = new AptAnnotationHelper(controlMirror); - Collection references = (Collection)controlAnnot.getObjectValue("value"); - if ( references != null ) - { - for ( AnnotationValue av : references ) - { - TypeMirror crType = (TypeMirror)av.getValue(); - controlTypes.add( crType ); - } - } - } - } - } - } - - // For each client type: - // 1 - emit a controls client manifest in the same dir as the client type's class. - // 2 - emit a controls client initializer class in the same pkg/dir as the client type's class - - Filer f = getAnnotationProcessorEnvironment().getFiler(); - Set clientTypes = clientsMap.keySet(); - for ( TypeDeclaration clientType : clientTypes ) - { - // Emit manifest - - String clientPkg = clientType.getPackage().getQualifiedName(); - File clientManifestName = - new File( clientType.getSimpleName() + ControlClientManifest.FILE_EXTENSION ); - - ControlClientManifest mf = new ControlClientManifest( clientType.getQualifiedName() ); - - try - { - Set controlTypes = clientsMap.get( clientType ); - for ( TypeMirror controlType : controlTypes ) - { - InterfaceDeclaration controlIntfOrExt = getControlInterfaceOrExtension(controlType); - InterfaceDeclaration controlIntf = getMostDerivedControlInterface( controlIntfOrExt ); - - assert controlIntf != null : "Can't find most derived control intf for=" + controlIntfOrExt; - - ControlInterface annot = controlIntf.getAnnotation(ControlInterface.class); - String defBinding = annot.defaultBinding(); - - defBinding = ControlUtils.resolveDefaultBinding( defBinding, controlIntf.getQualifiedName() ); - - mf.addControlType( controlIntfOrExt.getQualifiedName(), defBinding ); - } - - mf.emit( f, clientPkg, clientManifestName, null ); - } - catch ( IOException ie ) - { - printError( clientType, "controls.client.manifest.ioerror" ); - ie.printStackTrace( ); - } - - // Emit initializer - - AnnotationProcessorEnvironment env = getAnnotationProcessorEnvironment(); - Generator genClass = new AptControlClient( clientType, this ); - - if ( genClass != null ) - { - try - { - List genList = genClass.getGenerateOutput(env.getFiler()); - if (genList == null || genList.size() == 0) - return; - - for (GeneratorOutput genOut : genList) - { - getGenerator().generate(genOut); - } - } - catch (IOException ioe) - { - throw new CodeGenerationException("Code generation failure: ", ioe); - } - } - } - } - - @Override - public void generate(Declaration decl) - { - } - - private void checkControlField( FieldDeclaration f ) - { - TypeMirror fieldType = f.getType(); - - // Make sure that this field doesn't try to override another that's inherited. - String fieldName = f.getSimpleName(); - TypeDeclaration declaringType = f.getDeclaringType(); - - if ( declaringType instanceof ClassDeclaration ) - { - for ( ClassType i = ( ( ClassDeclaration ) declaringType ).getSuperclass(); i != null; i = i.getSuperclass() ) - { - ClassDeclaration decl = i.getDeclaration(); - - if ( decl != null ) - { - for ( FieldDeclaration baseClassField : decl.getFields() ) - { - if ( fieldName.equals( baseClassField.getSimpleName() ) ) - { - Collection modifiers = baseClassField.getModifiers(); - - if ( modifiers.contains( Modifier.PROTECTED ) || modifiers.contains( Modifier.PUBLIC ) ) - { - printError( f, "control.field.override", decl.getQualifiedName() ); - } - } - } - } - } - } - - // Valid control field instances can be of an interface type - // or a class type. - if ( fieldType instanceof InterfaceType ) - { - // Valid interface type decls must be annotated w/ @ControlInterface - // or @ControlExtension. - Declaration fieldTypeDecl = ((InterfaceType)fieldType).getDeclaration(); - if ( fieldTypeDecl.getAnnotation(ControlInterface.class) == null && - fieldTypeDecl.getAnnotation(ControlExtension.class) == null ) - printError( f, "control.field.bad.interfacetype" ); - } - else if ( fieldType instanceof ClassType ) - { - // Valid class type decls must implements the ControlBean API. - - // Walk the implementation inheritance hierarchy, seeing if one of the - // classes implements ControlBean. - // - // REVIEW: Does NOT check if the interfaces might implement ControlBean! - // This is unnecessary for our impl, since our generated bean class directly - // implements ControlBean, but other impls may choose to do otherwise. - boolean foundControlBean = false; - ClassType classType = (ClassType)fieldType; - - if (classType.getDeclaration() != null) - { - outer: while ( classType != null ) - { - Collection intfs = classType.getSuperinterfaces(); - for ( InterfaceType intfType : intfs ) - { - if ( intfType.getDeclaration().getQualifiedName().equals( "org.apache.beehive.controls.api.bean.ControlBean" ) ) - { - foundControlBean = true; - break outer; - } - } - classType = classType.getSuperclass(); - } - if ( !foundControlBean ) - printError( f, "control.field.bad.classtype" ); - - // Valid generated beans should only "implement" the control interface/extension, and no others - classType = (ClassType)fieldType; - Collection intfs = classType.getSuperinterfaces(); - if ( intfs.size() != 1 ) - { - printError( f, "control.field.bad.classtype.badinterface" ); - } - - for ( InterfaceType intfType : intfs ) - { - if ( intfType.getDeclaration().getAnnotation(ControlExtension.class) == null && - intfType.getDeclaration().getAnnotation(ControlInterface.class) == null) - { - printError( f, "control.field.bad.classtype.badinterface"); - } - } - } - else - { - // TODO: This could be a ControlBean type that is going to be generated by - // the current APT processing iteration. It should be possible to do more - // specific verification here using the getTypeDeclaration API on - // AnnotationProcessorEnvironment. In any event, the implementation of - // getControlInterface will properly handle this case, and if it cannot a - // malformed type error will be generated. - } - } - else - { - printError( f, "control.field.bad.type" ); - } - - // Enforce any versioning requirements this control field has. - // - // Since our generate() does some detailed grovelling of control types, make sure that - // will not result in an error by doing that grovelling now. Control types may be - // malformed if the source for those types has errors (yet the apt type may still exist!). - try - { - InterfaceDeclaration controlIntfOrExt = getControlInterfaceOrExtension(fieldType); - InterfaceDeclaration controlIntf = getMostDerivedControlInterface( controlIntfOrExt ); - - if ( controlIntf != null ) - { - enforceVersionRequired( f, controlIntf ); - } - else - { - printError( f, "control.field.type.malformed" ); - } - } - catch ( CodeGenerationException cge ) - { - printError( f, "control.field.type.malformed" ); - } - - assert declaringType != null : "Field " + f + " has no declaring type!"; - - if ( declaringType.getDeclaringType() != null ) - printError( f, "control.field.in.inner.class" ); - - Collection mods = f.getModifiers(); - - if ( mods.contains( Modifier.TRANSIENT )) - printError( f, "transient.control.field" ); - - if ( mods.contains( Modifier.STATIC )) - printError( f, "static.control.field" ); - - } - - private void checkControlClientType( TypeDeclaration t ) - { - // validate @ControlReferences - AnnotationMirror controlMirror = null; - - for (AnnotationMirror annot : t.getAnnotationMirrors()) - { - if (annot.getAnnotationType().getDeclaration().getQualifiedName().equals( - "org.apache.beehive.controls.api.bean.ControlReferences")) - { - controlMirror = annot; - break; - } - } - - // Bail out if no @ControlReferences annotation found - if ( controlMirror == null ) - return; - - AptAnnotationHelper controlAnnot = new AptAnnotationHelper(controlMirror); - - // - // Validate that the types listed in the ControlReferences annotations are actually - // control types. - // - - Collection references = (Collection)controlAnnot.getObjectValue("value"); - - if ( references != null ) - { - for ( AnnotationValue av : references ) - { - DeclaredType crType = (DeclaredType)av.getValue(); - if ( crType instanceof InterfaceType ) - { - // Valid interface type decls must be annotated w/ @ControlInterface - // or @ControlExtension. - Declaration typeDecl = crType.getDeclaration(); - if ( typeDecl.getAnnotation(ControlInterface.class) == null && - typeDecl.getAnnotation(ControlExtension.class) == null ) - printError( t, "control.reference.bad.interfacetype" ); - } - else { - printError( t, "control.reference.bad.interfacetype" ); - } - } - } - } - - /** - * Given a InterfaceType or ClassType, returns the InterfaceType for the control type's - * public interface/extension. - * @param intfOrBeanClass - * @return The InterfaceType for the control type's public interface/extension. - */ - private InterfaceDeclaration getControlInterfaceOrExtension( TypeMirror intfOrBeanClass ) - { - if (intfOrBeanClass instanceof InterfaceType) - { - return ((InterfaceType)intfOrBeanClass).getDeclaration(); - } - else if (intfOrBeanClass instanceof ClassType) - { - ClassType classType = (ClassType)intfOrBeanClass; - - // If the bean type declaration cannot be found, then the only (valid) possibility - // is that it is a generated type from the current processor pass. See if a base - // interface type can be determined from the current processor input list. - if (classType.getDeclaration() == null) - { - // - // Compute the bean type name, and the associated interface name by stripping - // the "Bean" suffix - // - String className = classType.toString(); - AnnotationProcessorEnvironment ape = getAnnotationProcessorEnvironment(); - InterfaceDeclaration id = null; - String intfName = null; - if (className.length() > 4) { - intfName = className.substring(0, className.length() - 4); - id = (InterfaceDeclaration)ape.getTypeDeclaration(intfName); - } - - if (id == null && intfName != null) - { - // The specified class name may not be fully qualified. In this case, the - // best we can do is look for a best fit match against the input types - for (TypeDeclaration td :ape.getSpecifiedTypeDeclarations()) - { - if (td instanceof InterfaceDeclaration && - td.getSimpleName().equals(intfName)) - { - return (InterfaceDeclaration)td; - } - } - } - return id; - } - else - { - // direct supers only - Collection intfs = classType.getSuperinterfaces(); - - // per the code in checkControlField, this set must be of size 1 - // and the 1 super interface must be a control interface/extension - // a value of zero may be valid if the control field is not referencing - // a control -- for this case fall through and return null. - assert ( intfs.size() <= 1 ); - for ( InterfaceType intfType : intfs ) - return intfType.getDeclaration(); - } - } - else - { - throw new CodeGenerationException( "Param not a interface or class type"); - } - - return null; - } - - /** - * Given a control interface or extension, do a BFS of its inheritance heirarchy for - * the first one marked with @ControlInterface. This represents the point in the - * heirarchy where use of @ControlExtension changes to use of @ControlInterface. - * - * @param controlIntfOrExt an interface annotated with @ControlInterface or @ControlExtension. - * @return most derived interface in the heirarchy annotated with @ControlInterface, null - * if no such interface found. - */ - private InterfaceDeclaration getMostDerivedControlInterface( InterfaceDeclaration controlIntfOrExt ) - { - Queue q = new LinkedList(); - - InterfaceDeclaration id = controlIntfOrExt; - while ( id != null ) - { - if ( id.getAnnotation(ControlInterface.class) != null ) - break; - - Collection supers = id.getSuperinterfaces(); - for ( InterfaceType s : supers ) - q.offer( s.getDeclaration() ); - - id = q.poll(); - } - - return id; - } - - /** - * Enforces the VersionRequired annotation for control fields. - */ - private void enforceVersionRequired( FieldDeclaration f, InterfaceDeclaration controlIntf ) - { - VersionRequired versionRequired = f.getAnnotation(VersionRequired.class); - Version versionPresent = controlIntf.getAnnotation(Version.class); - - if (versionRequired != null) { - int majorRequired = -1; - try { - majorRequired = versionRequired.major(); - } - catch(NullPointerException ignore) { - /* - the major version annotation is required and if unspecified, will - throw an NPE when it is quereid but not provided. this error will - be caught during syntactic validation perfoemed by javac, so ignore - it if an NPE is caught here - */ - return; - } - - int minorRequired = versionRequired.minor(); - - /* no version requirement, so return */ - if(majorRequired < 0) - return; - - int majorPresent = -1; - int minorPresent = -1; - if ( versionPresent != null ) - { - try { - majorPresent = versionPresent.major(); - } - catch(NullPointerException ignore) { - /* - the major version annotation is required and if unspecified, will - throw an NPE when it is quereid but not provided. this error will - be caught during syntactic validation perfoemed by javac, so ignore - it if an NPE is caught here - */ - } - - minorPresent = versionPresent.minor(); - - if ( majorRequired <= majorPresent && - (minorRequired < 0 || minorRequired <= minorPresent) ) - { - // Version requirement is satisfied - return; - } - } - - // - // Version requirement failed - // - printError( f, "control.field.bad.version", f.getSimpleName(), majorRequired, minorRequired, - majorPresent, minorPresent ); - } - } - - /** - * Returns the CodeGenerator instance supporting this processor, instantiating a new - * generator instance if necessary. - */ - protected CodeGenerator getGenerator() { - - if (_generator == null) { - /* Locate the class that wraps the Velocity code generation process */ - AnnotationProcessorEnvironment env = getAnnotationProcessorEnvironment(); - - try { - _generator = new VelocityGenerator(env); - } - catch (Exception e) { - throw new CodeGenerationException("Unable to create code generator", e); - } - } - - return _generator; - } - - CodeGenerator _generator; -} diff --git a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/generator/apt/ControlClientAnnotationProcessorFactory.java b/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/generator/apt/ControlClientAnnotationProcessorFactory.java deleted file mode 100644 index 4e6540f..0000000 --- a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/generator/apt/ControlClientAnnotationProcessorFactory.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.runtime.generator.apt; - -import java.util.Arrays; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.Set; - -import com.sun.mirror.apt.AnnotationProcessor; -import com.sun.mirror.apt.AnnotationProcessorFactory; -import com.sun.mirror.apt.AnnotationProcessorEnvironment; -import com.sun.mirror.declaration.AnnotationTypeDeclaration; - -public class ControlClientAnnotationProcessorFactory implements AnnotationProcessorFactory -{ - private static final Collection _supportedAnnotations = - Collections.unmodifiableCollection( - Arrays.asList(new String[] { - org.apache.beehive.controls.api.bean.Control.class.getName(), - org.apache.beehive.controls.api.bean.ControlReferences.class.getName() - })); - - private static final Collection _supportedOptions = - Collections.unmodifiableCollection( Arrays.asList( new String[0] ) ); - - public Collection supportedOptions() - { - return _supportedOptions; - } - - public Collection supportedAnnotationTypes() - { - return _supportedAnnotations; - } - - public AnnotationProcessor getProcessorFor(Set atds, - AnnotationProcessorEnvironment env) - { - return new ControlClientAnnotationProcessor(atds, env); - } -} diff --git a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/generator/apt/ControlClientManifest.java b/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/generator/apt/ControlClientManifest.java deleted file mode 100644 index d9db1e5..0000000 --- a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/generator/apt/ControlClientManifest.java +++ /dev/null @@ -1,253 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.runtime.generator.apt; - -import com.sun.mirror.apt.Filer; - -import java.io.*; -import java.util.*; - -/** - * The controls client manifest (aka "client manifest") surfaces the set of - * control types used by a client, and make the assembly process more - * efficient. The control client annotation processor generates a client - * manifest documenting the set of used control types. This manifest is a - * java.util.Properties file that specifies: - * - * - classname of the control client - * - classnames of each control type used by that control client (the set - * identified by @Control and @ControlReference usages) and the - * corresponding default implementation binding - * - * Example client manifest: - * - * FooImpl.controls.properties - * --------------------------- - * .client.name=org.acme.controls.FooImpl - * org.acme.controls.CustomerDbBean=org.apache.beehive.controls.scl.DatabaseControlImpl - * org.acme.controls.DailyTimerBean=org.apache.beehive.controls.scl.TimerControlImpl - * - * The manifest is a generated artifact and is not user-editable. Ideally, the apt - * environment optimizes the writing of the manifest such that it's only written - * to disk when changes occur (allowing external build tools to use the timestamp of - * the manifest to determine whether assembly on a client needs to occur). - */ -public class ControlClientManifest -{ - public final static String CLIENT_NAME_PROP = ".client.name"; - public final static String BEEHIVE_VERSION_PROP = ".beehive.version"; - public final static String FILE_EXTENSION = ".controls.properties"; - - /** - * Loads a ControlClientManifest from an existing manifest file. - * @param f the manifest file - * @throws FileNotFoundException - * @throws IOException - */ - public ControlClientManifest( File f ) throws FileNotFoundException, IOException - { - if ( !f.exists() ) - throw new FileNotFoundException( "Control manifest file=" + f + " not found"); - - FileInputStream fis = new FileInputStream( f ); - _properties.load( fis ); - - String client = _properties.getProperty( CLIENT_NAME_PROP ); - if ( client == null || client.equals("") ) - throw new IOException( "Control client manifest missing client name" ); - } - - /** - * Creates a new ControlClientManifest - * @param client the fully qualified classname of the control client - */ - public ControlClientManifest( String client ) - { - if ( client == null || client.equals("") ) - throw new RuntimeException( "Missing or empty client name" ); - - _properties.setProperty( CLIENT_NAME_PROP, client ); - } - - /** - * @return the name of the control client in this manifest - */ - public String getControlClient() - { - return _properties.getProperty( CLIENT_NAME_PROP ); - } - - /** - * Adds a new control type to the manifest - * @param intf fully qualified name of the control type - * @param impl fully qualified name of the default implementation for the control type - */ - public void addControlType( String intf, String impl ) - { - _properties.setProperty( intf, impl ); - } - - /** - * @return a list of all control types listed in the manifest - */ - public List getControlTypes() - { - ArrayList l = new ArrayList(); - - Set keys = _properties.keySet(); - for ( Object k : keys ) - { - String propname = (String)k; - if ( propname.equals( CLIENT_NAME_PROP ) ) - continue; - - l.add( propname ); - } - - return l; - } - - /** - * @param controlType - * @return the default implementation for the control type listed in the manifest - */ - public String getDefaultImpl( String controlType ) - { - return (String)_properties.get( controlType ); - } - - /** - * Emits the manifest via an apt Filer implementation - * @param f an apt Filer - * @param pkg the package structure to place the manifest in - * @param mf the name of the manifest - * @throws IOException - */ - public void emit( Filer f, String pkg, File mf, String csn ) throws IOException - { - PrintWriter pw = f.createTextFile( Filer.Location.CLASS_TREE, pkg, mf, csn ); - - pw.println( "# Apache Beehive Controls client manifest (auto-generated, do not edit!)"); - Set props = _properties.keySet(); - for ( Object p : props ) - { - String name = (String)p; - String value = _properties.getProperty(name); - - /* convert the name and value to a format excpected by the Properties.load() method */ - name = escapeJava(name); - if (value != null) - value = escapeJava(value); - - pw.println( name + "=" + value ); - } - - pw.flush(); - pw.close(); - } - - private static String escapeJava(String str) { - if (str == null) - return null; - - try { - StringWriter writer = new StringWriter(str.length() * 2); - escapeJavaStyleString(writer, str); - return writer.toString(); - } catch (IOException ioe) { - /* this should never ever happen while writing to a StringWriter */ - ioe.printStackTrace(); - return null; - } - } - - private static void escapeJavaStyleString(Writer out, String str) - throws IOException { - - assert str != null : "Received a null string"; - assert out != null : "The writer must not be null"; - - int sz = str.length(); - for (int i = 0; i < sz; i++) { - char ch = str.charAt(i); - - /* convert to unicode */ - if (ch > 0xfff) - out.write("\\u" + hex(ch)); - else if (ch > 0xff) - out.write("\\u0" + hex(ch)); - else if (ch > 0x7f) - out.write("\\u00" + hex(ch)); - else if (ch < 32) { - switch (ch) { - case '\b': - out.write('\\'); - out.write('b'); - break; - case '\n': - out.write('\\'); - out.write('n'); - break; - case '\t': - out.write('\\'); - out.write('t'); - break; - case '\f': - out.write('\\'); - out.write('f'); - break; - case '\r': - out.write('\\'); - out.write('r'); - break; - default : - if (ch > 0xf) - out.write("\\u00" + hex(ch)); - else out.write("\\u000" + hex(ch)); - break; - } - } - else { - switch (ch) { - case '\'': - out.write('\''); - break; - case '"': - out.write('\\'); - out.write('"'); - break; - case '\\': - out.write('\\'); - out.write('\\'); - break; - default : - out.write(ch); - break; - } - } - } - } - - private static String hex(char ch) { - return Integer.toHexString(ch).toUpperCase(); - } - - private Properties _properties = new Properties(); -} - diff --git a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/generator/apt/ControlMemberTypeAnnotationProcessor.java b/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/generator/apt/ControlMemberTypeAnnotationProcessor.java deleted file mode 100644 index f50eb99..0000000 --- a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/generator/apt/ControlMemberTypeAnnotationProcessor.java +++ /dev/null @@ -1,96 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.runtime.generator.apt; - -import java.lang.annotation.Annotation; -import java.util.Set; -import java.text.ParseException; -import java.text.SimpleDateFormat; - -import org.apache.beehive.controls.api.bean.AnnotationMemberTypes; -import org.apache.beehive.controls.runtime.generator.AptControlInterface; -import org.apache.beehive.controls.runtime.generator.apt.TwoPhaseAnnotationProcessor; -import org.apache.beehive.controls.runtime.bean.AnnotationConstraintValidator; - -import com.sun.mirror.apt.AnnotationProcessorEnvironment; -import com.sun.mirror.declaration.AnnotationTypeDeclaration; -import com.sun.mirror.declaration.Declaration; -import com.sun.mirror.declaration.MethodDeclaration; -import com.sun.mirror.type.VoidType; - -public class ControlMemberTypeAnnotationProcessor extends TwoPhaseAnnotationProcessor -{ - /** - * @param atds - * @param env - */ - public ControlMemberTypeAnnotationProcessor( - Set atds, - AnnotationProcessorEnvironment env) - { - super(atds, env); - } - - public void check() - { - super.check(); - - } - public void check(Declaration decl) - { - if (decl.getAnnotation(AnnotationMemberTypes.Date.class) != null) - { - checkDate(decl); - } - } - - public void generate(Declaration decl) - { - } - - public void checkDate(Declaration decl) - { - AnnotationMemberTypes.Date date = decl.getAnnotation(AnnotationMemberTypes.Date.class); - - try - { - String dateValue = date.minValue(); - String format = date.format(); - - //Validate the date format specified - SimpleDateFormat sdFormat = new SimpleDateFormat(date.format()); - - //Validate that the date specified is in the specified format. - if (dateValue != null && dateValue.length() > 0) - AnnotationConstraintValidator.parseDate(format, dateValue); - dateValue = date.maxValue(); - if (dateValue != null && dateValue.length() > 0) - AnnotationConstraintValidator.parseDate(format, dateValue); - } - catch (ParseException pe) - { - printError( decl, "control.member.type.invalid.date.value.error"); - } - catch (Exception e) - { - printError( decl, "control.member.type.invalid.date.format.error"); - } - - } -} diff --git a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/generator/apt/ControlMemberTypeAnnotationProcessorFactory.java b/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/generator/apt/ControlMemberTypeAnnotationProcessorFactory.java deleted file mode 100644 index b77fcbe..0000000 --- a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/generator/apt/ControlMemberTypeAnnotationProcessorFactory.java +++ /dev/null @@ -1,72 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.runtime.generator.apt; - -import java.util.Arrays; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.Set; - -import org.apache.beehive.controls.api.bean.AnnotationMemberTypes.Date; - -import com.sun.mirror.apt.AnnotationProcessor; -import com.sun.mirror.apt.AnnotationProcessorFactory; -import com.sun.mirror.apt.AnnotationProcessorEnvironment; -import com.sun.mirror.declaration.AnnotationTypeDeclaration; - -public class ControlMemberTypeAnnotationProcessorFactory implements AnnotationProcessorFactory -{ - private static final Collection _supportedAnnotations = - Collections.unmodifiableCollection( - Arrays.asList(new String[] { - org.apache.beehive.controls.api.bean.AnnotationMemberTypes.Date.class.getName(), - org.apache.beehive.controls.api.bean.AnnotationMemberTypes.Decimal.class.getName(), - org.apache.beehive.controls.api.bean.AnnotationMemberTypes.FilePath.class.getName(), - org.apache.beehive.controls.api.bean.AnnotationMemberTypes.Int.class.getName(), - org.apache.beehive.controls.api.bean.AnnotationMemberTypes.JndiName.class.getName(), - org.apache.beehive.controls.api.bean.AnnotationMemberTypes.Optional.class.getName(), - org.apache.beehive.controls.api.bean.AnnotationMemberTypes.QName.class.getName(), - org.apache.beehive.controls.api.bean.AnnotationMemberTypes.Text.class.getName(), - org.apache.beehive.controls.api.bean.AnnotationMemberTypes.URI.class.getName(), - org.apache.beehive.controls.api.bean.AnnotationMemberTypes.URL.class.getName(), - org.apache.beehive.controls.api.bean.AnnotationMemberTypes.URN.class.getName(), - org.apache.beehive.controls.api.bean.AnnotationMemberTypes.XML.class.getName() - })); - - private static final Collection _supportedOptions = - Collections.unmodifiableCollection( - Arrays.asList( new String[0] ) ); - - public Collection supportedOptions() - { - return _supportedOptions; - } - - public Collection supportedAnnotationTypes() - { - return _supportedAnnotations; - } - - public AnnotationProcessor getProcessorFor(Set atds, - AnnotationProcessorEnvironment env) - { - return new ControlMemberTypeAnnotationProcessor(atds, env); - } -} diff --git a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/generator/apt/ControlSecondaryAnnotationProcessor.java b/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/generator/apt/ControlSecondaryAnnotationProcessor.java deleted file mode 100644 index 37a5cd6..0000000 --- a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/generator/apt/ControlSecondaryAnnotationProcessor.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.runtime.generator.apt; - -import java.io.IOException; -import java.util.Arrays; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Set; - -import com.sun.mirror.apt.AnnotationProcessor; -import com.sun.mirror.apt.AnnotationProcessorFactory; -import com.sun.mirror.apt.AnnotationProcessorEnvironment; -import com.sun.mirror.declaration.AnnotationTypeDeclaration; -import com.sun.mirror.declaration.Declaration; - -import org.apache.beehive.controls.api.bean.ControlExtension; -import org.apache.beehive.controls.api.bean.ControlImplementation; -import org.apache.beehive.controls.api.bean.ControlInterface; -import org.apache.beehive.controls.api.properties.PropertySet; - -import org.apache.beehive.controls.runtime.generator.*; - -/** - * Currently, the sole purpose of this annotation processor is to suppress warning messages from apt regarding - * "annotations without processors". - */ -public class ControlSecondaryAnnotationProcessor extends TwoPhaseAnnotationProcessor -{ - public ControlSecondaryAnnotationProcessor(Set atds, - AnnotationProcessorEnvironment env) - { - super(atds, env); - } - - @Override - public void check(Declaration decl) - { - } - - @Override - public void generate(Declaration decl) - { - } -} diff --git a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/generator/apt/ControlSecondaryAnnotationProcessorFactory.java b/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/generator/apt/ControlSecondaryAnnotationProcessorFactory.java deleted file mode 100644 index ca4b48d..0000000 --- a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/generator/apt/ControlSecondaryAnnotationProcessorFactory.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.runtime.generator.apt; - -import java.util.Arrays; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.Set; - -import com.sun.mirror.apt.AnnotationProcessor; -import com.sun.mirror.apt.AnnotationProcessorFactory; -import com.sun.mirror.apt.AnnotationProcessorEnvironment; -import com.sun.mirror.declaration.AnnotationTypeDeclaration; - -public class ControlSecondaryAnnotationProcessorFactory implements AnnotationProcessorFactory -{ - private static final Collection _supportedAnnotations = - Collections.unmodifiableCollection( - Arrays.asList(new String[] { - java.lang.annotation.Target.class.getName(), - java.lang.annotation.Retention.class.getName(), - org.apache.beehive.controls.api.bean.ExternalPropertySets.class.getName(), - org.apache.beehive.controls.api.bean.ControlReferences.class.getName(), - org.apache.beehive.controls.api.bean.Threading.class.getName(), - org.apache.beehive.controls.api.context.Context.class.getName(), - org.apache.beehive.controls.api.events.Client.class.getName(), - org.apache.beehive.controls.api.events.EventHandler.class.getName(), - org.apache.beehive.controls.api.events.EventSet.class.getName(), - org.apache.beehive.controls.api.packaging.BeanInfo.class.getName(), - org.apache.beehive.controls.api.packaging.EventSetInfo.class.getName(), - org.apache.beehive.controls.api.packaging.FeatureAttribute.class.getName(), - org.apache.beehive.controls.api.packaging.FeatureInfo.class.getName(), - org.apache.beehive.controls.api.packaging.ManifestAttribute.class.getName(), - org.apache.beehive.controls.api.packaging.ManifestAttributes.class.getName(), - org.apache.beehive.controls.api.packaging.PropertyInfo.class.getName(), - org.apache.beehive.controls.api.packaging.PropertyInfo.class.getName(), - org.apache.beehive.controls.api.packaging.PropertyInfo.class.getName(), - org.apache.beehive.controls.api.packaging.PropertyInfo.class.getName(), - org.apache.beehive.controls.api.properties.BaseProperties.class.getName(), - org.apache.beehive.controls.api.versioning.Version.class.getName(), - org.apache.beehive.controls.api.versioning.VersionRequired.class.getName(), - org.apache.beehive.controls.api.versioning.VersionSupported.class.getName() - })); - - private static final Collection _supportedOptions = - Collections.unmodifiableCollection( - Arrays.asList(new String[] { - "-AcontrolGenerator", // sets CodeGenerator class - })); - - public Collection supportedOptions() - { - return _supportedOptions; - } - - public Collection supportedAnnotationTypes() - { - return _supportedAnnotations; - } - - public AnnotationProcessor getProcessorFor(Set atds, - AnnotationProcessorEnvironment env) - { - return new ControlSecondaryAnnotationProcessor(atds, env); - } -} diff --git a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/generator/apt/Diagnostics.java b/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/generator/apt/Diagnostics.java deleted file mode 100644 index 5ad109e..0000000 --- a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/generator/apt/Diagnostics.java +++ /dev/null @@ -1,96 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.runtime.generator.apt; - -import com.sun.mirror.apt.AnnotationProcessorEnvironment; -import com.sun.mirror.declaration.Declaration; -import com.sun.mirror.declaration.AnnotationValue; -import com.sun.mirror.declaration.AnnotationMirror; - -/** - * Wrapper class that allows the Control annotation processors to report diagnostics - * without calling directly against the {@link AnnotationProcessorEnvironment}. This - * class keeps track of whether errors have been reported during annotation processing. - */ -public abstract class Diagnostics -{ - private AnnotationProcessorEnvironment _env; - private boolean _hasErrors = false; - - protected Diagnostics( AnnotationProcessorEnvironment env ) - { - _env = env; - } - - public void addError( Declaration decl, String messageKey, Object ... args ) - { - _env.getMessager().printError( decl.getPosition(), getResourceString( messageKey, args ) ); - _hasErrors = true; - } - - public void addError( AnnotationMirror ann, String messageKey, Object ... args ) - { - _env.getMessager().printError( ann.getPosition(), getResourceString( messageKey, args ) ); - _hasErrors = true; - } - - public void addErrorArrayArgs( AnnotationMirror ann, String messageKey, Object[] args ) - { - _env.getMessager().printError( ann.getPosition(), getResourceString( messageKey, args ) ); - _hasErrors = true; - } - - public void addError( AnnotationValue annVal, String messageKey, Object ... args ) - { - _env.getMessager().printError( annVal.getPosition(), getResourceString( messageKey, args ) ); - _hasErrors = true; - } - - public void addWarning( Declaration decl, String messageKey, Object ... args ) - { - _env.getMessager().printWarning( decl.getPosition(), getResourceString( messageKey, args ) ); - } - - public void addWarning( AnnotationMirror ann, String messageKey, Object ... args ) - { - _env.getMessager().printWarning( ann.getPosition(), getResourceString( messageKey, args ) ); - } - - public void addWarning( AnnotationValue annVal, String messageKey, Object ... args ) - { - _env.getMessager().printWarning( annVal.getPosition(), getResourceString( messageKey, args ) ); - } - - public AnnotationProcessorEnvironment getAnnotationProcessorEnvironment() - { - return _env; - } - - protected abstract String getResourceString( String key, Object ... args ); - - public boolean hasErrors() - { - return _hasErrors; - } - - protected void setHasErrors( boolean hadErrors ) - { - _hasErrors = hadErrors; - } -} diff --git a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/generator/apt/TwoPhaseAnnotationProcessor.java b/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/generator/apt/TwoPhaseAnnotationProcessor.java deleted file mode 100644 index 2f0ab4b..0000000 --- a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/generator/apt/TwoPhaseAnnotationProcessor.java +++ /dev/null @@ -1,181 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.runtime.generator.apt; - -import java.util.*; -import java.text.MessageFormat; - -import com.sun.mirror.apt.AnnotationProcessor; -import com.sun.mirror.apt.AnnotationProcessorEnvironment; -import com.sun.mirror.declaration.AnnotationTypeDeclaration; -import com.sun.mirror.declaration.Declaration; - -import org.apache.beehive.controls.runtime.generator.CodeGenerationException; - -/** - * The TwoPhaseAnnotationProcessor class is an abstract class that implements the APT - * AnnotationProcessor interface. It breaks the work of the process() method of the - * AnnotationProcessor down into two distinct phases, represented as abstract method - * of TwoPhaseAnnotationProcessor that are to be implemented by concrete subclasses. - *

    - * The two phases of processing are: - *

      - *
    • The check phase is used to validate input Declarations that have been - * annotated with annotations claimed by the processor to ensure that it - * is semantically valid. If the presence of the input Declaration implies the need - * to add new files, and those files need to be visible during the check phase for - * other Declarations, then the AnnotationProcessorEnvironment's Filer API should be - * used to add those files in this phase. The adding of such files at this point - * should typically not result in their emission to persistent storage (i.e. disk), - * but rather be kept in memory to be referenced by the check phase of other - * Declarations. - *
    • The generate phase will actually emit any source, binary, or class files - * that are derived from the input Declaration, including files added via the Filer - * API during the check phase. The Filer API may also be used in this phase to add - * new files, however, such additions will not be visible during the check phase of - * any Declarations. - *
    - *

    - * The benefits of breaking process() down into check() and generate() phases are: - *

      - *
    1. Makes it possible to perform the semantic validation of Declarations without - * necessarily resulting in code generation. - *
    2. Provides a clearer association between input Declarations and generator output. - *
    - * TwoPhaseAnnotationProcessor is intended provide a uniform mechanism for writing - * AnnotationProcessor implementations that can be used in tooling environments more - * sophisticated than command-line tools (that may not do all their work on source - * in a single pass). Such environments will typically also provide implementations - * of the AnnotationProcessorEnvironment and associated interfaces (Messager, - * Filer etc). - */ -abstract public class TwoPhaseAnnotationProcessor - extends Diagnostics - implements AnnotationProcessor -{ - public TwoPhaseAnnotationProcessor(Set atds, - AnnotationProcessorEnvironment env) - { - super( env ); - _atds = atds; - _locale = Locale.getDefault(); - } - - /** - * Implements AnnotationProcessor.process() as two phases, "check" and "generate". - * "generate" will not be called if "check" emitted any errors (via printError()). - */ - public void process() - { - check(); - - // Do not call generate if check resulted in errors. - if ( !hasErrors() ) - generate(); - } - - /** - * Performs semantic validation of input Declarations that are annotated with - * annotations claimed by this AnnotationProcessor. - */ - public void check() - { - for (AnnotationTypeDeclaration atd : _atds) - { - Collection decls = getAnnotationProcessorEnvironment().getDeclarationsAnnotatedWith(atd); - for (Declaration decl : decls) - { - check(decl); - } - } - } - - /** - * Emits additional artifacts for input Declarations that are annotated with - * annotations claimed by this AnnotationProcessor. - */ - public void generate() throws CodeGenerationException - { - for (AnnotationTypeDeclaration atd : _atds) - { - Collection decls = getAnnotationProcessorEnvironment().getDeclarationsAnnotatedWith(atd); - for (Declaration decl : decls) - { - generate(decl); - } - } - } - - /** - * The check method is responsible for all semantic validation of the input Declaration. - *

    - * All semantic errors/warnings associated with the input Declaration should - * be output during check via the {@link #printError} and - * {@link #printWarning} methods. If an implementation - * bypasses printError, it must override {@link #hasErrors()} to ensure correct behaviour. - *

    - * If the presence of the input Declaration implies the need to add new files, - * and those files need to be visible during the check phase for - * other Declarations, then the AnnotationProcessorEnvironment's Filer API should be - * used to add those files in this phase. The adding of such files at this point - * should typically not result in their emission to persistent storage (i.e. disk), - * but rather be kept in memory to be referenced by the check phase of other - * Declarations. - */ - abstract public void check(Declaration decl); - - /** - * The generate method is responsible for the generation of any additional artifacts - * (source, class, or binary) that are derived from the input Declaration. - */ - abstract public void generate(Declaration decl); - - // - // Helper functions for handling diagnostics - // - - /** - * Report an error detected during the "check" phase. The presence of errors - * will suppress execution of the "generate" phase. - */ - public void printError( Declaration d, String id, Object... args ) - { - addError( d, id, args ); - } - - /** - * Report a warning detected during the "check" phase. The presence of warnings - * will not affect execution of the "generate" phase. - */ - public void printWarning( Declaration d, String id, Object... args ) - { - addWarning( d, id, args ); - } - - protected String getResourceString( String id, Object... args ) - { - ResourceBundle rb = ResourceBundle.getBundle( - this.getClass().getPackage().getName() + ".strings", _locale ); - String pattern = rb.getString(id); - return MessageFormat.format(pattern, args); - } - - Set _atds; - Locale _locale; -} diff --git a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/packaging/ControlEventSetDescriptor.java b/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/packaging/ControlEventSetDescriptor.java deleted file mode 100644 index 8367452..0000000 --- a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/packaging/ControlEventSetDescriptor.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.runtime.packaging; - -import java.beans.EventSetDescriptor; -import java.beans.IntrospectionException; -import java.beans.MethodDescriptor; -import java.lang.ref.Reference; -import java.lang.ref.SoftReference; -import java.lang.reflect.Method; - -/** - * The ControlEventSetDescriptor is a result of an infortunate evoluntary flaw in the - * java.beans.EventSetDescriptor class. The getListeners functionality for event sets was - * added after the initial implementation, and unfortunately, there is no constructor that - * let you specify both the MethodDescriptors for events and the getListener - * method. To compensate for this, we must subclass and provide our own getGetListenerMethod - * implementation. - */ -public class ControlEventSetDescriptor extends EventSetDescriptor -{ - /** - * This constructor adds the getListenerMethod argument that is missing from the JDK! - */ - public ControlEventSetDescriptor(String eventSetName, - Class listenerType, - MethodDescriptor[] listenerMethodDescriptors, - Method addListenerMethod, - Method removeListenerMethod, - Method getListenerMethod) - throws IntrospectionException - { - super(eventSetName, listenerType, listenerMethodDescriptors, addListenerMethod, removeListenerMethod); - - // Follow the same pattern as the JDK and store the method as a soft reference, so - // the introspector (alone) won't prevent Class garbage collection. - _getMethodRef = new SoftReference(getListenerMethod); - } - - /** - * Override the default implementation of getGetListenerMethod to return the method - * provided in the constructor. - */ - public Method getGetListenerMethod() - { - if (_getMethodRef == null) - return null; - - return _getMethodRef.get(); - } - - Reference _getMethodRef; -} diff --git a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/packaging/ControlJarTask.java b/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/packaging/ControlJarTask.java deleted file mode 100644 index 4fe4345..0000000 --- a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/packaging/ControlJarTask.java +++ /dev/null @@ -1,157 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.runtime.packaging; - -import java.io.File; -import java.io.FileInputStream; -import java.io.InputStreamReader; -import java.io.IOException; -import java.util.List; -import java.util.Map; -import java.util.Vector; - -import org.apache.tools.ant.BuildException; -import org.apache.tools.ant.taskdefs.Jar; -import org.apache.tools.ant.taskdefs.Manifest; -import org.apache.tools.ant.taskdefs.ManifestException; -import org.apache.tools.ant.types.Resource; -import org.apache.tools.ant.types.FileSet; -import org.apache.tools.ant.util.FileUtils; -import org.apache.tools.zip.ZipOutputStream; - -/** - * The ControlTask class extends the standard ant Jar task to perform - * additional processing for JAR files that contain Beehive Controls. - */ -public class ControlJarTask extends Jar -{ - private static FileUtils fileUtils = FileUtils.newFileUtils(); - - /** - * Step #1: Wrap the implementation of Zip.grabResources. This method identifies the - * set of resources to be stored in the JAR file. For each added/updated resource, - * the overrided method will look for an associated .manifest file that any - * JAR manifest data to add/update in the JAR manifest. - */ - protected Resource[][] grabResources(FileSet[] filesets) - { - // - // Get the list of resources being added/updated by calling Zip.grabResources - // - Resource [][] resources = super.grabResources(filesets); - - // - // Iterate through the resources for each input FileSet, looking for an associated - // manifest file. - // - for (int i = 0; i < filesets.length; i++) - { - if (resources[i].length == 0) - continue; - - File base = filesets[i].getDir(getProject()); - Resource [] setResources = resources[i]; - - for (int j = 0; j < setResources.length; j++) - { - File manifestFile = - fileUtils.resolveFile(base, setResources[j].getName() + ".manifest"); - if (manifestFile.exists()) - manifestFiles.add(manifestFile); - } - } - - return resources; - } - - /** - * Step #2: Override Jar.initZipOutputStream to inject manifest sections. This is done - * by treating them as if they were 'inline' entries, from a task perspective. - */ - protected void initZipOutputStream(ZipOutputStream zOut) throws IOException, BuildException - { - if (manifestFiles.size() != 0) - { - // - // Create a default (empty) manifest - // - Manifest mergeManifest = Manifest.getDefaultManifest(); - - // - // Iterate through each found manifest file, merging its contents into the - // merge manifest - // - for (File manifestFile : manifestFiles) - { - FileInputStream fis = null; - try - { - fis = new FileInputStream(manifestFile); - Manifest resourceManifest = new Manifest(new InputStreamReader(fis)); - mergeManifest.merge(resourceManifest); - } - catch (IOException ioe) - { - throw new BuildException("Unable to read manifest file:" + manifestFile, ioe); - } - catch (ManifestException me) - { - throw new BuildException("Unable to process manifest file: "+ manifestFile, me); - } - finally - { - if (fis != null) fis.close(); - } - } - - // - // Set the merge manifest as the 'configured' manifest. This will treat its - // contents as if they had been included inline with the task, with - // similar precedence rules. - // - try - { - addConfiguredManifest(mergeManifest); - } - catch (ManifestException me) - { - throw new BuildException("Unable to add new manifest entries:" + me); - } - } - - super.initZipOutputStream(zOut); - } - - protected void addToManifest(Manifest jarManifest, List mergeList) - { - } - - /** - * Reset the manifest file list to be empty - */ - protected void cleanUp() - { - manifestFiles = new Vector(); - } - - /** - * Contains the set of manifest entries to merge into the JAR manifest - */ - private List manifestFiles = new Vector(); -} diff --git a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/servlet/ControlFilter.java b/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/servlet/ControlFilter.java deleted file mode 100644 index 1ce5c2f..0000000 --- a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/servlet/ControlFilter.java +++ /dev/null @@ -1,127 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.runtime.servlet; - -import javax.servlet.Filter; -import javax.servlet.FilterChain; -import javax.servlet.FilterConfig; -import javax.servlet.ServletException; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; -import javax.servlet.http.HttpServletRequest; - -/** - * The ControlFilter class provides an implementation of an HTTP servlet filter that supports - * running controls in the web tier. It works, in conjunction with the {@link ServletBeanContext} - * class to provide runtime containment for controls. It ensures that a valid BeanContext has - * been set up prior to forwarding the request to the actual target servlet, and does - * post-processing to ensure that resources have been properly released. - * - * This filter needs to be configured in web.xml for URL mappings that will be hosting servlets. - */ -public class ControlFilter implements Filter -{ - public static String BEAN_CONTEXT_ATTRIBUTE = ServletBeanContext.class.getName(); - - /** - * The contextClass init parameter is a class name that defines the BeanContext class to use - * for containing Controls in the servlet container. This class must be a subclass of - * the org.apache.beehive.runtime.servlet.ServletBeanContext class. - */ - public static String INIT_PARAM_CONTEXT_CLASS = "contextClass"; - - public void init(FilterConfig filterConfig) throws ServletException - { - _filterConfig = filterConfig; - String contextClassName = filterConfig.getInitParameter(INIT_PARAM_CONTEXT_CLASS); - if(contextClassName != null) - { - try - { - _contextClass = Class.forName(contextClassName); - } - catch(Exception e) - { - throw new ServletException("Cannot load container context class '"+contextClassName+"'"); - } - if(!ServletBeanContext.class.isAssignableFrom(_contextClass)) - { - throw new ServletException("'"+contextClassName+"' is not a ServletBeanContext sub-class"); - } - - } - } - - public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) - throws java.io.IOException, ServletException - { - if (request instanceof HttpServletRequest) - { - ServletBeanContext beanContext; - try - { - beanContext = (ServletBeanContext)_contextClass.newInstance(); - } - catch(Exception e) - { - throw new ServletException("Cannot construct BeanContext class instance: " + - _contextClass.getName()); - } - - // - // Start a new execution context - // - beanContext.beginContext(_filterConfig.getServletContext(), request, response); - try - { - // - // Pass the requst on to the next filter or target servlet - // - chain.doFilter(request, response); - } - finally - { - // - // End the execution context - // - beanContext.endContext(); - } - } - else - { - // - // If the filter is (mis)configured on something other than an http servlet, just - // pass it on - // - chain.doFilter(request, response); - } - } - - public void destroy() {} - - /** - * The FilterConfig associated with this filter instance. - */ - FilterConfig _filterConfig; - - /** - * The BeanContext class to use as the container for controls running in the ServletContainer - */ - private Class _contextClass = ServletBeanContext.class; -} diff --git a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/servlet/HttpRequestService.java b/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/servlet/HttpRequestService.java deleted file mode 100644 index 4942d82..0000000 --- a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/servlet/HttpRequestService.java +++ /dev/null @@ -1,213 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.runtime.servlet; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletRequestWrapper; -import javax.servlet.ServletRequest; - -/** - * This class is the contextual service implementation for javax.servlet.http.HttpServletRequest. - * It acts as an intermediary between the client and the HttpServletRequest instance held by the - * associated ServletBeanContext. It validates that attempt to access the HttpServletRequest - * only occur during the servlet request processing lifecycle, then delegates to the underlying - * HttpServletRequest instance for actual services. - */ -/* package */ class HttpRequestService - extends ServletRequestService - implements HttpServletRequest -{ - - // todo: how will this class version with subsequent Servlet specification versions? - - /** - * This static helper class derives from javax.servlet.HttpServletRequestWrapper and can - * be used to wrap a HttpServletRequestService instance in cases where the client expects - * to be able to use the standard wrapper interfaces to unwrap requests. - */ - private static class Wrapper extends HttpServletRequestWrapper - { - Wrapper(HttpRequestService requestService) - { - super(requestService); - _requestService = requestService; - } - - /** - * Overrides the default HttpServletRequestWrapper.getRequest implementation. Rather - * than just returning the request passed into the constructor (i.e. the request - * service), it will go unwrap step further and return the current (active) http - * request. - */ - public HttpServletRequest getRequest() - { - return _requestService.getHttpServletRequest(); - } - - HttpRequestService _requestService; - } - - /* package */ HttpRequestService(ServletBeanContext beanContext) - { - super(beanContext); - } - - final protected HttpServletRequest getHttpServletRequest() - { - ServletRequest servletRequest = getServletBeanContext().getServletRequest(); - if (! (servletRequest instanceof HttpServletRequest)) - throw new IllegalStateException("Current request is not an HttpServletRequest"); - return (HttpServletRequest)servletRequest; - } - - /** - * This method returns a HttpServletRequestWrapper instance that wraps the request service. - * This is useful in instances where there is code that uses the wrapper interfaces to - * unwrap requests to get to the 'root' request. - */ - /* package */ HttpServletRequestWrapper getHttpRequestWrapper() - { - return new Wrapper(this); - } - - public java.lang.String getAuthType() - { - return getHttpServletRequest().getAuthType(); - } - - public javax.servlet.http.Cookie[] getCookies() - { - return getHttpServletRequest().getCookies(); - } - - public long getDateHeader(java.lang.String name) - { - return getHttpServletRequest().getDateHeader(name); - } - - public java.lang.String getHeader(java.lang.String name) - { - return getHttpServletRequest().getHeader(name); - } - - public java.util.Enumeration getHeaders(java.lang.String name) - { - return getHttpServletRequest().getHeaders(name); - } - - public java.util.Enumeration getHeaderNames() - { - return getHttpServletRequest().getHeaderNames(); - } - - public int getIntHeader(java.lang.String name) - { - return getHttpServletRequest().getIntHeader(name); - } - - public java.lang.String getMethod() - { - return getHttpServletRequest().getMethod(); - } - - public java.lang.String getPathInfo() - { - return getHttpServletRequest().getPathInfo(); - } - - public java.lang.String getPathTranslated() - { - return getHttpServletRequest().getPathTranslated(); - } - - public java.lang.String getContextPath() - { - return getHttpServletRequest().getContextPath(); - } - - public java.lang.String getQueryString() - { - return getHttpServletRequest().getQueryString(); - } - - public java.lang.String getRemoteUser() - { - return getHttpServletRequest().getRemoteUser(); - } - - public boolean isUserInRole(java.lang.String role) - { - return getHttpServletRequest().isUserInRole(role); - } - - public java.security.Principal getUserPrincipal() - { - return getHttpServletRequest().getUserPrincipal(); - } - - public java.lang.String getRequestedSessionId() - { - return getHttpServletRequest().getRequestedSessionId(); - } - - public java.lang.String getRequestURI() - { - return getHttpServletRequest().getRequestURI(); - } - - public java.lang.StringBuffer getRequestURL() - { - return getHttpServletRequest().getRequestURL(); - } - - public java.lang.String getServletPath() - { - return getHttpServletRequest().getServletPath(); - } - - public javax.servlet.http.HttpSession getSession(boolean create) - { - return getHttpServletRequest().getSession(create); - } - - public javax.servlet.http.HttpSession getSession() - { - return getHttpServletRequest().getSession(); - } - - public boolean isRequestedSessionIdValid() - { - return getHttpServletRequest().isRequestedSessionIdValid(); - } - - public boolean isRequestedSessionIdFromCookie() - { - return getHttpServletRequest().isRequestedSessionIdFromCookie(); - } - - public boolean isRequestedSessionIdFromURL() - { - return getHttpServletRequest().isRequestedSessionIdFromURL(); - } - - public boolean isRequestedSessionIdFromUrl() - { - return getHttpServletRequest().isRequestedSessionIdFromUrl(); - } -} diff --git a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/servlet/HttpResponseService.java b/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/servlet/HttpResponseService.java deleted file mode 100644 index 17ff426..0000000 --- a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/servlet/HttpResponseService.java +++ /dev/null @@ -1,174 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.runtime.servlet; - -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpServletResponseWrapper; -import javax.servlet.ServletResponse; - -/** - * This class is the contextual service implementation for javax.servlet.http.HttpServletResponse. - * It acts as an intermediary between the client and the HttpServletResponse instance held by the - * associated ServletBeanContext. It validates that attempt to access the HttpServletResponse - * only occur during the servlet request processing lifecycle, then delegates to the underlying - * HttpServletResponse instance for actual services. - */ -/* package */ class HttpResponseService - extends ServletResponseService - implements HttpServletResponse -{ - - // todo: how will this class version with subsequent Servlet specification versions? - - /** - * This static helper class derives from javax.servlet.HttpServletResponseWrapper and can - * be used to wrap a HttpServletResponseService instance in cases where the client expects - * to be able to use the standard wrapper interfaces to unwrap responses. - */ - private static class Wrapper extends HttpServletResponseWrapper - { - Wrapper(HttpResponseService responseService) - { - super(responseService); - _responseService = responseService; - } - - /** - * Overrides the default HttpServletRequestWrapper.getResponse implementation. Rather - * than just returning the request passed into the constructor (i.e. the request - * service), it will go unwrap step further and return the current (active) http - * response. - */ - public HttpServletResponse getResponse() - { - return _responseService.getHttpServletResponse(); - } - - HttpResponseService _responseService; - } - - - /* package */ HttpResponseService(ServletBeanContext beanContext) - { - super(beanContext); - } - - final protected HttpServletResponse getHttpServletResponse() - { - ServletResponse servletRequest = getServletBeanContext().getServletResponse(); - if (! (servletRequest instanceof HttpServletResponse)) - throw new IllegalStateException("Current request is not an HttpServletResponse"); - return (HttpServletResponse)servletRequest; - } - - /** - * This method returns a ServletRequestWrapper instance that wraps the request service. - * This is useful in instances where there is code that uses the wrapper interfaces to - * unwrap requests to get to the 'root' request. - */ - /* package */ HttpServletResponse getHttpResponseWrapper() - { - return new Wrapper(this); - } - - public void addCookie(javax.servlet.http.Cookie cookie) - { - getHttpServletResponse().addCookie(cookie); - } - - public boolean containsHeader(java.lang.String name) - { - return getHttpServletResponse().containsHeader(name); - } - - public java.lang.String encodeURL(java.lang.String url) - { - return getHttpServletResponse().encodeURL(url); - } - - public java.lang.String encodeRedirectURL(java.lang.String url) - { - return getHttpServletResponse().encodeRedirectURL(url); - } - - public java.lang.String encodeUrl(java.lang.String url) - { - return getHttpServletResponse().encodeUrl(url); - } - - public java.lang.String encodeRedirectUrl(java.lang.String url) - { - return getHttpServletResponse().encodeRedirectUrl(url); - } - - public void sendError(int sc, java.lang.String msg) throws java.io.IOException - { - getHttpServletResponse().sendError(sc, msg); - } - - public void sendError(int sc) throws java.io.IOException - { - getHttpServletResponse().sendError(sc); - } - - public void sendRedirect(java.lang.String location) throws java.io.IOException - { - getHttpServletResponse().sendRedirect(location); - } - - public void setDateHeader(java.lang.String name, long date) - { - getHttpServletResponse().setDateHeader(name, date); - } - - public void addDateHeader(java.lang.String name, long date) - { - getHttpServletResponse().addDateHeader(name, date); - } - - public void setHeader(java.lang.String name, java.lang.String value) - { - getHttpServletResponse().setHeader(name, value); - } - - public void addHeader(java.lang.String name, java.lang.String value) - { - getHttpServletResponse().addHeader(name, value); - } - - public void setIntHeader(java.lang.String name, int value) - { - getHttpServletResponse().setIntHeader(name, value); - } - - public void addIntHeader(java.lang.String name, int value) - { - getHttpServletResponse().addIntHeader(name, value); - } - - public void setStatus(int sc) - { - getHttpServletResponse().setStatus(sc); - } - - public void setStatus(int sc, java.lang.String sm) - { - getHttpServletResponse().setStatus(sc, sm); - } -} diff --git a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/servlet/ServletBeanContext.java b/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/servlet/ServletBeanContext.java deleted file mode 100644 index 2f33c06..0000000 --- a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/servlet/ServletBeanContext.java +++ /dev/null @@ -1,271 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.runtime.servlet; - -import java.util.Stack; -import java.io.InputStream; -import java.beans.beancontext.BeanContextChild; -import java.beans.beancontext.BeanContextServiceProvider; -import java.net.URL; -import java.net.MalformedURLException; -import javax.servlet.ServletContext; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.apache.beehive.controls.runtime.bean.ControlContainerContext; -import org.apache.beehive.controls.runtime.bean.WebContextFactoryProvider; -import org.apache.beehive.controls.spi.context.ControlBeanContextFactory; - -/** - * The ServletBeanContext provides a ControlBeanContext implementation that offers services - * and a resource management context that is appropriate to web tier usage of controls. - */ -public class ServletBeanContext - extends ControlContainerContext -{ - public ServletBeanContext() { - // - // This sets the BeanContextServicesFactory instance on the ControlBeanContext and allows this - // CCC object to be created with a BeanContextServicesDelegate of the type returned by this factory - // - super(WebContextFactoryProvider.WEB_CONTEXT_BCS_FACTORY); - } - - /** - * Called by BeanContextSupport superclass during construction and deserialization to - * initialize subclass transient state - */ - public void initialize() - { - super.initialize(); - - // - // Register the ServletService classes associated with the ServletServiceProvider - // - ServletServiceProvider ssp = ServletServiceProvider.getProvider(); - addService(ServletContext.class, ssp); - addService(ServletRequest.class, ssp); - addService(ServletResponse.class, ssp); - addService(HttpServletRequest.class, ssp); - addService(HttpServletResponse.class, ssp); - - // - // Register an *internal* service that is used to create ControlBeanContext objects for - // children of this control container - // - _bcsp = WebContextFactoryProvider.getProvider(); - addService(ControlBeanContextFactory.class, _bcsp); - } - - /** - * Begins a new execution context, associated with a specific ServletRequest - */ - public void beginContext(ServletContext context, ServletRequest req, ServletResponse resp) - { - pushRequestContext(context, req, resp); - super.beginContext(); - } - - /** - * Ends the current execution context, and resetes the current active ServletRequest. - */ - public void endContext() - { - super.endContext(); - popRequestContext(); - } - - private Stack getRequestStack() - { - if (_reqStack == null) - _reqStack = new Stack(); - - return _reqStack; - } - - /** - * Pushes the current request context onto the stack - */ - private synchronized void pushRequestContext(ServletContext context, - ServletRequest req, - ServletResponse resp) - { - getRequestStack().push(new RequestContext(context, req, resp)); - } - - /** - * Pops the current request context from the stack - */ - private synchronized void popRequestContext() - { - getRequestStack().pop(); - } - - /** - * Returns the current request context, or null is none is available - */ - private synchronized RequestContext peekRequestContext() - { - Stack reqStack = getRequestStack(); - if (reqStack.empty()) - return null; - - return reqStack.peek(); - } - - /** - * Returns the ServletContext associated with this context (or null if not currently - * processing a request) - */ - public ServletContext getServletContext() - { - RequestContext reqContext = peekRequestContext(); - if (reqContext == null) - return null; - - return reqContext._context; - } - - /** - * Returns the ServletRequest associated with this context (or null if not currently - * processing a request) - */ - public ServletRequest getServletRequest() - { - RequestContext reqContext = peekRequestContext(); - if (reqContext == null) - return null; - - return reqContext._request; - } - - /** - * Returns the ServletResponse associated with this context (or null if not currently - * processing a request) - */ - public ServletResponse getServletResponse() - { - RequestContext reqContext = peekRequestContext(); - if (reqContext == null) - return null; - - return reqContext._response; - } - - /** - * Enables/disable the use of request/response wrappers for this context. By default, - * wrappers are enabled if this API is not invoked. - */ - public void setWrappers(boolean useWrappers) - { - _useWrappers = useWrappers; - } - - /** - * Override BeanContext.getResourceAsStream() so it delegates to the current ServletContext. - * - * @param name the resource name - * @param bcc the specified child - * @return an InputStream for reading the resource, or - * null if the resource could not be found. - * @throws IllegalArgumentException IllegalArgumentException if the resource is not valid - */ - public InputStream getResourceAsStream(String name, BeanContextChild bcc) - throws IllegalArgumentException - { - ServletContext sc = getServletContext(); - if ( sc != null ) - return sc.getResourceAsStream( name ); - - return null; - } - - /** - * Override BeanContext.getResource() so it delegates to the current ServletContext. - * - * @param name the resource name - * @param bcc the specified child - * @return a URL for the named - * resource for the specified child - * @throws IllegalArgumentException IllegalArgumentException if the resource is not valid - */ - public URL getResource(String name, BeanContextChild bcc) - throws IllegalArgumentException - { - ServletContext sc = getServletContext(); - if ( sc != null ) - { - try - { - return sc.getResource( name ); - } - catch ( MalformedURLException mue ) - { - throw new IllegalArgumentException( mue.getMessage() ); - } - } - - return null; - } - - /** - * Override ControlBeanContext.getService(). A control bean creates its bean context using the - * ControlBeanContextFactory service provided by this context. A control bean will attempt to create - * its context before adding its self to this context as a child. This creates a chicken/egg problem since - * only a child of a context may request a service from it. - * - * This method provides a way to crack the chicken/egg problem by first trying to get the service using the - * control bean context's getService() method, and if that call returns null and the requested service is - * the ControlBeanContextFactory then returning an instance of the service provider. - * - * @param serviceClass - * @param selector - */ - public T getService(Class serviceClass, Object selector) - { - T service = super.getService(serviceClass, selector); - if (service == null && serviceClass.equals(ControlBeanContextFactory.class)) { - return (T)_bcsp.getService(this, this, serviceClass, selector); - } - return service; - } - protected boolean useWrappers() { - return _useWrappers; - } - - private static class RequestContext - { - RequestContext(ServletContext context, ServletRequest req, ServletResponse resp) - { - _context = context; - _request = req; - _response = resp; - } - - ServletContext _context; - ServletResponse _response; - ServletRequest _request; - } - - private boolean _useWrappers = true; - private transient Stack _reqStack; - private transient BeanContextServiceProvider _bcsp; -} \ No newline at end of file diff --git a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/servlet/ServletContextService.java b/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/servlet/ServletContextService.java deleted file mode 100644 index ecc0b24..0000000 --- a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/servlet/ServletContextService.java +++ /dev/null @@ -1,189 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.runtime.servlet; - -import javax.servlet.ServletContext; - -import org.apache.beehive.controls.api.context.ControlContainerContext; -import org.apache.beehive.controls.api.context.ControlThreadContext; - -/** - * This class is the contextual service implementation for javax.servlet.ServletContext. It - * acts as an intermediary between the client and the ServletContext instance held by the - * associated ServletBeanContext. It validates that attempt to access the ServletContext - * only occur during the servlet request processing lifecycle, then delegates to the underlying - * ServletContext instance for actual services. - */ -/* package */ class ServletContextService - implements ServletContext -{ - - /* package */ ServletContextService(ServletBeanContext beanContext) - { - _beanContext = beanContext; - } - - /** - * This method retrieves the current ServletBeanContext for the service. It is capable - * of reassociating with the current active context, if the service instance has been - * serialized/deserialized. - */ - final protected ServletBeanContext getServletBeanContext() - { - if (_beanContext == null) - { - ControlContainerContext ccc = ControlThreadContext.getContext(); - if (! (ccc instanceof ServletBeanContext)) - throw new IllegalStateException("No ServletBeanContext available"); - - _beanContext = (ServletBeanContext)ccc; - } - return _beanContext; - } - - final protected ServletContext getServletContext() - { - ServletContext servletContext = getServletBeanContext().getServletContext(); - if (servletContext == null) - throw new IllegalStateException("No access to ServletContext outside request processing"); - return servletContext; - } - - public java.lang.Object getAttribute(java.lang.String name) - { - return getServletContext().getAttribute(name); - } - - public java.util.Enumeration getAttributeNames() - { - return getServletContext().getAttributeNames(); - } - - public ServletContext getContext(java.lang.String uripath) - { - return getServletContext().getContext(uripath); - } - - public java.lang.String getInitParameter(java.lang.String name) - { - return getServletContext().getInitParameter(name); - } - - public java.util.Enumeration getInitParameterNames() - { - return getServletContext().getInitParameterNames(); - } - - public int getMajorVersion() - { - return getServletContext().getMajorVersion(); - } - - public java.lang.String getMimeType(java.lang.String file) - { - return getServletContext().getMimeType(file); - } - - public int getMinorVersion() - { - return getServletContext().getMinorVersion(); - } - - public javax.servlet.RequestDispatcher getNamedDispatcher(java.lang.String name) - { - return getServletContext().getNamedDispatcher(name); - } - - public java.lang.String getRealPath(java.lang.String path) - { - return getServletContext().getRealPath(path); - } - - public javax.servlet.RequestDispatcher getRequestDispatcher(java.lang.String path) - { - return getServletContext().getRequestDispatcher(path); - } - - public java.net.URL getResource(java.lang.String path) throws java.net.MalformedURLException - { - return getServletContext().getResource(path); - } - - public java.io.InputStream getResourceAsStream(java.lang.String path) - { - return getServletContext().getResourceAsStream(path); - } - - public java.util.Set getResourcePaths(java.lang.String path) - { - return getServletContext().getResourcePaths(path); - } - - public java.lang.String getServerInfo() - { - return getServletContext().getServerInfo(); - } - - public javax.servlet.Servlet getServlet(java.lang.String name) throws javax.servlet.ServletException - { - return getServletContext().getServlet(name); - } - - public java.lang.String getServletContextName() - { - return getServletContext().getServletContextName(); - } - - public java.util.Enumeration getServletNames() - { - return getServletContext().getServletNames(); - } - - public java.util.Enumeration getServlets() - { - return getServletContext().getServlets(); - } - - public void log(java.lang.String msg) - { - getServletContext().log(msg); - } - - public void log(java.lang.Exception exception, java.lang.String msg) - { - getServletContext().log(exception, msg); - } - - public void log(java.lang.String message, java.lang.Throwable throwable) - { - getServletContext().log(message, throwable); - } - - public void removeAttribute(java.lang.String name) - { - getServletContext().removeAttribute(name); - } - - public void setAttribute(java.lang.String name, java.lang.Object object) - { - getServletContext().setAttribute(name, object); - } - - transient private ServletBeanContext _beanContext; // never access directly -} diff --git a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/servlet/ServletRequestService.java b/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/servlet/ServletRequestService.java deleted file mode 100644 index 8f21912..0000000 --- a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/servlet/ServletRequestService.java +++ /dev/null @@ -1,252 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.runtime.servlet; - -import javax.servlet.ServletRequest; -import javax.servlet.ServletRequestWrapper; - -import org.apache.beehive.controls.api.context.ControlContainerContext; -import org.apache.beehive.controls.api.context.ControlThreadContext; - -/** - * This class is the contextual service implementation for javax.servlet.ServletRequest. It - * acts as an intermediary between the client and the ServletRequest instance held by the - * associated ServletBeanContext. It validates that attempt to access the ServletRequest - * only occur during the servlet request processing lifecycle, then delegates to the underlying - * ServletRequest instance for actual services. - */ -/* package */ class ServletRequestService implements ServletRequest -{ - /** - * This static helper class derives from javax.servlet.ServletRequestWrapper and can - * be used to wrap a ServletRequestService instance in cases where the client expects - * to be able to use the standard wrapper interfaces to unwrap requests. - */ - private static class Wrapper extends ServletRequestWrapper - { - Wrapper(ServletRequestService requestService) - { - super(requestService); - _requestService = requestService; - } - - /** - * Overrides the default ServletRequestWrapper.getRequest implementation. Rather - * than just returning the request passed into the constructor (i.e. the request - * service), it will go unwrap step further and return the current (active) http - * request. - */ - public ServletRequest getRequest() - { - return _requestService.getServletRequest(); - } - - ServletRequestService _requestService; - } - - /* package */ ServletRequestService(ServletBeanContext beanContext) - { - _beanContext = beanContext; - } - - /** - * This method retrieves the current ServletBeanContext for the service. It is capable - * of reassociating with the current active context, if the service instance has been - * serialized/deserialized. - */ - final protected ServletBeanContext getServletBeanContext() - { - if (_beanContext == null) - { - ControlContainerContext ccc = ControlThreadContext.getContext(); - if (! (ccc instanceof ServletBeanContext)) - throw new IllegalStateException("No ServletBeanContext available"); - - _beanContext = (ServletBeanContext)ccc; - } - return _beanContext; - } - - /** - * This method returns a ServletRequestWrapper instance that wraps the request service. - * This is useful in instances where there is code that uses the wrapper interfaces to - * unwrap requests to get to the 'root' request. - */ - /* package */ ServletRequestWrapper getRequestWrapper() - { - return new Wrapper(this); - } - - final protected ServletRequest getServletRequest() - { - ServletRequest servletRequest = getServletBeanContext().getServletRequest(); - if (servletRequest == null) - throw new IllegalStateException("No access to ServletRequest outside request processing"); - return servletRequest; - } - - public java.lang.Object getAttribute(java.lang.String name) - { - return getServletRequest().getAttribute(name); - } - - public java.util.Enumeration getAttributeNames() - { - return getServletRequest().getAttributeNames(); - } - - public java.lang.String getCharacterEncoding() - { - return getServletRequest().getCharacterEncoding(); - } - - public void setCharacterEncoding(java.lang.String env) - throws java.io.UnsupportedEncodingException - { - getServletRequest().setCharacterEncoding(env); - } - - public int getContentLength() - { - return getServletRequest().getContentLength(); - } - - public java.lang.String getContentType() - { - return getServletRequest().getContentType(); - } - - public javax.servlet.ServletInputStream getInputStream() throws java.io.IOException - { - return getServletRequest().getInputStream(); - } - - public java.lang.String getParameter(java.lang.String name) - { - return getServletRequest().getParameter(name); - } - - public java.util.Enumeration getParameterNames() - { - return getServletRequest().getParameterNames(); - } - - public java.lang.String[] getParameterValues(java.lang.String name) - { - return getServletRequest().getParameterValues(name); - } - - public java.util.Map getParameterMap() - { - return getServletRequest().getParameterMap(); - } - - public java.lang.String getProtocol() - { - return getServletRequest().getProtocol(); - } - - public java.lang.String getScheme() - { - return getServletRequest().getScheme(); - } - - public java.lang.String getServerName() - { - return getServletRequest().getServerName(); - } - - public int getServerPort() - { - return getServletRequest().getServerPort(); - } - - public int getLocalPort() - { - return getServletRequest().getLocalPort(); - } - - public java.lang.String getLocalAddr() - { - return getServletRequest().getLocalAddr(); - } - - public java.lang.String getLocalName() - { - return getServletRequest().getLocalName(); - } - - - public java.io.BufferedReader getReader() throws java.io.IOException - { - return getServletRequest().getReader(); - } - - public java.lang.String getRemoteAddr() - { - return getServletRequest().getRemoteAddr(); - } - - public java.lang.String getRemoteHost() - { - return getServletRequest().getRemoteHost(); - } - - public int getRemotePort() - { - return getServletRequest().getRemotePort(); - } - - public void setAttribute(java.lang.String name, java.lang.Object o) - { - getServletRequest().setAttribute(name, o); - } - - public void removeAttribute(java.lang.String name) - { - getServletRequest().removeAttribute(name); - } - - public java.util.Locale getLocale() - { - return getServletRequest().getLocale(); - } - - public java.util.Enumeration getLocales() - { - return getServletRequest().getLocales(); - } - - public boolean isSecure() - { - return getServletRequest().isSecure(); - } - - public javax.servlet.RequestDispatcher getRequestDispatcher(java.lang.String path) - { - return getServletRequest().getRequestDispatcher(path); - } - - public java.lang.String getRealPath(java.lang.String path) - { - return getServletRequest().getRealPath(path); - } - - transient private ServletBeanContext _beanContext; // never access directly -} diff --git a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/servlet/ServletResponseService.java b/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/servlet/ServletResponseService.java deleted file mode 100644 index 50a9a47..0000000 --- a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/servlet/ServletResponseService.java +++ /dev/null @@ -1,180 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.runtime.servlet; - -import javax.servlet.ServletResponse; -import javax.servlet.ServletResponseWrapper; - -import org.apache.beehive.controls.api.context.ControlContainerContext; -import org.apache.beehive.controls.api.context.ControlThreadContext; - -/** - * This class is the contextual service implementation for javax.servlet.ServletResponse. It - * acts as an intermediary between the client and the ServletResponse instance held by the - * associated ServletBeanContext. It validates that attempt to access the ServletResponse - * only occur during the servlet request processing lifecycle, then delegates to the underlying - * ServletResponse instance for actual services. - */ -/* package */ class ServletResponseService implements ServletResponse -{ - /** - * This static helper class derives from javax.servlet.ServletRequestWrapper and can - * be used to wrap a ServletRequestService instance in cases where the client expects - * to be able to use the standard wrapper interfaces to unwrap requests. - */ - private static class Wrapper extends ServletResponseWrapper - { - Wrapper(ServletResponseService responseService) - { - super(responseService); - _responseService = responseService; - } - - /** - * Overrides the default ServletRequestWrapper.getRequest implementation. Rather - * than just returning the request passed into the constructor (i.e. the request - * service), it will go unwrap step further and return the current (active) http - * request. - */ - public ServletResponse getResponse() - { - return _responseService.getServletResponse(); - } - - ServletResponseService _responseService; - } - - /* package */ ServletResponseService(ServletBeanContext beanContext) - { - _beanContext = beanContext; - } - - /** - * This method retrieves the current ServletBeanContext for the service. It is capable - * of reassociating with the current active context, if the service instance has been - * serialized/deserialized. - */ - final protected ServletBeanContext getServletBeanContext() - { - if (_beanContext == null) - { - ControlContainerContext ccc = ControlThreadContext.getContext(); - if (! (ccc instanceof ServletBeanContext)) - throw new IllegalStateException("No ServletBeanContext available"); - - _beanContext = (ServletBeanContext)ccc; - } - return _beanContext; - } - - final protected ServletResponse getServletResponse() - { - ServletResponse servletResponse = getServletBeanContext().getServletResponse(); - if (servletResponse == null) - throw new IllegalStateException("No access to ServletResponse outside request processing"); - return servletResponse; - } - - /** - * This method returns a ServletResponseWrapper instance that wraps the response service. - * This is useful in instances where there is code that uses the wrapper interfaces to - * unwrap responses to get to the 'root' response. - */ - /* package */ ServletResponseWrapper getResponseWrapper() - { - return new Wrapper(this); - } - - public java.lang.String getCharacterEncoding() - { - return getServletResponse().getCharacterEncoding(); - } - - public java.lang.String getContentType() - { - return getServletResponse().getContentType(); - } - - public javax.servlet.ServletOutputStream getOutputStream() throws java.io.IOException - { - return getServletResponse().getOutputStream(); - } - - public java.io.PrintWriter getWriter() throws java.io.IOException - { - return getServletResponse().getWriter(); - } - - public void setCharacterEncoding(java.lang.String charset) - { - getServletResponse().setCharacterEncoding(charset); - } - - public void setContentLength(int len) - { - getServletResponse().setContentLength(len); - } - - public void setContentType(java.lang.String type) - { - getServletResponse().setContentType(type); - } - - public void setBufferSize(int size) - { - getServletResponse().setBufferSize(size); - } - - public int getBufferSize() - { - return getServletResponse().getBufferSize(); - } - - public void flushBuffer() throws java.io.IOException - { - getServletResponse().flushBuffer(); - } - - public void resetBuffer() - { - getServletResponse().resetBuffer(); - } - - public boolean isCommitted() - { - return getServletResponse().isCommitted(); - } - - public void reset() - { - getServletResponse().reset(); - } - - public void setLocale(java.util.Locale loc) - { - getServletResponse().setLocale(loc); - } - - public java.util.Locale getLocale() - { - return getServletResponse().getLocale(); - } - - transient private ServletBeanContext _beanContext; // never access directly -} diff --git a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/servlet/ServletServiceProvider.java b/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/servlet/ServletServiceProvider.java deleted file mode 100644 index 34e9eb4..0000000 --- a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/servlet/ServletServiceProvider.java +++ /dev/null @@ -1,102 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.runtime.servlet; - -import java.beans.beancontext.BeanContextServices; -import java.beans.beancontext.BeanContextServiceProvider; -import java.util.Iterator; - -import javax.servlet.ServletContext; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -/** - * The ServletContextProvider helper class acts at the BeanContextServiceProvider provides - * instances of web tier services associated with a ServletBeanContext - */ -class ServletServiceProvider implements BeanContextServiceProvider -{ - static final private ServletServiceProvider _provider = new ServletServiceProvider(); - - static ServletServiceProvider getProvider() { - return _provider; - } - - /* package */ ServletServiceProvider() {} - - public Object getService(BeanContextServices bcs, Object requestor, Class serviceClass, Object serviceSelector) - { - // - // These services are only available to controls running within the scope of a - // ServletBeanContext - // - if (! (bcs instanceof ServletBeanContext)) - return null; - - ServletBeanContext sbc = (ServletBeanContext)bcs; - if (serviceClass.equals(ServletContext.class)) - return new ServletContextService(sbc); - - if (serviceClass.equals(HttpServletRequest.class)) - { - HttpRequestService requestService = new HttpRequestService(sbc); - if (sbc.useWrappers()) - return requestService.getHttpRequestWrapper(); - return requestService; - } - - if (serviceClass.equals(HttpServletResponse.class)) - { - HttpResponseService responseService = new HttpResponseService(sbc); - if (sbc.useWrappers()) - return responseService.getHttpResponseWrapper(); - return responseService; - } - - if (serviceClass.equals(ServletRequest.class)) - { - ServletRequestService requestService = new ServletRequestService(sbc); - if (sbc.useWrappers()) - return requestService.getRequestWrapper(); - return requestService; - } - - if (serviceClass.equals(ServletResponse.class)) - { - ServletResponseService responseService = new ServletResponseService(sbc); - if (sbc.useWrappers()) - return responseService.getResponseWrapper(); - return responseService; - } - - return null; - } - - public void releaseService(BeanContextServices bcs, Object requestor, Object service) - { - // noop, because the provider isn't tracking service instances. - } - - public Iterator getCurrentServiceSelectors(BeanContextServices bcs, Class serviceClass) - { - return null; // no selectors - } -} diff --git a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/webcontext/ControlBeanContextChildSupport.java b/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/webcontext/ControlBeanContextChildSupport.java deleted file mode 100755 index e5b4ef2..0000000 --- a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/webcontext/ControlBeanContextChildSupport.java +++ /dev/null @@ -1,250 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ - -package org.apache.beehive.controls.runtime.webcontext; - -import java.beans.PropertyChangeListener; -import java.beans.PropertyChangeSupport; -import java.beans.PropertyVetoException; -import java.beans.VetoableChangeListener; -import java.beans.VetoableChangeSupport; -import java.beans.beancontext.BeanContext; -import java.beans.beancontext.BeanContextChild; -import java.beans.beancontext.BeanContextServiceAvailableEvent; -import java.beans.beancontext.BeanContextServiceRevokedEvent; -import java.beans.beancontext.BeanContextServiceRevokedListener; -import java.beans.beancontext.BeanContextServicesListener; -import java.io.IOException; -import java.io.ObjectOutputStream; -import java.io.Serializable; -import java.io.ObjectInputStream; -import java.util.EventListener; - -/** - * Implementation of the BeanContextChild api for Beehive controls. - */ -public class ControlBeanContextChildSupport - implements BeanContextChild, BeanContextServiceRevokedListener, - BeanContextServicesListener, Serializable, EventListener { - private static final long serialVersionUID = 1; - - private transient BeanContext _beanContext; - private transient boolean _vetodOnce; - private BeanContextChild _peer; - private PropertyChangeSupport _propertyChangeSupport; - private VetoableChangeSupport _vetoableChangeSupport; - - /** - * Constructor. - */ - public ControlBeanContextChildSupport() { - _beanContext = null; - _peer = this; - _vetodOnce = false; - _propertyChangeSupport = new PropertyChangeSupport(_peer); - _vetoableChangeSupport = new VetoableChangeSupport(_peer); - } - - /** - * Constructor -- java bean implements BeanContextChild and delegates the interface - * to this implementation. - * - * @param bcc - */ - public ControlBeanContextChildSupport(BeanContextChild bcc) { - _beanContext = null; - _vetodOnce = false; - _peer = (bcc != null) ? bcc : this; - _propertyChangeSupport = new PropertyChangeSupport(_peer); - _vetoableChangeSupport = new VetoableChangeSupport(_peer); - } - - /** - *

    - * Objects that implement this interface, - * shall fire a java.beans.PropertyChangeEvent, with parameters: - *

    - * propertyName "beanContext", oldValue (the previous nesting - * BeanContext instance, or null), - * newValue (the current nesting - * BeanContext instance, or null). - *

    - * A change in the value of the nesting BeanContext property of this - * BeanContextChild may be vetoed by throwing the appropriate exception. - *

    - * - * @param bc The BeanContext with which - * to associate this BeanContextChild. - */ - public synchronized void setBeanContext(BeanContext bc) throws PropertyVetoException { - - if (bc == _beanContext) return; - - // track if veto'd the first time, then then second time remove anyway (dont except); - if (!_vetodOnce) { - try { - _vetoableChangeSupport.fireVetoableChange("beanContext", _beanContext, bc); - } - catch (PropertyVetoException pve) { - _vetodOnce = true; - throw pve; - } - } - - releaseBeanContextResources(); - BeanContext oldValue = _beanContext; - _beanContext = bc; - _vetodOnce = false; - firePropertyChange("beanContext", oldValue, _beanContext); - } - - /** - * Gets the BeanContext associated - * with this BeanContextChild. - * - * @return the BeanContext associated - * with this BeanContextChild. - */ - public synchronized BeanContext getBeanContext() { - return _beanContext; - } - - /** - * Adds a PropertyChangeListener - * to this BeanContextChild - * in order to receive a PropertyChangeEvent - * whenever the specified property has changed. - * - * @param name the name of the property to listen on - * @param pcl the PropertyChangeListener to add - */ - public void addPropertyChangeListener(String name, PropertyChangeListener pcl) { - _propertyChangeSupport.addPropertyChangeListener(name, pcl); - } - - /** - * Removes a PropertyChangeListener from this - * BeanContextChild so that it no longer - * receives PropertyChangeEvents when the - * specified property is changed. - * - * @param name the name of the property that was listened on - * @param pcl the PropertyChangeListener to remove - */ - public void removePropertyChangeListener(String name, PropertyChangeListener pcl) { - _propertyChangeSupport.removePropertyChangeListener(name, pcl); - } - - /** - * Adds a VetoableChangeListener to - * this BeanContextChild - * to receive events whenever the specified property changes. - * - * @param name the name of the property to listen on - * @param vcl the VetoableChangeListener to add - */ - public void addVetoableChangeListener(String name, VetoableChangeListener vcl) { - _vetoableChangeSupport.addVetoableChangeListener(name, vcl); - } - - /** - * Removes a VetoableChangeListener from this - * BeanContextChild so that it no longer receives - * events when the specified property changes. - * - * @param name the name of the property that was listened on. - * @param vcl the VetoableChangeListener to remove. - */ - public void removeVetoableChangeListener(String name, VetoableChangeListener vcl) { - _vetoableChangeSupport.addVetoableChangeListener(name, vcl); - } - - /** - * The service named has been registered. getService requests for - * this service may now be made. - * - * @param bcsae the BeanContextServiceAvailableEvent - */ - public void serviceAvailable(BeanContextServiceAvailableEvent bcsae) { - // noop - } - - /** - * The service named has been revoked. getService requests for - * this service will no longer be satisifed. - * - * @param bcsre the BeanContextServiceRevokedEvent received - * by this listener. - */ - public void serviceRevoked(BeanContextServiceRevokedEvent bcsre) { - // Noop - } - - /** - * *************************************************************** - */ - - /** - * Get the delegate for this child. - */ - protected BeanContextChild getPeer() { - return _peer; - } - - /** - * Fire a property change event. - * @param name - * @param oldValue - * @param newValue - */ - protected void firePropertyChange(String name, Object oldValue, Object newValue) { - _propertyChangeSupport.firePropertyChange(name, oldValue, newValue); - } - - /** - * Release any resources that may have been acumlated from the current bean context, invoked - * by setBeanContext BEFORE the context is changed. - */ - protected void releaseBeanContextResources() { - // noop - } - - /** - * Serialization support -- throw IOException if a non-serializable delegate is present. - * - * @param out - */ - private void writeObject(ObjectOutputStream out) throws IOException { - if (!_peer.equals(this) && !(_peer instanceof Serializable)) { - throw new IOException("Bean context child delegate does not support serialization!!!"); - } - out.defaultWriteObject(); - } - - /** - * Deserialization support -- just deserialize. - * - * @param in - * @throws IOException - * @throws ClassNotFoundException - */ - private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { - in.defaultReadObject(); - } -} diff --git a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/webcontext/ControlBeanContextServicesSupport.java b/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/webcontext/ControlBeanContextServicesSupport.java deleted file mode 100755 index e576fa2..0000000 --- a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/webcontext/ControlBeanContextServicesSupport.java +++ /dev/null @@ -1,638 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ - -package org.apache.beehive.controls.runtime.webcontext; - -import java.beans.beancontext.BeanContext; -import java.beans.beancontext.BeanContextChild; -import java.beans.beancontext.BeanContextServiceAvailableEvent; -import java.beans.beancontext.BeanContextServiceProvider; -import java.beans.beancontext.BeanContextServiceRevokedEvent; -import java.beans.beancontext.BeanContextServiceRevokedListener; -import java.beans.beancontext.BeanContextServices; -import java.beans.beancontext.BeanContextServicesListener; -import java.io.IOException; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; -import java.io.Serializable; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.TooManyListenersException; - -/** - * Implementation of BeanContextServices for Beehive Controls. Assumes single threaded usage. - */ -public class ControlBeanContextServicesSupport extends ControlBeanContextSupport implements BeanContextServices { - - private transient Map _serviceProviders; - private transient List _bcsListeners; - - /** - * Constructor. - */ - public ControlBeanContextServicesSupport() { - super(); - } - - /** - * Constructor which allows delegate to be passed in. - * - * @param peer BeanContextServices peer. - */ - public ControlBeanContextServicesSupport(BeanContextServices peer) { - super(peer); - } - - /** - * Adds a service to this BeanContext. - * BeanContextServiceProviders call this method - * to register a particular service with this context. - * If the service has not previously been added, the - * BeanContextServices associates - * the service with the BeanContextServiceProvider and - * fires a BeanContextServiceAvailableEvent to all - * currently registered BeanContextServicesListeners. - * The method then returns true, indicating that - * the addition of the service was successful. - * If the given service has already been added, this method - * simply returns false. - * - * @param serviceClass the service to add - * @param serviceProvider the BeanContextServiceProvider - * associated with the service - * @return true if service was added. - */ - public boolean addService(Class serviceClass, BeanContextServiceProvider serviceProvider) { - // todo: for multithreaded usage this block needs to be synchronized - if (!_serviceProviders.containsKey(serviceClass)) { - _serviceProviders.put(serviceClass, new ServiceProvider(serviceProvider)); - BeanContextServiceAvailableEvent bcsae = new BeanContextServiceAvailableEvent((BeanContextServices)getPeer(), serviceClass); - fireServiceAvailableEvent(bcsae); - return true; - } - // end synchronized - return false; - } - - /** - * BeanContextServiceProviders wishing to remove - * a currently registered service from this context - * may do so via invocation of this method. Upon revocation of - * the service, the BeanContextServices fires a - * BeanContextServiceRevokedEvent to its - * list of currently registered - * BeanContextServiceRevokedListeners and - * BeanContextServicesListeners. - * - * @param serviceClass the service to revoke from this BeanContextServices - * @param serviceProvider the BeanContextServiceProvider associated with - * this particular service that is being revoked - * @param revokeCurrentServicesNow a value of true - * indicates an exceptional circumstance where the - * BeanContextServiceProvider or - * BeanContextServices wishes to immediately - * terminate service to all currently outstanding references - * to the specified service. - */ - public void revokeService(Class serviceClass, BeanContextServiceProvider serviceProvider, boolean revokeCurrentServicesNow) { - // todo: for multithreaded usage this block needs to be synchronized - if (!_serviceProviders.containsKey(serviceClass)) { - return; - } - - // propagate to any children implementing BeanContextServices - Iterator i = iterator(); - while (i.hasNext()) { - Object o = i.next(); - if (o instanceof BeanContextServices) { - ((BeanContextServices) o).revokeService(serviceClass, serviceProvider, revokeCurrentServicesNow); - } - } - - BeanContextServiceRevokedEvent bcsre = - new BeanContextServiceRevokedEvent((BeanContextServices)getPeer(), serviceClass, revokeCurrentServicesNow); - fireServiceRevokedEvent(bcsre); - - // fire revoked event to requestor listeners, if the service is delegated the owner of the - // service should fire these events. - ServiceProvider sp = _serviceProviders.get(serviceClass); - if (!sp.isDelegated()) { - sp.revoke(bcsre); - } - - if (revokeCurrentServicesNow || !sp.hasRequestors()) { - _serviceProviders.remove(serviceClass); - } - // end synchronized - } - - /** - * Reports whether or not a given service is - * currently available from this context. - * - * @param serviceClass the service in question - * @return true if the service is available - */ - public synchronized boolean hasService(Class serviceClass) { - - // todo: for multithreaded usage this block needs to be synchronized - ServiceProvider sp = _serviceProviders.get(serviceClass); - if (sp != null && !sp.isRevoked()) { - return true; - } - - // if service not found locally check in nested context - BeanContext bc = getBeanContext(); - if (bc instanceof BeanContextServices) { - return ((BeanContextServices) bc).hasService(serviceClass); - } - return false; - // end synchronized - } - - /** - * A BeanContextChild, or any arbitrary object - * associated with a BeanContextChild, may obtain - * a reference to a currently registered service from its - * nesting BeanContextServices - * via invocation of this method. When invoked, this method - * gets the service by calling the getService() method on the - * underlying BeanContextServiceProvider. - * - * @param child the BeanContextChild - * associated with this request - * @param requestor the object requesting the service - * @param serviceClass class of the requested service - * @param serviceSelector the service dependent parameter - * @param bcsrl the - * BeanContextServiceRevokedListener to notify - * if the service should later become revoked - * @return a reference to this context's named - * Service as requested or null - * @throws java.util.TooManyListenersException - * - */ - public Object getService(BeanContextChild child, Object requestor, - Class serviceClass, Object serviceSelector, BeanContextServiceRevokedListener bcsrl) - throws TooManyListenersException { - - if (!contains(child)) { - throw new IllegalArgumentException(child + "is not a child of this context!"); - } - - Object service; - BeanContext bc = getBeanContext(); - - // todo: for multithreaded usage this block needs to be synchronized - // check to see if this is a known service - ServiceProvider sp = _serviceProviders.get(serviceClass); - if (sp != null) { - if (sp.isRevoked()) { - return null; - } - else if (sp.isDelegated()) { - service = ((BeanContextServices) bc).getService(getPeer(), requestor, serviceClass, serviceSelector, bcsrl); - } - else { - service = sp.getBCServiceProvider().getService((BeanContextServices)getPeer(), requestor, serviceClass, serviceSelector); - } - - if (service != null) { - sp.addChildReference(requestor, bcsrl); - } - return service; - } - - // unknown service provider, delegate the request to the nested BeanContextServices (if available) - if (bc instanceof BeanContextServices) { - service = ((BeanContextServices) bc).getService(getPeer(), requestor, serviceClass, serviceSelector, bcsrl); - if (service != null) { - sp = new ServiceProvider(); - sp.addChildReference(requestor, bcsrl); - _serviceProviders.put(serviceClass, sp); - } - return service; - } - return null; - } - - /** - * Releases a BeanContextChild's - * (or any arbitrary object associated with a BeanContextChild) - * reference to the specified service by calling releaseService() - * on the underlying BeanContextServiceProvider. - * - * @param child the BeanContextChild - * @param requestor the requestor - * @param service the service - */ - public void releaseService(BeanContextChild child, Object requestor, Object service) { - - if (!contains(child)) { - throw new IllegalArgumentException(child + "is not a child of this context!"); - } - - // todo: for multithreaded usage this block needs to be synchronized - Class serviceClass = findServiceClass(service); - ServiceProvider sp = _serviceProviders.get(serviceClass); - sp.removeChildReference(requestor); - - // if this is a delegated service, delegate the release request - // delegated services are removed from the _serviceProviders table - // as soon as their reference count drops to zero - if (sp.isDelegated()) { - BeanContextServices bcs = (BeanContextServices) getBeanContext(); - bcs.releaseService(this, requestor, service); - if (!sp.hasRequestors()) { - _serviceProviders.remove(serviceClass); - } - } - else { - sp.getBCServiceProvider().releaseService((BeanContextServices)getPeer(), requestor, service); - } - // end synchronized - } - - /** - * Gets the currently available services for this context. - * - * @return an Iterator consisting of the - * currently available services - */ - public Iterator getCurrentServiceClasses() { - - ArrayList currentClasses = new ArrayList(); - for (Class serviceClass : _serviceProviders.keySet()) { - ServiceProvider sp = _serviceProviders.get(serviceClass); - if (!sp.isRevoked() && !sp.isDelegated()) { - currentClasses.add(serviceClass); - } - } - return currentClasses.iterator(); - } - - /** - * Gets the list of service dependent service parameters - * (Service Selectors) for the specified service, by - * calling getCurrentServiceSelectors() on the - * underlying BeanContextServiceProvider. - * - * @param serviceClass the specified service - * @return the currently available service selectors - * for the named serviceClass - */ - public Iterator getCurrentServiceSelectors(Class serviceClass) { - - if (_serviceProviders.containsKey(serviceClass)) { - ServiceProvider sp = _serviceProviders.get(serviceClass); - if (!sp.isDelegated() && !sp.isRevoked()) { - return sp.getBCServiceProvider().getCurrentServiceSelectors((BeanContextServices)getPeer(), serviceClass); - } - } - return null; - } - - /** - * Adds a BeanContextServicesListener to this BeanContext. - * - * @param bcsl the BeanContextServicesListener to add - */ - public void addBeanContextServicesListener(BeanContextServicesListener bcsl) { - if (!_bcsListeners.contains(bcsl)) { - _bcsListeners.add(bcsl); - } - } - - /** - * Removes a BeanContextServicesListener - * from this BeanContext. - * - * @param bcsl the BeanContextServicesListener - * to remove from this context - */ - public void removeBeanContextServicesListener(BeanContextServicesListener bcsl) { - _bcsListeners.remove(bcsl); - } - - /* - * ********************************************************************************** - * Protected - * ********************************************************************************** - */ - - /** - * Invoked when all resources obtained from the current nested bean context - * need to be released. For BeanContextServices this means revoke any services - * obtained from a delegate services provider. Typically invoked when the parent - * context is changed. - */ - protected synchronized void releaseBeanContextResources() { - - for (Class serviceClass : _serviceProviders.keySet()) { - ServiceProvider sp = _serviceProviders.get(serviceClass); - if (sp.isDelegated()) { - sp.revoke(new BeanContextServiceRevokedEvent((BeanContextServices)getPeer(), serviceClass, true)); - } - } - } - - /* - * ********************************************************************************** - * Private - * ********************************************************************************** - */ - - /** - * first a service available event. - * - * @param bcsae - */ - private void fireServiceAvailableEvent(BeanContextServiceAvailableEvent bcsae) { - for (BeanContextServicesListener bcsl : _bcsListeners) { - bcsl.serviceAvailable(bcsae); - } - } - - /** - * Fire a service revoked event. - * - * @param bcsre - */ - private void fireServiceRevokedEvent(BeanContextServiceRevokedEvent bcsre) { - for (BeanContextServicesListener bcsl : _bcsListeners) { - bcsl.serviceRevoked(bcsre); - } - } - - /** - * Initialize data structures. - */ - protected void initialize() { - super.initialize(); - _serviceProviders = Collections.synchronizedMap(new HashMap()); - _bcsListeners = Collections.synchronizedList(new ArrayList()); - } - - /** - * Try to find the registered service for a service object instance. - * May return null if the object instance is not from a service registered - * with this service provider. - * - * @return Service class for service instance. - * @throws IllegalArgumentException if service class can not be found. - */ - private Class findServiceClass(Object service) { - for (Class sc : _serviceProviders.keySet()) { - if (sc.isInstance(service)) { - return sc; - } - } - throw new IllegalArgumentException("Cannot find service provider for: " + service.getClass().getCanonicalName()); - } - - /** - * Deserialization support. - * - * @param ois - * @throws IOException - * @throws ClassNotFoundException - */ - private synchronized void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException { - ois.defaultReadObject(); - - int svcsSize = ois.readInt(); - for (int i = 0; i < svcsSize; i++) { - _serviceProviders.put((Class) ois.readObject(), (ServiceProvider) ois.readObject()); - } - - int listenersSize = ois.readInt(); - for (int i = 0; i < listenersSize; i++) { - _bcsListeners.add((BeanContextServicesListener) ois.readObject()); - } - } - - /** - * Serialize this instance including any serializable services and BeanContextServicesListeners. - * Any services or listeners which are not Serializable will not be present once deserialized. - * - * @param oos - * @throws IOException - */ - private synchronized void writeObject(ObjectOutputStream oos) throws IOException { - - int serializable = 0; - oos.defaultWriteObject(); - - // write out the service providers - Set> providers = _serviceProviders.entrySet(); - for (Map.Entry provider : providers) { - if (provider.getValue().isSerializable()) { - serializable++; - } - } - - oos.writeInt(serializable); - if (serializable > 0) { - for (Map.Entry entry : providers) { - if (entry.getValue().isSerializable()) { - oos.writeObject(entry.getKey()); - oos.writeObject(entry.getValue()); - } - } - } - - // write out the event listeners - serializable = 0; - for (BeanContextServicesListener l : _bcsListeners) { - if (l instanceof Serializable) { - serializable++; - } - } - - oos.writeInt(serializable); - if (serializable > 0) { - for (BeanContextServicesListener l : _bcsListeners) { - if (l instanceof Serializable) { - oos.writeObject(l); - } - } - } - } - - /* - * *************************************************************************************** - * Inner Classes - * *************************************************************************************** - */ - - /** - * A ServiceProvider instance is associated with a service class in a Map. One ServiceProvider - * exists for a given service type. The Service manager keeps track of all of the requestors - * for the given service. It provides functionality to add new references to services, remove - * references to services, and to notify referenants that a service has been revoked. - */ - private static final class ServiceProvider implements Serializable { - - private transient HashMap _requestors; - private BeanContextServiceProvider _bcss; - private boolean _revoked; - private final boolean _serializable; - - /** - * Constructor for delegated service provider. - */ - private ServiceProvider() { - _bcss = null; - _serializable = false; - } - - /** - * Constructor for local service provider. - */ - private ServiceProvider(BeanContextServiceProvider bcss) { - _bcss = bcss; - _serializable = _bcss instanceof Serializable; - } - - /** - * Add a child reference to this service provider. - * - * @param requestor - * @param bcsrl - * @throws TooManyListenersException - */ - private synchronized void addChildReference(Object requestor, BeanContextServiceRevokedListener bcsrl) - throws TooManyListenersException { - - ChildServiceReference csr = getRequestors().get(requestor); - if (csr == null) { - csr = new ChildServiceReference(bcsrl); - getRequestors().put(requestor, csr); - return; - } - - if (bcsrl != null && !bcsrl.equals(csr.getListener())) { - throw new TooManyListenersException(); - } - csr.incrementRefCount(); - } - - /** - * Remove a child reference from this Service provider. - * - * @param requestor - */ - private synchronized void removeChildReference(Object requestor) { - ChildServiceReference csr = getRequestors().get(requestor); - if (csr == null) return; - int refCount = csr.decrementRefCount(); - if (refCount <= 0) { - getRequestors().remove(requestor); - } - } - - /** - * Notify all the active requestors for this service that the service - * has been revoked (per spec). - */ - private synchronized void revoke(BeanContextServiceRevokedEvent bcsre) { - for (ChildServiceReference csr : getRequestors().values()) { - csr.getListener().serviceRevoked(bcsre); - } - _revoked = true; - } - - /** - * Get the BeanContextServiceProvider. - */ - private BeanContextServiceProvider getBCServiceProvider() { - return _bcss; - } - - /** - * True if this is a delegated service. - */ - private boolean isDelegated() { - return _bcss == null; - } - - /** - * True if this service has been revoked, but still has references. - */ - private boolean isRevoked() { - return _revoked; - } - - /** - * Can this service provider be serialized? - */ - private boolean isSerializable() { - return _serializable && !_revoked && !isDelegated(); - } - - /** - * True if any requestors are being tracked for this service. - */ - private boolean hasRequestors() { - return !getRequestors().isEmpty(); - } - - /** - * Get a reference to the transient requestors hashmap. - */ - private synchronized HashMap getRequestors() { - if (_requestors == null) { - _requestors = new HashMap(); - } - return _requestors; - } - } - - /** - * Keeps track of the number of references to a service for a single requestor. - * Associated with the requestor in the ServiceProvider's _requestors Map. - */ - private static final class ChildServiceReference { - - private int _refCount; - private BeanContextServiceRevokedListener _bcsrl; - - private ChildServiceReference(BeanContextServiceRevokedListener bcsrl) { - _bcsrl = bcsrl; - _refCount = 1; - } - - private int incrementRefCount() { - return ++_refCount; - } - - private int decrementRefCount() { - return --_refCount; - } - - private BeanContextServiceRevokedListener getListener() { - return _bcsrl; - } - } -} diff --git a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/webcontext/ControlBeanContextSupport.java b/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/webcontext/ControlBeanContextSupport.java deleted file mode 100755 index fc4d997..0000000 --- a/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/webcontext/ControlBeanContextSupport.java +++ /dev/null @@ -1,870 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ - -package org.apache.beehive.controls.runtime.webcontext; - -import java.beans.Beans; -import java.beans.PropertyChangeEvent; -import java.beans.PropertyChangeListener; -import java.beans.PropertyVetoException; -import java.beans.VetoableChangeListener; -import java.beans.Visibility; -import java.beans.beancontext.BeanContext; -import java.beans.beancontext.BeanContextChild; -import java.beans.beancontext.BeanContextMembershipEvent; -import java.beans.beancontext.BeanContextMembershipListener; -import java.beans.beancontext.BeanContextProxy; -import java.io.IOException; -import java.io.InputStream; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; -import java.io.Serializable; -import java.net.URL; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Set; - -/** - * BeanContext implementation for Beehive Controls. - */ -public class ControlBeanContextSupport extends ControlBeanContextChildSupport - implements BeanContext, Serializable, PropertyChangeListener, VetoableChangeListener { - - private static final long serialVersionUID = 1L; - - private transient Map _children; - private transient List _bcMembershipListeners; - - // change listeners used for children, in an attempt to prevent - // the unintentional serialization of this bean context by a - // problematic child. - private transient PropertyChangeListener _childPcl; - private transient VetoableChangeListener _childVcl; - - private boolean _designTime = false; - private boolean _mayUseGui = false; - - /** - * Constructor. - */ - public ControlBeanContextSupport() { - super(); - initialize(); - } - - /** - * Constructor. - * - * @param peer - */ - public ControlBeanContextSupport(BeanContext peer) { - super(peer); - initialize(); - } - - /** - * Instantiate the javaBean named as a - * child of this BeanContext. - * The implementation of the JavaBean is - * derived from the value of the beanName parameter, - * and is defined by the - * java.beans.Beans.instantiate() method. - * - * @param beanName The name of the JavaBean to instantiate - * as a child of this BeanContext - * @throws IOException - * @throws ClassNotFoundException if the class identified - * by the beanName parameter is not found - */ - public Object instantiateChild(String beanName) throws IOException, ClassNotFoundException { - BeanContextChild bcc = getPeer(); - return Beans.instantiate(bcc.getClass().getClassLoader(), beanName, (BeanContext) bcc); - } - - /** - * Analagous to java.lang.ClassLoader.getResourceAsStream(), - * this method allows a BeanContext implementation - * to interpose behavior between the child Component - * and underlying ClassLoader. - * - * @param name the resource name - * @param bcc the specified child - * @return an InputStream for reading the resource, - * or null if the resource could not - * be found. - * @throws IllegalArgumentException if the resource is not valid - */ - public InputStream getResourceAsStream(String name, BeanContextChild bcc) throws IllegalArgumentException { - - // bcc must be a child of this context - if (!contains(bcc)) { - throw new IllegalArgumentException("Child is not a member of this context"); - } - - ClassLoader cl = bcc.getClass().getClassLoader(); - InputStream is; - if (cl != null && (is = cl.getResourceAsStream(name)) != null) { - return is; - } - return ClassLoader.getSystemResourceAsStream(name); - } - - /** - * Analagous to java.lang.ClassLoader.getResource(), this - * method allows a BeanContext implementation to interpose - * behavior between the child Component - * and underlying ClassLoader. - * - * @param name the resource name - * @param bcc the specified child - * @return a URL for the named - * resource for the specified child - * @throws IllegalArgumentException if the resource is not valid - */ - public URL getResource(String name, BeanContextChild bcc) throws IllegalArgumentException { - - // bcc must be a child of this context - if (!contains(bcc)) { - throw new IllegalArgumentException("Child is not a member of this context"); - } - - ClassLoader cl = bcc.getClass().getClassLoader(); - URL url; - if (cl != null && (url = cl.getResource(name)) != null) { - return url; - } - return ClassLoader.getSystemResource(name); - } - - /** - * Adds the specified BeanContextMembershipListener - * to receive BeanContextMembershipEvents from - * this BeanContext whenever it adds - * or removes a child Component(s). - * - * @param bcml the BeanContextMembershipListener to be added - */ - public void addBeanContextMembershipListener(BeanContextMembershipListener bcml) { - _bcMembershipListeners.add(bcml); - } - - /** - * Removes the specified BeanContextMembershipListener - * so that it no longer receives BeanContextMembershipEvents - * when the child Component(s) are added or removed. - * - * @param bcml the BeanContextMembershipListener - * to be removed - */ - public void removeBeanContextMembershipListener(BeanContextMembershipListener bcml) { - _bcMembershipListeners.remove(bcml); - } - - /** - * Returns the number of children in this BeanContext. If this BeanContext - * contains more than Integer.MAX_VALUE children, returns - * Integer.MAX_VALUE. - * - * @return the number of elements in this collection - */ - public int size() { - return _children.size(); - } - - /** - * Returns true if this BeanContext has no children. - */ - public boolean isEmpty() { - return _children.isEmpty(); - } - - /** - * Returns true if this BeanContext contains the specified child. - * - * @param o element whose presence in this BeanContext is to be tested. - * @return true if this BeanContext contains the specified child - * @throws ClassCastException if the type of the specified element - * is incompatible with this collection (optional). - * @throws NullPointerException if the specified element is null and this - * collection does not support null elements (optional). - */ - public boolean contains(Object o) { - return _children.containsKey(o); - } - - /** - * Returns an iterator over the elements in this collection. The - * iterator's collection is non-modifiable and element does not - * correspond to the order that children are added. - * - * @return an Iterator over the children of this BeanContext - */ - public Iterator iterator() { - return Collections.unmodifiableSet(_children.keySet()).iterator(); - } - - /** - * Returns an array containing all of the children in this BeanContext. - *

    - * The returned array will be "safe" in that no references to it are - * maintained by this collection. (In other words, this method must - * allocate a new array even if this collection is backed by an array). - * The caller is thus free to modify the returned array.

    - *

    - * This method acts as bridge between array-based and collection-based - * APIs. - * - * @return an array containing all of the elements in this collection - */ - public Object[] toArray() { - return _children.keySet().toArray(); - } - - /** - * Add a child to this BeanContext. If the child is already a child - * of this bean context this method returns immediately with a return - * value of false. - *

    - * If the child implements the BeanContextProxy interface, the child - * AND the BeanContextChild referenced by the proxy are added to this - * BeanContext. - * - * @param o element whose presence in this collection is to be ensured. - * @return true if this collection changed as a result of the - * call - * @throws UnsupportedOperationException add is not supported by - * this collection. - * @throws ClassCastException class of the specified element prevents it - * from being added to this collection. - * @throws NullPointerException if the specified element is null and this - * collection does not support null elements. - * @throws IllegalArgumentException some aspect of this element prevents - * it from being added to this collection. - */ - public boolean add(Object o) { - return internalAdd(o, true); - } - - /** - * Remove the specified child from this BeanContext. If the child - * to be removed implements the BeanContextProxy interface or is - * referenced from an existing BeanContextProxy child both children - * will be removed. - * - * @param o element to be removed from this collection, if present. - * @return true if this collection changed as a result of the - * call - * @throws ClassCastException if the type of the specified element - * is incompatible with this collection (optional). - * @throws NullPointerException if the specified element is null and this - * collection does not support null elements (optional). - * @throws UnsupportedOperationException remove is not supported by this - * collection. - */ - public boolean remove(Object o) { - return internalRemove(o, true); - } - - /** - * Not supported. - * - * @throws UnsupportedOperationException - */ - public boolean addAll(Collection c) { - // NOOP : Not Supported - throw new UnsupportedOperationException(); - } - - /** - * Not supported. - * - * @throws UnsupportedOperationException - */ - public void clear() { - // NOOP: Not supported - throw new UnsupportedOperationException(); - } - - /** - * Not supported. - * - * @throws UnsupportedOperationException - */ - public boolean retainAll(Collection c) { - // NOOP: Not supported - throw new UnsupportedOperationException(); - } - - /** - * Not supported. - * - * @throws UnsupportedOperationException - */ - public boolean removeAll(Collection c) { - throw new UnsupportedOperationException(); - } - - /** - * Returns true if this BeanContext contains all of the children - * in the specified collection. - * - * @param c collection to be checked for containment in this collection. - * @return true if this collection contains all of the elements - * in the specified collection - * @throws ClassCastException if the types of one or more elements - * in the specified collection are incompatible with this - * collection (optional). - * @throws NullPointerException if the specified collection contains one - * or more null elements and this collection does not support null - * elements (optional). - * @throws NullPointerException if the specified collection is - * null. - * @see #contains(Object) - */ - public boolean containsAll(Collection c) { - return _children.keySet().containsAll(c); - } - - /** - * Returns an array containing all of the children of this BeanContext; - * the runtime type of the returned array is that of the specified array. - * - * @param a the array into which the elements of this collection are to be - * stored, if it is big enough; otherwise, a new array of the same - * runtime type is allocated for this purpose. - * @return an array containing the elements of this collection - * @throws ArrayStoreException the runtime type of the specified array is - * not a supertype of the runtime type of every element in this - * collection. - * @throws NullPointerException if the specified array is null. - */ - public Object[] toArray(Object[] a) { - return _children.keySet().toArray(a); - } - - /** - * Sets the "value" of the "designTime" property. - *

    - * If the implementing object is an instance of java.beans.beancontext.BeanContext, - * or a subinterface thereof, then that BeanContext should fire a - * PropertyChangeEvent, to its registered BeanContextMembershipListeners, with - * parameters: - *

      - *
    • propertyName - java.beans.DesignMode.PROPERTYNAME - *
    • oldValue - previous value of "designTime" - *
    • newValue - current value of "designTime" - *
    - * Note it is illegal for a BeanContextChild to invoke this method - * associated with a BeanContext that it is nested within. - * - * @param designTime the current "value" of the "designTime" property - * @see java.beans.beancontext.BeanContext - * @see java.beans.beancontext.BeanContextMembershipListener - * @see java.beans.PropertyChangeEvent - */ - public void setDesignTime(boolean designTime) { - if (designTime == _designTime) return; - _designTime = designTime; - firePropertyChange("designTime", !_designTime, designTime); - } - - /** - * A value of true denotes that JavaBeans should behave in design time - * mode, a value of false denotes runtime behavior. - * - * @return the current "value" of the "designTime" property. - */ - public boolean isDesignTime() { - return _designTime; - } - - /** - * Determines whether this bean needs a GUI. - * - * @return True if the bean absolutely needs a GUI available in - * order to get its work done. - */ - public boolean needsGui() { - BeanContextChild bcc = getPeer(); - if (bcc != this && bcc instanceof Visibility) { - return ((Visibility) bcc).needsGui(); - } - - // check children - for (Object o : _children.keySet()) { - if (o instanceof Visibility) { - if (((Visibility) o).needsGui()) { - return true; - } - } - } - return false; - } - - /** - * This method instructs the bean that it should not use the Gui. - */ - public void dontUseGui() { - if (!_mayUseGui) return; - - _mayUseGui = false; - - for (Object o : _children.keySet()) { - if (o instanceof Visibility) { - ((Visibility) o).dontUseGui(); - } - } - } - - /** - * This method instructs the bean that it is OK to use the Gui. - */ - public void okToUseGui() { - if (_mayUseGui) return; - - _mayUseGui = true; - - for (Object o : _children.keySet()) { - if (o instanceof Visibility) { - ((Visibility) o).okToUseGui(); - } - } - } - - /** - * Determines whether this bean is avoiding using a GUI. - * - * @return true if the bean is currently avoiding use of the Gui. - * e.g. due to a call on dontUseGui(). - */ - public boolean avoidingGui() { - return !_mayUseGui && needsGui(); - } - - /** - * This method gets called when a bound property is changed. - * - * @param evt A PropertyChangeEvent object describing the event source - * and the property that has changed. - */ - public void propertyChange(PropertyChangeEvent evt) { - // monitor "beanContext" property - if ("beanContext".equals(evt.getPropertyName()) && contains(evt.getSource())) { - BeanContext bc = (BeanContext) getPeer(); - if (bc.equals(evt.getOldValue()) && !bc.equals(evt.getNewValue())) { - internalRemove(evt.getSource(), false); - } - } - } - - /** - * This method gets called when a constrained property is changed. - * - * @param evt a PropertyChangeEvent object describing the - * event source and the property that has changed. - * @throws java.beans.PropertyVetoException - * if the recipient wishes the property - * change to be rolled back. - */ - public void vetoableChange(PropertyChangeEvent evt) throws PropertyVetoException { - // monitor "beanContext" property - if ("beanContext".equals(evt.getPropertyName()) - && contains(evt.getOldValue())) { - // noop: at this point doesn't veto - } - } - - /** - * ************************************************************************************* - */ - - - /** - * Init this classes data structures. - */ - protected void initialize() { - _bcMembershipListeners = new ArrayList(); - _children = Collections.synchronizedMap(new HashMap()); - - _childPcl = new PropertyChangeListener() { - public void propertyChange(PropertyChangeEvent pce) { - ControlBeanContextSupport.this.propertyChange(pce); - } - }; - - _childVcl = new VetoableChangeListener() { - public void vetoableChange(PropertyChangeEvent pce) throws PropertyVetoException { - ControlBeanContextSupport.this.vetoableChange(pce); - } - }; - } - - /** - * Fire a BeanContextMembershipEvent. - * - * @param bcme Event to fire. - * @param childrenAdded True if add event, false if remove event. - */ - private void fireMembershipEvent(BeanContextMembershipEvent bcme, boolean childrenAdded) { - - for (BeanContextMembershipListener bcml : _bcMembershipListeners) { - if (childrenAdded) { - bcml.childrenAdded(bcme); - } - else { - bcml.childrenRemoved(bcme); - } - } - } - - /** - * The internalAdd method is used in two different cases. If an add is done - * through the public add() api, this method is invoked with the publicApi - * parameter set to true. During deserialization of children this method - * is invoked with publicApi set to false. During deserialization it is - * not necessary to set Visibility features or re-register as a listener. - * - * @param o - * @param publicApi - * @return true if added. - */ - private boolean internalAdd(Object o, boolean publicApi) { - - if (contains(o)) return false; - - // todo: for multithreaded usage this block needs to be synchronized - // spec: if the object being added implements BeanContextChild or BeanContextProxy - // need to set the bean context of the object to this bean context. - BeanContextChild bcc = null; - BeanContextProxy bcp = null; - - if (o instanceof BeanContextProxy) { - if (o instanceof BeanContext) { - throw new IllegalArgumentException("May not implement both BeanContextProxy and BeanContext!!"); - } - bcp = (BeanContextProxy) o; - bcc = bcp.getBeanContextProxy(); - } - else if (o instanceof BeanContextChild) { - bcc = (BeanContextChild) o; - } - - if (bcc != null) { - try { - bcc.setBeanContext((BeanContext) getPeer()); - } - catch (PropertyVetoException e) { - throw new IllegalStateException(e); - } - - bcc.addPropertyChangeListener("beanContext", _childPcl); - bcc.addVetoableChangeListener("beanContext", _childVcl); - } - - if (publicApi) { - if (o instanceof Visibility) { - if (_mayUseGui) { - ((Visibility) o).okToUseGui(); - } - else { - ((Visibility) o).dontUseGui(); - } - } - if (o instanceof BeanContextMembershipListener) { - addBeanContextMembershipListener((BeanContextMembershipListener) o); - } - } - - if (bcp == null) { - _children.put(o, new BCChild(o)); - } - else { - _children.put(bcp, new BCChild(bcp, bcc, true)); - _children.put(bcc, new BCChild(bcp, bcc, false)); - } - - BeanContextMembershipEvent bcme = new BeanContextMembershipEvent((BeanContext) getPeer(), new Object[]{o}); - fireMembershipEvent(bcme, true); -// } - return true; - } - - /** - * There are two ways a object can be removed from a BeanContext, by either explicitly invoking the - * remove() api or if the child implements BeanContextChild by calling its setBeanContext() api. - * - * @param o - * @param publicApi - * @return true if successful - */ - private boolean internalRemove(Object o, boolean publicApi) { - - if (!contains(o)) return false; - - // todo: for multithreaded usage this block needs to be synchronized - BeanContextChild bcc = null; - if (o instanceof BeanContextProxy) { - bcc = ((BeanContextProxy) o).getBeanContextProxy(); - } - else if (o instanceof BeanContextChild) { - bcc = (BeanContextChild) o; - } - - if (bcc != null) { - - /* - If remove invoked as a result of the BeanContext receiving an unexpected PropertyChangeEvent - notification as a result of a 3rd party invoking setBeanContext() then the remove implementation - shall not invoke setBeanContext(null) on that child as part of the remove() semantics, since - doing so would overwrite the value previously set by the 3rd party. - */ - if (publicApi) { - - // remove the property/veto listeners -- we know we want to remove the bean - // and don't need to be notified if we have initiated the removal - bcc.removePropertyChangeListener("beanContext", _childPcl); - bcc.removeVetoableChangeListener("beanContext", _childVcl); - - try { - bcc.setBeanContext(null); - } - catch (PropertyVetoException e) { - // rewire the listeners we removed above then except - bcc.addPropertyChangeListener("beanContext", _childPcl); - bcc.addVetoableChangeListener("beanContext", _childVcl); - throw new IllegalStateException(e); - } - } - } - - if (o instanceof BeanContextMembershipListener) { - removeBeanContextMembershipListener((BeanContextMembershipListener) o); - } - - BCChild bc = _children.get(o); - if (bc.isProxy()) { - _children.remove(bc.getChild()); - } - else if (bc.hasProxy()) { - _children.remove(bc.getProxy()); - } - _children.remove(o); - - BeanContextMembershipEvent bcme = new BeanContextMembershipEvent((BeanContext) getPeer(), new Object[]{o}); - fireMembershipEvent(bcme, false); - // end synchronized block - return true; - } - - /** - * Serialize all serializable children (unless this BeanContext has a peer). Any - * children which are not serializable not be present upon deserialization. Also - * serialize any BeanContextMembership listeners which are serializable. - * - * @param out ObjectOutputStream to serialize to. - */ - private synchronized void writeObject(ObjectOutputStream out) throws IOException { - - // todo: for multithreaded usage this block needs to be synchronized - out.defaultWriteObject(); - - // spec: only write children if not using a peer - if (this.equals(getPeer())) { - writeChildren(out); - } - else { - out.writeInt(0); - } - - // write event handlers - int serializable = 0; - for (BeanContextMembershipListener listener : _bcMembershipListeners) { - if (listener instanceof Serializable) serializable++; - } - - out.writeInt(serializable); - if (serializable > 0) { - for (BeanContextMembershipListener listener : _bcMembershipListeners) { - if (listener instanceof Serializable) { - out.writeObject(listener); - } - } - } - // end synchronized block - } - - /** - * Necessary for the case of this bean context having a peer. The specification - * states that a bean context which has a peer should not serialize its children, - * this hook is necessary to allow the peer to serialize children. - * - * @param oos ObjectOutputStream - * @throws IOException - */ - public final void writeChildren(ObjectOutputStream oos) throws IOException { - int serializable = 0; - Set> bcChildren = _children.entrySet(); - for (Map.Entry entry : bcChildren) { - if (entry.getValue().isSerializable()) { - serializable++; - } - } - - oos.writeInt(serializable); - if (serializable > 0) { - for (Map.Entry bc : bcChildren) { - if (bc.getValue().isSerializable()) { - oos.writeObject(bc.getKey()); - } - } - } - } - - /** - * Deserialize this an instance of this class, including any children and - * BeanContextMembershipListeners which were present during serialization and - * were serializable. - * - * @param in ObjectInputStream to deserialize from. - * @throws IOException - * @throws ClassNotFoundException - */ - private synchronized void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { - // todo: for multithreaded usage this block needs to be synchronized - in.defaultReadObject(); - initialize(); - - // only deserialize child if not using a peer - if (this.equals(getPeer())) { - readChildren(in); - } - - int listenerCount = in.readInt(); - for (int i = 0; i < listenerCount; i++) { - addBeanContextMembershipListener((BeanContextMembershipListener) in.readObject()); - } - // end synchronized block - } - - /** - * This public api is necessary to allow a bean context with a peer to deserialize its children. - * This api is not part any standard api. - * - * @param in ObjectInputStream - * @throws IOException - * @throws ClassNotFoundException - */ - public final void readChildren(ObjectInputStream in) throws IOException, ClassNotFoundException { - int childCount = in.readInt(); - for (int i = 0; i < childCount; i++) { - internalAdd(in.readObject(), false); - } - } - - /** - * A child of this BeanContext. This class is used to manage the relationship - * between a BeanContextProxy and its BeanContextChild. When a BeanContextProxy - * is added or removed from this context the BeanContextChild it references must - * also be added or removed. This requires that both the BeanContextChild and - * BeanContextProxy are added/removed to the list of children. This class - * is used to map from the proxy -> child and child -> proxy. - *

    - * The _child field is always guarenteed to be non-null, the proxy field may - * be null if this child does not have a proxy. - */ - private final static class BCChild { - - private Object _child; - private BeanContextProxy _proxy; - private boolean _isProxy; - private boolean _serializable; - - /** - * Construct a new BCChild for a child which is not related to a BeanContextProxy. - * - * @param child child to add -- must not be an instance of BeanContextProxy. - */ - protected BCChild(Object child) { - assert child != null; - assert !(child instanceof BeanContextProxy); - - _child = child; - _proxy = null; - _isProxy = false; - _serializable = _child instanceof Serializable; - } - - /** - * Construct a new BCChild for a proxy -> child relationship. - * - * @param proxy BeanContextProxy - * @param child BeanContextChild - * @param isProxy true if this will be entered into the child map keyed on the proxy. - */ - protected BCChild(BeanContextProxy proxy, BeanContextChild child, boolean isProxy) { - assert child != null; - assert proxy != null; - - _child = child; - _proxy = proxy; - _isProxy = isProxy; - _serializable = (_isProxy) && _child instanceof Serializable && _proxy instanceof Serializable; - } - - /** - * Get the proxy. - */ - protected BeanContextProxy getProxy() { - return _proxy; - } - - /** - * Get the child. - */ - protected Object getChild() { - return _child; - } - - /** - * True if a proxy was set for this child. - */ - protected boolean hasProxy() { - return _proxy != null; - } - - /** - * True if this child was keyed by its proxy in the child map. - */ - protected boolean isProxy() { - return _isProxy; - } - - /** - * True if this BCChild is serializable. - */ - protected boolean isSerializable() { - return _serializable; - } - } -} diff --git a/beehive-controls/src/main/java/org/apache/beehive/controls/spi/bean/ControlFactory.java b/beehive-controls/src/main/java/org/apache/beehive/controls/spi/bean/ControlFactory.java deleted file mode 100644 index b37edab..0000000 --- a/beehive-controls/src/main/java/org/apache/beehive/controls/spi/bean/ControlFactory.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.spi.bean; - -import org.apache.beehive.controls.api.bean.ControlBean; -import org.apache.beehive.controls.api.context.ControlBeanContext; -import org.apache.beehive.controls.api.properties.PropertyMap; - -/** - * The ControlFactory interface defines a service provider interface for integrating - * an external JavaBean instantation/configuration framework with the Controls runtime. - */ -public interface ControlFactory -{ - /** - * Instantiates a new ControlBean of the requested class, using mechanisms provided - * by a provider-specific JavaBeans framework. - * - * @param beanClass the ControlBean class to instantiate - * @param props an initial set of client-specified properties to associate with the - * bean instance. May be null. - * @param context the containing ControlBeanContext for the bean, if nested inside of - * a container or other control. May be null to use the current active - * execution context. - * @param id the bean control ID. Must be unique within the containing context. If - * null, a unique identifier will be auto-generated. - * @return a new ControlBean instance of the requested class. - */ - public T instantiate(Class beanClass, - PropertyMap props, - ControlBeanContext context, - String id); -} diff --git a/beehive-controls/src/main/java/org/apache/beehive/controls/spi/bean/JavaControlFactory.java b/beehive-controls/src/main/java/org/apache/beehive/controls/spi/bean/JavaControlFactory.java deleted file mode 100644 index 900b106..0000000 --- a/beehive-controls/src/main/java/org/apache/beehive/controls/spi/bean/JavaControlFactory.java +++ /dev/null @@ -1,133 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.spi.bean; - -import java.io.InputStream; -import java.io.IOException; -import java.lang.reflect.Constructor; -import java.lang.reflect.InvocationTargetException; -import java.util.Properties; -import java.util.concurrent.ConcurrentHashMap; - -import org.apache.beehive.controls.api.properties.PropertyMap; -import org.apache.beehive.controls.api.properties.BeanPropertyMap; -import org.apache.beehive.controls.api.properties.PropertyKey; -import org.apache.beehive.controls.api.bean.ControlBean; -import org.apache.beehive.controls.api.context.ControlBeanContext; -import org.apache.beehive.controls.api.ControlException; - -/** - * The SimpleControlFactory class is a default implementation of the - * org.apache.beehive.controls.api.bean.ControlFactory interface. It - * uses Java reflection to create new control instances. - * - * @see org.apache.beehive.controls.api.bean.Controls#instantiate - * @see org.apache.beehive.controls.spi.bean.ControlFactory - */ -public class JavaControlFactory implements ControlFactory -{ - private static ConcurrentHashMap _constructors = new ConcurrentHashMap(); - - private static final Properties _extImplBindings = new Properties(); - - private static final String EXT_IMPL_BINDING_CONFIG = "controlbindings.properties"; - private static final String KEY_CONTROL_IMPLEMENTATION = "controlImplementation"; - - static - { - InputStream is = JavaControlFactory.class.getClassLoader().getResourceAsStream( EXT_IMPL_BINDING_CONFIG ); - - if (is != null) { - try { - _extImplBindings.load(is); - } - catch(IOException ignore) { - // ignore... - } - finally { - try{is.close();} - catch(IOException ignore) { - // ignore... - } - } - } - } - - /** - * Instantiates a new ControlBean of the requested class, using mechanisms provided - * by a provider-specific JavaBeans framework. - * - * @param beanClass the ControlBean class to instantiate - * @param props an initial set of client-specified properties to associate with the - * bean instance. May be null. - * @param context the containing ControlBeanContext for the bean, if nested inside of - * a container or other control. May be null to use the current active - * execution context. - * @param id the bean control ID. Must be unique within the containing context. If - * null, a unique identifier will be auto-generated. - * @return a new ControlBean instance of the requested class. - */ - public T instantiate(Class beanClass, - PropertyMap props, - ControlBeanContext context, - String id) - { - String beanClassName = beanClass.getName(); - - String extImplBinding = _extImplBindings.getProperty( beanClassName + "_" + id ); - if ( extImplBinding == null ) - extImplBinding = _extImplBindings.getProperty( beanClassName ); - - if ( extImplBinding != null ) - { - BeanPropertyMap bpm = props == null ? new BeanPropertyMap( beanClass ) : new BeanPropertyMap( props ); - PropertyKey propKey = new PropertyKey(org.apache.beehive.controls.api.properties.BaseProperties.class, - KEY_CONTROL_IMPLEMENTATION); - - bpm.setProperty( propKey, extImplBinding ); - props = bpm; - } - - T ret = null; - try - { - Constructor ctor = _constructors.get(beanClass); - if (ctor == null) - { - ctor = beanClass.getConstructor(ControlBeanContext.class, - String.class, - PropertyMap.class); - - _constructors.put(beanClass, ctor); - } - ret = ctor.newInstance(context, id, props); - } - catch (InvocationTargetException ite) - { - Throwable t = ite.getCause(); - throw new ControlException("ControlBean constructor exception", t); - } - catch (Exception e) - { - throw new ControlException("Exception creating ControlBean", e); - } - - return ret; - } -} diff --git a/beehive-controls/src/main/java/org/apache/beehive/controls/spi/context/ControlBeanContextFactory.java b/beehive-controls/src/main/java/org/apache/beehive/controls/spi/context/ControlBeanContextFactory.java deleted file mode 100644 index fbd9494..0000000 --- a/beehive-controls/src/main/java/org/apache/beehive/controls/spi/context/ControlBeanContextFactory.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.spi.context; - -import org.apache.beehive.controls.api.bean.ControlBean; -import org.apache.beehive.controls.api.context.ControlBeanContext; - -/** - * The ControlBeanContextFactory defines a service provider interface for providing implementations - * of factories to create a {@link org.apache.beehive.controls.api.context.ControlBeanContext} - * object. This factory is only used to create ControlBeanContexts that are associated - * with a ControlBean instance; it is not used to create - * {@link org.apache.beehive.controls.api.context.ControlContainerContext} objects. - */ -public interface ControlBeanContextFactory { - - /** - * Instantiate a {@link ControlBeanContext} object that will be associated with the - * provided {@link ControlBean}. - * - * @param controlBean - * @return the ControlBeanContext instance - */ - public T instantiate(ControlBean controlBean); -} diff --git a/beehive-controls/src/main/java/org/apache/beehive/controls/spi/svc/Interceptor.java b/beehive-controls/src/main/java/org/apache/beehive/controls/spi/svc/Interceptor.java deleted file mode 100644 index 8d9fb80..0000000 --- a/beehive-controls/src/main/java/org/apache/beehive/controls/spi/svc/Interceptor.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.spi.svc; - -import java.lang.reflect.Method; - -import org.apache.beehive.controls.api.bean.ControlBean; - -/** - * The controls implementation architecture has a interceptor model for - * adding annotation-based features. This model provides the ability to - * associate a JavaBeans service interface with an annotation to define - * its runtime feature behaviour. Such interfaces must extend this - * Interceptor interface, which defines the contract that the controls runtime - * has with interceptors. - * - * The controls runtime will automatically instantiate and execute - * implementations of interceptors at the appropriate execution points - * (pre/post invocation of a control operation, etc). - * - * The control runtime will continue the normal flow of control (ie, subsequent - * interceptors and operation/event execution) unless an interceptor throws a - * {@link InterceptorPivotException}. When this type of execption is encountered, - * the runtime will "pivot" out. - */ -public interface Interceptor -{ - /** Called before a control operation is invoked */ - public void preInvoke( ControlBean cb, Method m, Object [] args) - throws InterceptorPivotException; - - /** Called after a control operation is invoked */ - public void postInvoke( ControlBean cb, Method m, Object [] args, Object retval, Throwable t ); - - /** Called before a control event is fired (through a client proxy) */ - public void preEvent( ControlBean cb, Class eventSet, Method m, Object [] args ) - throws InterceptorPivotException; - - /** Called after a control event is fired (through a client proxy) */ - public void postEvent( ControlBean cb, Class eventSet, Method m, Object [] args, Object retval, Throwable t ); -} diff --git a/beehive-controls/src/main/java/org/apache/beehive/controls/spi/svc/InterceptorAnnotation.java b/beehive-controls/src/main/java/org/apache/beehive/controls/spi/svc/InterceptorAnnotation.java deleted file mode 100644 index b8c0361..0000000 --- a/beehive-controls/src/main/java/org/apache/beehive/controls/spi/svc/InterceptorAnnotation.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.spi.svc; - -import java.lang.annotation.Documented; -import java.lang.annotation.ElementType; -import java.lang.annotation.Target; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; - -/** - * InterceptorAnnotation is the meta-annotation used to identify annotations - * that are interceptor-based, and bind an interceptor service interface to - * those annotations. - */ -@Documented -@Retention(RetentionPolicy.RUNTIME) -@Target(ElementType.ANNOTATION_TYPE) -public @interface InterceptorAnnotation -{ - /** - * The Interceptor-based JavaBeans service interface associated with the annotated annotation - * */ - Class service(); -} diff --git a/beehive-controls/src/main/java/org/apache/beehive/controls/spi/svc/InterceptorPivotException.java b/beehive-controls/src/main/java/org/apache/beehive/controls/spi/svc/InterceptorPivotException.java deleted file mode 100644 index e7be967..0000000 --- a/beehive-controls/src/main/java/org/apache/beehive/controls/spi/svc/InterceptorPivotException.java +++ /dev/null @@ -1,111 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.spi.svc; - -/** - * The InterceptorPivotException class declares a checked exception that is thrown by - * an Interceptor upon pivoting. For example, if an interceptor wishes to stop a method - * from executing further and return a value, it can throw this exception and embed in - * the exception the return value that it wishes the method to return. - */ -public class InterceptorPivotException - extends Exception -{ - /** - * Comment for serialVersionUID - */ - private static final long serialVersionUID = 1L; - private Object returnValue; - private String interceptorName; - - /** - * Constructs a InterceptorPivotException object with the specified interceptor. - * - * @param interceptorName name of the interceptor that generated this exception - */ - public InterceptorPivotException(String interceptorName) - { - super(); - this.interceptorName = interceptorName; - } - - /** - * Constructs a InterceptorPivotException object with the specified interceptor - * and return value for the method that is intercepted. - * - * @param interceptorName name of the interceptor that generated this exception - * @param returnValue the return value of the method that is intercepted. - */ - public InterceptorPivotException(String interceptorName, Object returnValue) - { - super(); - this.interceptorName = interceptorName; - this.returnValue = returnValue; - } - - /** - * Constructs a ServiceException object using the specified interceptor, the - * return value for the method that is intercepted and message. - * - * @param interceptorName name of the interceptor that generated this exception - * @param returnValue the return value of the method that is intercepted. - * @param message The message to use. - */ - public InterceptorPivotException(String interceptorName, Object returnValue, String message) - { - super(message); - this.interceptorName = interceptorName; - this.returnValue = returnValue; - } - - /** - * Constructs a ServiceException object using the specified interceptor and - * a message. - * - * @param interceptorName name of the interceptor that generated this exception - * @param message The message to use. - */ - public InterceptorPivotException(String interceptorName, String message) - { - super(message); - this.interceptorName = interceptorName; - } - - /** - * @return Returns the interceptorName. - */ - public String getInterceptorName() - { - return interceptorName; - } - /** - * @return Returns the returnValue. - */ - public Object getReturnValue() - { - return returnValue; - } - /** - * @param interceptorName The interceptorName to set. - */ - public void setInterceptorName(String interceptorName) - { - this.interceptorName = interceptorName; - } -} diff --git a/beehive-controls/src/main/java/org/apache/beehive/controls/spi/svc/ServiceException.java b/beehive-controls/src/main/java/org/apache/beehive/controls/spi/svc/ServiceException.java deleted file mode 100644 index 6b5cfc4..0000000 --- a/beehive-controls/src/main/java/org/apache/beehive/controls/spi/svc/ServiceException.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.spi.svc; - -/** - * The ServiceException class declares an checked exception that is thrown by the Service API - * runtime under certain failure conditions. - */ -public class ServiceException - extends Exception -{ - /** - * Constructs a ServiceException object with the specified String as a message. - * - * @param message The message to use. - */ - public ServiceException(String message) - { - super(message); - } - - /** - * Constructs a ServiceException object using the specified String as a message, and the - * specified Throwable as a nested exception. - * - * @param message The message to use. - * @param t The exception to nest within this - * exception. - */ - public ServiceException(String message, Throwable t) - { - super(message + "[" + t.getMessage() + "]", t); - } - - /* Private Constant(s) */ - private static final long serialVersionUID = 8818197331269164527L; -} diff --git a/beehive-controls/src/main/java/org/apache/beehive/controls/test/ControlTestException.java b/beehive-controls/src/main/java/org/apache/beehive/controls/test/ControlTestException.java deleted file mode 100644 index 96fc041..0000000 --- a/beehive-controls/src/main/java/org/apache/beehive/controls/test/ControlTestException.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.test; - -/** - * Exception type thrown when the controls test infrastructure reports framework errors. - */ -public class ControlTestException - extends RuntimeException { - - public ControlTestException() { - super(); - } - - public ControlTestException(String message) { - super(message); - } - - public ControlTestException(Throwable cause) { - super(cause); - } - - public ControlTestException(String message, Throwable cause) { - super(message, cause); - } -} diff --git a/beehive-controls/src/main/java/org/apache/beehive/controls/test/container/ControlTestContainerContext.java b/beehive-controls/src/main/java/org/apache/beehive/controls/test/container/ControlTestContainerContext.java deleted file mode 100644 index 15642ef..0000000 --- a/beehive-controls/src/main/java/org/apache/beehive/controls/test/container/ControlTestContainerContext.java +++ /dev/null @@ -1,87 +0,0 @@ -/* - 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. - - $Header:$ -*/ -package org.apache.beehive.controls.test.container; - -import java.io.InputStream; -import java.beans.beancontext.BeanContextChild; -import java.beans.beancontext.BeanContextServiceProvider; - -import org.apache.beehive.controls.runtime.bean.ControlContainerContext; -import org.apache.beehive.controls.runtime.bean.WebContextFactoryProvider; -import org.apache.beehive.controls.spi.context.ControlBeanContextFactory; - -/** - * ControlContainerContext implementation used to test controls in a standalone JVM. - */ -public class ControlTestContainerContext - extends ControlContainerContext { - - private transient BeanContextServiceProvider _cbcFactoryProvider; - - public ControlTestContainerContext(){ - // - // This sets the BeanContextServicesFactory instance on the ControlBeanContext and allows this - // CCC object to be created with a BeanContextServicesDelegate of the type returned by this factory - // - super(WebContextFactoryProvider.WEB_CONTEXT_BCS_FACTORY); - } - - /** - * Called by BeanContextSupport superclass during construction and deserialization to - * initialize subclass transient state - */ - public void initialize() - { - super.initialize(); - // Register an *internal* service that is used to create ControlBeanContext objects for - // children of this control container - // - _cbcFactoryProvider = WebContextFactoryProvider.getProvider(); - addService(ControlBeanContextFactory.class, _cbcFactoryProvider); - } - - /** - * Override ControlBeanContext.getService(). A control bean creates its bean context using the - * ControlBeanContextFactory service provided by this context. A control bean will attempt to create - * its context before adding its self to this context as a child. This creates a chicken/egg problem since - * only a child of a context may request a service from it. - * - * This method provides a way to crack the chicken/egg problem by first trying to get the service using the - * control bean context's getService() method, and if that call returns null and the requested service is - * the ControlBeanContextFactory then returning an instance of the service provider. - * - * @param serviceClass - * @param selector - * @return - */ - public T getService(Class serviceClass, Object selector) - { - T service = super.getService(serviceClass, selector); - if (service == null && serviceClass.equals(ControlBeanContextFactory.class)) { - return (T)_cbcFactoryProvider.getService(this, this, serviceClass, selector); - } - return service; - } - - public InputStream getResourceAsStream(String name, BeanContextChild bcc) { - ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); - InputStream inputStream = classLoader.getResourceAsStream(name); - return inputStream; - } -} diff --git a/beehive-controls/src/main/java/org/apache/beehive/controls/test/junit/ControlTestCase.java b/beehive-controls/src/main/java/org/apache/beehive/controls/test/junit/ControlTestCase.java deleted file mode 100644 index 9ebaa37..0000000 --- a/beehive-controls/src/main/java/org/apache/beehive/controls/test/junit/ControlTestCase.java +++ /dev/null @@ -1,103 +0,0 @@ -/* - 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. - - $Header:$ -*/ -package org.apache.beehive.controls.test.junit; - -import junit.framework.TestCase; - -import org.apache.beehive.controls.api.bean.ControlBean; -import org.apache.beehive.controls.api.context.ControlContainerContext; -import org.apache.beehive.controls.api.context.ControlThreadContext; -import org.apache.beehive.controls.test.container.ControlTestContainerContext; -import org.apache.beehive.controls.test.util.ControlContainerContextManager; -import org.apache.beehive.controls.test.util.ControlContainerContextManagerFactory; -import org.apache.beehive.controls.test.ControlTestException; - -/** - * Base control test case. - */ -public abstract class ControlTestCase - extends TestCase { - - /* todo: push strings into a .properties file */ - - private ControlContainerContextManager _controlContainerContextManager = null; - - public void setUp() - throws Exception { - - super.setUp(); - - beginContext(); - initializeControls(); - } - - public void tearDown() - throws Exception { - - super.tearDown(); - - endContext(); - } - - protected ControlContainerContext initializeControlContainerContext() { - return new ControlTestContainerContext(); - } - - protected ControlContainerContext getControlContainerContext() { - return getControlContainerContextManager().getControlContainerContext(); - } - - protected void initializeControls() { - getControlContainerContextManager().instantiateControls(this); - } - - protected void beginContext() { - getControlContainerContextManager().beginContext(); - } - - protected void endContext() { - getControlContainerContextManager().endContext(); - } - - protected ControlContainerContextManager getControlContainerContextManager() { - if(_controlContainerContextManager == null) { - ControlContainerContext ccc = initializeControlContainerContext(); - - if(ccc == null) - throw new ControlTestException("Could not instantiate a ControlContainerContextManager as the control container context was null"); - - _controlContainerContextManager = ControlContainerContextManagerFactory.getInstance(ccc); - } - - return _controlContainerContextManager; - } - - protected ControlBean instantiateControl(String className) { - ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); - try { - Object controlBean = java.beans.Beans.instantiate(classLoader, className, ControlThreadContext.getContext()); - assert controlBean instanceof ControlBean; - return (ControlBean)controlBean; - } - catch(Exception e) { - throw new ControlTestException("Could not instantiate control with class \"" + className + - "\". Cause: " + e.getMessage(), e); - } - } -} diff --git a/beehive-controls/src/main/java/org/apache/beehive/controls/test/util/ControlContainerContextManager.java b/beehive-controls/src/main/java/org/apache/beehive/controls/test/util/ControlContainerContextManager.java deleted file mode 100644 index f1a25b3..0000000 --- a/beehive-controls/src/main/java/org/apache/beehive/controls/test/util/ControlContainerContextManager.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - 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. - - $Header:$ -*/ -package org.apache.beehive.controls.test.util; - -import org.apache.beehive.controls.api.bean.Controls; -import org.apache.beehive.controls.api.context.ControlThreadContext; -import org.apache.beehive.controls.api.context.ControlContainerContext; -import org.apache.beehive.controls.test.ControlTestException; - -/** - * - */ -public class ControlContainerContextManager { - - private ControlContainerContext _controlContainerContext; - - protected ControlContainerContextManager(ControlContainerContext controlContainerContext) { - super(); - _controlContainerContext = controlContainerContext; - } - - public ControlContainerContext getControlContainerContext() { - return ControlThreadContext.getContext(); - } - - public void instantiateControls(Object object) { - Class testClass = object.getClass(); - try { - Controls.initializeClient(Thread.currentThread().getContextClassLoader(), object, ControlThreadContext.getContext()); - } - catch(Exception e) { - if(e.getCause() instanceof ClassNotFoundException) - System.err.println("Could not locate initializer for '" + getClass().getName() + "'. Assuming no controls to initialize"); - else throw new ControlTestException("Exception initializing controls for type '" + testClass.getName() + "'", e); - } - } - - public void beginContext() { - _controlContainerContext.beginContext(); - } - - public void endContext() { - _controlContainerContext.endContext(); - } -} \ No newline at end of file diff --git a/beehive-controls/src/main/java/org/apache/beehive/controls/test/util/ControlContainerContextManagerFactory.java b/beehive-controls/src/main/java/org/apache/beehive/controls/test/util/ControlContainerContextManagerFactory.java deleted file mode 100644 index a66d8f5..0000000 --- a/beehive-controls/src/main/java/org/apache/beehive/controls/test/util/ControlContainerContextManagerFactory.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - 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. - - $Header:$ -*/ -package org.apache.beehive.controls.test.util; - -import org.apache.beehive.controls.api.context.ControlContainerContext; -import org.apache.beehive.controls.test.container.ControlTestContainerContext; - -/** - */ -public final class ControlContainerContextManagerFactory { - - public static ControlContainerContextManager getInstance(ControlContainerContext controlContainerContext) { - return new ControlContainerContextManager(controlContainerContext); - } -} diff --git a/beehive-controls/src/main/resources/META-INF/services/com.sun.mirror.apt.AnnotationProcessorFactory b/beehive-controls/src/main/resources/META-INF/services/com.sun.mirror.apt.AnnotationProcessorFactory deleted file mode 100644 index abbd3ee..0000000 --- a/beehive-controls/src/main/resources/META-INF/services/com.sun.mirror.apt.AnnotationProcessorFactory +++ /dev/null @@ -1,26 +0,0 @@ -# -# 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. -# -# $Header:$ -# - -# -# This configures APT so the ControlProcessorFactory can be used to process Control annotations -# -org.apache.beehive.controls.runtime.generator.apt.ControlAnnotationProcessorFactory -org.apache.beehive.controls.runtime.generator.apt.ControlClientAnnotationProcessorFactory -org.apache.beehive.controls.runtime.generator.apt.ControlMemberTypeAnnotationProcessorFactory -org.apache.beehive.controls.runtime.generator.apt.ControlSecondaryAnnotationProcessorFactory diff --git a/beehive-controls/src/main/resources/org/apache/beehive/controls/runtime/generator/ClientInitializer.vm b/beehive-controls/src/main/resources/org/apache/beehive/controls/runtime/generator/ClientInitializer.vm deleted file mode 100644 index 01f49cd..0000000 --- a/beehive-controls/src/main/resources/org/apache/beehive/controls/runtime/generator/ClientInitializer.vm +++ /dev/null @@ -1,211 +0,0 @@ -## -## The Velocity code generation template for the ClientInitializer class generated for -## a control client class (a class that uses controls declaratively). -## -## 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. -## -## $Header:$ -## -## The following context variables are used by this template: -## $client - a ControlClient instance -## $init - a ClientInitializer instance that defines the attributes of the intializer -## -## The actual class template apears at the end of this file, and is preceded by a number of -## supporting macros that define elements of the template. -## -## SUPPORTING MACROS -## -## This macro defines any static final Field values needed for field initialization -## -#macro (declareReflectFields) - #foreach ($field in $init.reflectFields) - static final Field $field.reflectField; - #end -#end -## -## This macro initializes the value of any static final Field values for field initialization -## -#macro (initReflectFields) - try - { - #foreach ($field in $init.reflectFields) - $field.reflectField = ${client.className}.class.getDeclaredField("$field.name"); - ${field.reflectField}.setAccessible(true); - #end - } - catch (NoSuchFieldException __bc_nsfe) - { - throw new ExceptionInInitializerError(__bc_nsfe); - } -#end -## -## This macro declares a new event adaptor class that maps events from an EventSet to -## a set of implemented handlers on a control client -## -#macro (declareEventAdaptor $adaptor) - #set ($eventSet = $adaptor.eventSet) - #set ($binding = $adaptor.eventField.typeBindingMap) - public static class $adaptor.className - implements ${eventSet.className}${adaptor.eventSetBinding}, - EventAdaptor, java.io.Serializable - { - private static final long serialVersionUID = 1L; - - $client.className __bc_client; - - public ${adaptor.className}($client.className client) { __bc_client = client; } - - public Object getClient() { return __bc_client; } - - #foreach ($event in $eventSet.events) - public ${event.getReturnType($binding)} ${event.name}(${event.getArgDecl($binding)}) $event.throwsClause - { - #if ($adaptor.hasHandler($event)) - #if ($event.returnType != "void") return #end __bc_client.${adaptor.getHandler($event).name}(${event.argList}); - #elseif ($event.returnType != "void") - return $event.getDefaultReturnValue($binding); - #end - } - #end - - #foreach ($superEvent in $eventSet.superEventSet.events) - public ${superEvent.getReturnType($binding)} ${superEvent.name}(${superEvent.getArgDecl($binding)}) $superEvent.throwsClause - { - #if ($adaptor.hasHandler($superEvent)) - #if ($superEvent.returnType != "void") return #end __bc_client.${adaptor.getHandler($superEvent).name}(${superEvent.argList}); - #elseif ($superEvent.returnType != "void") - return $superEvent.getDefaultReturnValue($binding); - #end - } - #end - } - -#end -## -## This macro declares the generated classes that act as event adaptors between an event -## source (control in this case) and client class event handlers. -## -#macro (declareEventAdaptors) - #foreach ($control in $client.controls) - #foreach ($adaptor in $control.eventAdaptors) - #declareEventAdaptor($adaptor) - #end - #end -#end -## -## This macro initializes any event adaptors for a declared control -## -#macro (initEventAdaptors $control) - #foreach ($adaptor in $control.eventAdaptors) - ${control.localName}.${adaptor.eventSet.addListenerMethod}(new ${adaptor.className}(client)); - #end -#end -## -## -## This macro defines the initialization of a declared control. A check is made first to see -## if an external initializer (like java.beans.XMLDecoder) has already instantiated a configured -## bean into the context. -## -#macro (initControl $client $control) - __bc_id = ${client.getID($control)}; - $control.controlBean.className $control.localName = (cbc == null ? null : ($control.controlBean.className)cbc.getBean(__bc_id)); - if ($control.localName == null) - $control.localName = (${control.controlBean.className}) Controls.instantiate(${control.controlBean.className}.class, getAnnotationMap(cbc, ${control.reflectField}), cbc, __bc_id ); - #initEventAdaptors($control) - - #if ($control.hasVersionRequired()) - enforceVersionRequired( $control.localName, ${control.reflectField}.getAnnotation(VersionRequired.class) ); - #end - - #if ($init.needsReflection($control)) - ${control.reflectField}.set(client, $control.localName); - #else - client.${control.name} = $control.localName; - #end -#end -## -## -## This macro defines the initialization method for all declared control instances. -## -#macro (declareFieldInit) - private static void initializeFields(ControlBeanContext cbc, - $client.className client) - { - try - { - String __bc_id; - #foreach ($control in $client.Controls) - #if ($velocityCount == 1) - // - // Initialize any nested controls used by the client - // - #end - #initControl($client $control) - #end - } - catch (RuntimeException __bc_re) { throw __bc_re; } - catch (Exception __bc_e) - { - __bc_e.printStackTrace(); - throw new ControlException("Initializer failure", __bc_e); - } - } -#end - -## -## THE CONTROL INITIALIZER CLASS TEMPLATE -## -#if (!$init.isRootPackage()) -package $init.package; -#end - -import java.lang.reflect.Field; -import org.apache.beehive.controls.api.ControlException; -import org.apache.beehive.controls.api.bean.Controls; -import org.apache.beehive.controls.api.versioning.VersionRequired; -import org.apache.beehive.controls.api.context.ControlBeanContext; -import org.apache.beehive.controls.runtime.bean.EventAdaptor; -import org.apache.beehive.controls.runtime.bean.AdaptorPersistenceDelegate; - -@SuppressWarnings("all") -public class $init.shortName - extends org.apache.beehive.controls.runtime.bean.ClientInitializer -{ - #if ($init.reflectFields.size() != 0) - #declareReflectFields() - static - { - #initReflectFields() - } - #end - - #if ($client.needsFieldInit()) - #declareEventAdaptors() - - #declareFieldInit() - #end - - public static void initialize(ControlBeanContext cbc, $client.ClassName client) - { - #if ($client.hasSuperClient()) - ${client.superClientName}ClientInitializer.initialize( cbc, client ); - #end - - #if ($client.needsFieldInit()) - initializeFields( cbc, client ); - #end - } -} diff --git a/beehive-controls/src/main/resources/org/apache/beehive/controls/runtime/generator/ControlBean.vm b/beehive-controls/src/main/resources/org/apache/beehive/controls/runtime/generator/ControlBean.vm deleted file mode 100644 index 65d1119..0000000 --- a/beehive-controls/src/main/resources/org/apache/beehive/controls/runtime/generator/ControlBean.vm +++ /dev/null @@ -1,697 +0,0 @@ -## -## The Velocity code generation template for the JavaBean generated from a Control public -## or extension interface. -## -## 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. -## -## $Header:$ -## -## The following context variables are used by this template: -## $bean - a ControlBean instance that defines the attributes of the bean -## $intf - a ControlInterface instance that defines the attributes of the public interface -## -## The actual class template apears at the end of this file, and is preceded by a number of -## supporting macros that define elements of the template. -## -## LOCAL SUPPORTING MACROS -## -## This macro declares the template for defining bean constructors -## -#macro (declareConstructors) - /** - * This is the public constructor for the class. A client-defined control ID may - * be provided. This ID must be unique within the nesting ControlBeanContext. - * @param context The containing ControlBeanContext - * @param id The control identifier (or null to autogenerate a unique value) - * @param props The initialization Properties for the new instance (or null for defaults) - */ - public ${bean.shortName}(ControlBeanContext context, String id, PropertyMap props) - { - this(context, id, props, ${intf.className}.class); - } - - /** - * This is the public null-arg constructor for this ControlBean. If a control id - * is not provided, a unique value will be auto-generated. - */ - public ${bean.shortName}() - { - this(null, null, null); - } - - /** - * This is the protected version that is used by any ControlBean subclass - */ - protected ${bean.shortName}(ControlBeanContext context, String id, PropertyMap props, Class controlClass) - { - super(context, id, props, controlClass); - - #foreach ($eventSet in $intf.eventSets) - #if ($velocityCount == 1) - // - // Register event notifier instances for any EventSets - // - #end - setEventNotifier(${eventSet.className}.class, new ${eventSet.notifierClass}()); - #end - } - -#end -## -## This macro defines the implementation of of the getParameterNames helper method -## -#macro (declareGetParameterNames) - /** - * Returns an array of parameter names for the request method, or null if no parameter - * data is available. - */ - protected String [] getParameterNames(Method m) - { - // Check the local map for operations on this bean type - if (_methodParamMap.containsKey(m)) - { - return _methodParamMap.get(m); - } - - // Delegate up if not found locally - return super.getParameterNames(m); - } -#end -## -## This macro defines the implementation of an operation -## -#macro (declareOperationImpl $operation) - #set ($returnType = $operation.returnType) - /** - * Implements ${intf.className}.${operation.name} - */ - @SuppressWarnings({"unchecked"}) // for __bc_retval cast - public $operation.formalTypes $returnType ${operation.name}($operation.argDecl) $operation.throwsClause - { - Object [] __bc_argArray = new Object[] { $operation.argList }; - Throwable __bc_thrown = null; - #if (!$intf.isExtension()) - $intf.formalClassName __bc_target = ($intf.formalClassName)ensureControl(); - #else - Extensible __bc_target = (Extensible)ensureControl(); - #end - #if ($returnType != "void") - $returnType __bc_retval = ${operation.defaultReturnValue}; - #end - #if ($operation.interceptorServiceNames.size() > 0) - String __bc_pivotedInterceptor = null; - #end - - try - { - #if ($operation.interceptorServiceNames.size() == 0) - preInvoke(${operation.methodField}, __bc_argArray); - #else - preInvoke(${operation.methodField}, __bc_argArray, ${operation.methodField}Interceptors); - #end - - ## - ## There are two basic generation patterns: - ## - standard invoke (declared on a ControlInterface) - ## - extensible invoke (declared on a ControlExtension) - ## - #if ($returnType != "void") - __bc_retval = - #end - #if (!$intf.isExtension()) - __bc_target.${operation.name}($operation.argList) - #else - #if ($returnType != "void") - (#toObject ($returnType)) - #end - __bc_target.invoke(${operation.methodField}, __bc_argArray) - #end - ; - } - #if ($operation.interceptorServiceNames.size() > 0) - catch (org.apache.beehive.controls.spi.svc.InterceptorPivotException __bc_ipe) - { - __bc_pivotedInterceptor = __bc_ipe.getInterceptorName(); - #if ($returnType != "void") - __bc_retval = (#toObject ($returnType))__bc_ipe.getReturnValue(); - #end - } - #end - catch (Throwable __bc_t) - { - // - // All exceptions are caught here, so postInvoke processing has visibility into - // the exception status. Errors, RuntimExceptions, or declared checked exceptions will - // be rethrown. - // - __bc_thrown = __bc_t; - - if (__bc_t instanceof Error) throw (Error)__bc_t; - else if (__bc_t instanceof RuntimeException) throw (RuntimeException)__bc_t; - #foreach ($thrownException in $operation.throwsList) - else if (__bc_t instanceof $thrownException) throw ($thrownException)__bc_t; - #end - - throw new UndeclaredThrowableException(__bc_t); - } - finally - { - #if ($returnType == "void") - Object __bc_rv = null; - #else - Object __bc_rv = __bc_retval; - #end - #if ($operation.interceptorServiceNames.size() == 0) - postInvoke(${operation.methodField}, __bc_argArray, __bc_rv, __bc_thrown); - #else - postInvoke(${operation.methodField}, __bc_argArray, __bc_rv, __bc_thrown, ${operation.methodField}Interceptors, __bc_pivotedInterceptor); - #end - } - #if ($returnType != "void") - return __bc_retval; - #end - } - -#end -## -## This macro defines the property accessor methods for a bean property -## -#macro (declarePropertyAccessors $property) - /** - * A PropertyKey that can be used to access the $property.name property of the - * $property.propertySet.shortName PropertySet - */ - public static final PropertyKey $property.keyName = new PropertyKey(${property.propertySet.className}.class, "$property.name"); - - #if ($property.propertySet.hasSetters()) - public synchronized void ${property.writeMethod}($property.type value) - #if ($property.constrained) - throws java.beans.PropertyVetoException - #end - { - #if ($property.bound || $property.constrained) - // Ensure the control impl exists, since it may want to receive property events - ensureControl(); - - Object __bc_oldValue = getRawControlProperty($property.keyName); - #end - - #if ($property.constrained) - fireVetoableChange($property.keyName, __bc_oldValue, value); - #end - setControlProperty($property.keyName, value); - #if ($property.bound) - firePropertyChange($property.keyName, __bc_oldValue, value); - #end - } - #end - - #if (!$property.propertySet.isOptional()) - public $property.type ${property.readMethod}() - { - return (#toObject($property.type))getControlProperty($property.keyName); - } - #end - -#end -## -## This macro declares the registration methods supporting a PropertyChangeListener -## -#macro (declareBoundPropertySupport) - /** - * Adds a new PropertyChangeListener for listening to changes on bound properties of this - * control. - */ - public void addPropertyChangeListener(PropertyChangeListener pcl) - { - getPropertyChangeSupport().addPropertyChangeListener(pcl); - } - - /** - * Adds a new PropertyChangeListener for listening to changes to a specific bound - * property of this control. - */ - public void addPropertyChangeListener(String propertyName, PropertyChangeListener pcl) - { - getPropertyChangeSupport().addPropertyChangeListener(propertyName, pcl); - } - - /** - * Removes a registered PropertyChangeListener listening to changes on bound properties of - * this control. - */ - public void removePropertyChangeListener(PropertyChangeListener pcl) - { - getPropertyChangeSupport().removePropertyChangeListener(pcl); - } - - /** - * Removes a registered PropertyChangeListener listening to changes on a specific bound - * property of this control. - */ - public void removePropertyChangeListener(String propertyName, PropertyChangeListener pcl) - { - getPropertyChangeSupport().removePropertyChangeListener(propertyName, pcl); - } -#end -## -## This macro declares the registration methods supporting a VetoableChangeListener -## -#macro (declareConstrainedPropertySupport) - /** - * Adds a new PropertyChangeListener for listening to changes on bound properties of this - * control. - */ - public void addVetoableChangeListener(VetoableChangeListener vcl) - { - getVetoableChangeSupport().addVetoableChangeListener(vcl); - } - - /** - * Adds a new PropertyChangeListener for listening to changes to a specific constrained - * property of this control. - */ - public void addVetoableChangeListener(String propertyName, VetoableChangeListener vcl) - { - getVetoableChangeSupport().addVetoableChangeListener(propertyName, vcl); - } - - /** - * Removes a registered PropertyChangeListener listening to changes on constrained properties - * of this control. - */ - public void removeVetoableChangeListener(VetoableChangeListener vcl) - { - getVetoableChangeSupport().removeVetoableChangeListener(vcl); - } - - /** - * Removes a registered PropertyChangeListener listening to changes to a specific constrained - * property of this control. - */ - public void removeVetoableChangeListener(String propertyName, VetoableChangeListener vcl) - { - getVetoableChangeSupport().removeVetoableChangeListener(propertyName, vcl); - } -#end -## -## This macro defines the implementation of an event routing method -## -#macro (declareEventImpl $event) - #set ($returnType = $event.returnType) - public $returnType ${event.name}($event.argDecl) $event.throwsClause - { - Throwable __bc_thrown = null; - #if ($returnType != "void") - $returnType __bc_retval = ${event.defaultReturnValue}; - #end - - $eventSet.notifierClass __bc_notifier = ($eventSet.notifierClass)getEventNotifier(${eventSet.className}.class); - - #if ($event.eventSet.unicast) - $event.eventSet.formalClassName __bc_listener = ($event.eventSet.formalClassName)__bc_notifier.getListener(); - - // - // If an event listener has been registered, then deliver the event - // - if (__bc_listener != null) - { - Object [] __bc_argArray = new Object[] {$event.argList}; - #if ($event.interceptorServiceNames.size() != 0) - String __bc_pivotedInterceptor = null; - #end - try - { - #if ($event.interceptorServiceNames.size() != 0) - preEvent($event.methodField, __bc_argArray, ${event.methodField}Interceptors); - #end - #if ($returnType != "void") - __bc_retval = __bc_listener.${event.name}($event.argList); - #else - __bc_listener.${event.name}($event.argList); - #end - } - #if ($event.interceptorServiceNames.size() != 0) - catch (org.apache.beehive.controls.spi.svc.InterceptorPivotException __bc_ipe) - { - __bc_pivotedInterceptor = __bc_ipe.getInterceptorName(); - #if ($returnType != "void") - __bc_retval = (#toObject ($returnType))__bc_ipe.getReturnValue(); - #end - } - #end - catch (Throwable __bc_t) - { - // - // All exceptions are caught here, so postEvent processing has visibility into - // the exception status. Errors, RuntimExceptions, or declared checked exceptions will - // be rethrown. - // - __bc_thrown = __bc_t; - - if (__bc_t instanceof Error) throw (Error)__bc_t; - else if (__bc_t instanceof RuntimeException) throw (RuntimeException)__bc_t; - #foreach ($thrownException in $event.throwsList) - else if (__bc_t instanceof $thrownException) throw ($thrownException)__bc_t; - #end - - throw new UndeclaredThrowableException(__bc_t); - } - #if ($event.interceptorServiceNames.size() != 0) - finally - { - #if ($returnType == "void") - Object __bc_rv = null; - #else - Object __bc_rv = __bc_retval; - #end - postEvent($event.methodField, __bc_argArray, __bc_rv, __bc_thrown, ${event.methodField}Interceptors, __bc_pivotedInterceptor); - } - #end - } - #if ($returnType != "void") - return __bc_retval; - #end - #else - Object [] __bc_argArray = new Object[] {$event.argList}; - - #if ($event.interceptorServiceNames.size() != 0) - String __bc_pivotedInterceptor = null; - #end - java.util.Iterator __bc_listenerIter = __bc_notifier.listenerIterator(); - - try - { - #if ($event.interceptorServiceNames.size() != 0) - preEvent($event.methodField, __bc_argArray, ${event.methodField}Interceptors); - #end - while (__bc_listenerIter.hasNext()) - { - $event.eventSet.formalClassName __bc_listener = ($eventSet.formalClassName)__bc_listenerIter.next(); - __bc_listener.${event.name}($event.argList); - } - } - #if ($event.interceptorServiceNames.size() != 0) - catch (org.apache.beehive.controls.spi.svc.InterceptorPivotException __bc_ipe) - { - __bc_pivotedInterceptor = __bc_ipe.getInterceptorName(); - } - #end - catch (Throwable __bc_t) - { - // - // All exceptions are caught here, so postEvent processing has visibility into - // the exception status. Errors, RuntimExceptions, or declared checked exceptions will - // be rethrown. - // - __bc_thrown = __bc_t; - - if (__bc_t instanceof Error) throw (Error)__bc_t; - else if (__bc_t instanceof RuntimeException) throw (RuntimeException)__bc_t; - #foreach ($thrownException in $event.throwsList) - else if (__bc_t instanceof $thrownException) throw ($thrownException)__bc_t; - #end - - throw new UndeclaredThrowableException(__bc_t); - } - #if ($event.interceptorServiceNames.size() != 0) - finally - { - postEvent($event.methodField, __bc_argArray, null, __bc_thrown, ${event.methodField}Interceptors, __bc_pivotedInterceptor); - } - #end - #end - } - -#end -## -## This macro defines the implementation of a preEvent method -## -#macro (declarePreEvent $eventSet) - private void preEvent(Method method, Object[] argArray, String[] interceptors) - throws org.apache.beehive.controls.spi.svc.InterceptorPivotException - { - for ( String __bc_n : interceptors ) - { - org.apache.beehive.controls.spi.svc.Interceptor __bc_i = ensureInterceptor( __bc_n ); - try - { - __bc_i.preEvent( ${bean.shortName}.this, ${eventSet.formalClassName}.class , method, argArray ); - } - catch (org.apache.beehive.controls.spi.svc.InterceptorPivotException __bc_ipe) - { - __bc_ipe.setInterceptorName(__bc_n); - throw __bc_ipe; - } - } - } -#end -## -## This macro defines the implementation of a postEvent method -## -#macro (declarePostEvent $eventSet) - private void postEvent(Method method, Object[] argArray, Object retval, Throwable t, String[] interceptors, String pivotedInterceptor) - { - for (int __bc_cnt = interceptors.length - 1; __bc_cnt >= 0; __bc_cnt--) - { - String __bc_n = interceptors[__bc_cnt]; - if (pivotedInterceptor == null || __bc_n.equals(pivotedInterceptor)) - { - pivotedInterceptor = null; - org.apache.beehive.controls.spi.svc.Interceptor __bc_i = ensureInterceptor( __bc_n ); - __bc_i.postEvent( ${bean.shortName}.this, ${eventSet.formalClassName}.class , method, argArray, retval, t ); - } - } - } -#end -## -## This macro defines an EventSet proxy implementation for routing events -## -#macro (declareEventSetImpl $eventSet) - /** - * This inner class implements a simple proxy to deliver $eventSet.shortName events - * back to a register listener. - */ - protected class $eventSet.notifierClass - #if ($eventSet.extendsNotifierBase) - extends $eventSet.notifierExtends - #else - extends ${bean.superClass.className}.${eventSet.notifierExtendsShortName} - #end - implements ${eventSet.formalClassName}, java.io.Serializable - { - private static final long serialVersionUID = 1L; - - #set ( $interceptor = false ) - #foreach ($event in $eventSet.events) - #declareEventImpl($event) - #if ($event.interceptorServiceNames.size() != 0) - #set ( $interceptor = true ) - #end - #end - #if ( $interceptor ) - #declarePreEvent ($eventSet) - #declarePostEvent ($eventSet) - #end - } - -#end -## -## This macros defines the EventSet listener registration methods -## -#macro (declaredListenerMethods $eventSet) - /** - * Registers a new listener for ${eventSet.shortName} events on the bean. - */ - public synchronized void ${eventSet.addListenerMethod}($eventSet.formalClassName listener) - #if ($eventSet.unicast) - throws java.util.TooManyListenersException - #end - { - $eventSet.notifierClass __bc_notifier = ($eventSet.notifierClass)getEventNotifier(${eventSet.className}.class); - __bc_notifier.addListener(listener); - } - - /** - * Unregisters an existing listener for ${eventSet.shortName} events on the bean. - */ - public synchronized void ${eventSet.removeListenerMethod}($eventSet.formalClassName listener) - { - $eventSet.notifierClass __bc_notifier = ($eventSet.notifierClass)getEventNotifier(${eventSet.className}.class); - __bc_notifier.removeListener(listener); - } - - /** - * Returns the array of registered listeners for ${eventSet.shortName} events on the bean, or - * an empty array if no listener has been registered - */ - public synchronized $eventSet.formalClassName [] ${eventSet.getListenersMethod}() - { - $eventSet.notifierClass __bc_notifier = ($eventSet.notifierClass)getEventNotifier(${eventSet.className}.class); - $eventSet.formalClassName [] __bc_listeners = new ${eventSet.className}[__bc_notifier.getListenerCount()]; - __bc_notifier.getListeners(__bc_listeners); - return __bc_listeners; - } -#end -## -## This macro declares the local (bean class) cache that is used for shared PropertyMaps -## -#macro (declarePropertyCache) - /** - * The _annotCache maintains a lookup cache from AnnotatedElements to an associated - * PropertyMap. This enables these maps to be shared across multiple beans. - */ - static private HashMap __bc_annotCache = new HashMap(); - - protected Map getPropertyMapCache() { return __bc_annotCache; } -#end -## -## This macro enforces the VersionRequired annotation semantics -## -#macro (enforceVersionRequired) - /* - * Enforce VersionRequired - */ - Class __bc_controlIntf = null; - - #if ($intf.getMostDerivedInterface()) - __bc_controlIntf = ${intf.getMostDerivedInterface().className}.class; - #end - - Version __bc_versionPresent = (Version)__bc_controlIntf.getAnnotation(Version.class); - VersionRequired __bc_versionRequired = (${bean.shortName}.class).getAnnotation(VersionRequired.class); - - org.apache.beehive.controls.runtime.bean.ControlBean.enforceVersionRequired("${intf.className}", __bc_versionPresent, __bc_versionRequired); -#end -## -## This macro declares the interceptor arrays for operations and eventsets -## -#macro (declareMethodInterceptors) - #foreach ($operation in $intf.operations) - #if ($operation.interceptorServiceNames.size() != 0) - private static String[] ${operation.methodField}Interceptors = ${operation.interceptorDecl}; - #end - #end - - #foreach ($eventSet in $intf.eventSets) - #foreach ($event in $eventSet.events) - #if ($event.interceptorServiceNames.size() != 0) - private static String[] ${event.methodField}Interceptors = ${event.interceptorDecl}; - #end - #end - #end -#end - -## -## This macro declares the code that prioritizes interceptor arrays for operations -## -#macro (prioritizeInterceptors) - #foreach ($operation in $intf.operations) - #if ($operation.interceptorServiceNames.size() != 0) - ${operation.methodField}Interceptors = org.apache.beehive.controls.runtime.bean.InterceptorUtils.prioritizeInterceptors( ${operation.methodField}Interceptors ); - #end - #end - #foreach ($eventSet in $intf.eventSets) - #foreach ($event in $eventSet.events) - #if ($event.interceptorServiceNames.size() != 0) - ${event.methodField}Interceptors = org.apache.beehive.controls.runtime.bean.InterceptorUtils.prioritizeInterceptors(${event.methodField}Interceptors); - #end - #end - #end - -#end -## -## THE CONTROLBEAN CLASS TEMPLATE -## -#if (!$bean.isRootPackage()) -package $bean.package; -#end - -import java.beans.*; - -import java.lang.reflect.Method; -import java.lang.reflect.UndeclaredThrowableException; -import java.util.HashMap; -import java.util.Map; - -import org.apache.beehive.controls.api.bean.*; -import org.apache.beehive.controls.api.context.ControlBeanContext; -import org.apache.beehive.controls.api.properties.PropertyKey; -import org.apache.beehive.controls.api.properties.PropertyMap; -import org.apache.beehive.controls.api.versioning.*; - -@SuppressWarnings("all") -public class ${bean.classDeclaration} - extends ${bean.superClass.className}${bean.superTypeBinding} - implements ${intf.formalClassName} -{ - #if ($intf.operations.size() != 0 || $intf.localEventSetCount != 0) - #declareMethodStatics() - - static - { - #initMethodStatics() - } - - #declareMethodInterceptors() - - static - { - #prioritizeInterceptors() - } - - #end - - #if ($intf.getVersionRequired()) - static - { - #enforceVersionRequired() - } - #end - - #declareConstructors() - - #if ($intf.operations.size() != 0) - #declareGetParameterNames() - - #foreach ($operation in $intf.operations) - #declareOperationImpl ($operation) - #end - #end - - #foreach ($propertySet in $intf.propertySets) - #foreach ($property in $propertySet.properties) - #declarePropertyAccessors ($property) - #end - #end - - #if ($intf.addsBoundPropertySupport()) - #declareBoundPropertySupport() - #end - - #if ($intf.addsConstrainedPropertySupport()) - #declareConstrainedPropertySupport() - #end - - #foreach ($eventSet in $intf.eventSets) - #declareEventSetImpl ($eventSet) - #declaredListenerMethods($eventSet) - #end - - #declarePropertyCache() - - private static final long serialVersionUID = 1L; -} diff --git a/beehive-controls/src/main/resources/org/apache/beehive/controls/runtime/generator/ControlBeanInfo.vm b/beehive-controls/src/main/resources/org/apache/beehive/controls/runtime/generator/ControlBeanInfo.vm deleted file mode 100644 index ab044a9..0000000 --- a/beehive-controls/src/main/resources/org/apache/beehive/controls/runtime/generator/ControlBeanInfo.vm +++ /dev/null @@ -1,400 +0,0 @@ -## -## The Velocity code generation template for the JavaBean BeanInfo generated from a Control public -## or extension interface. -## -## 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. -## -## $Header:$ -## -## The following context variables are used by this template: -## $bean - a ControlBean instance that defines the attributes of the bean -## $intf - a ControlInterface instance that defines the attributes of the public interface -## -## The initFeatureDescriptor macro will initialize the contents of a FeatureDescriptor using -## a FeatureInfo annotation instance. -## -## The localizeString is used to inject code to do resource bundle lookup on string values that -## begin/end with '%'. See org.apache.beehive.controls.runtime.ControlBeanInfo.localizeString() -## for details -## -#macro (localizeString $string) -#if ($string.startsWith('%') && $string.endsWith('%')) localizeString("$string") #else "$string" #end -#end -#macro (initFeatureDescriptor $featureDesc $featureInfo $defaultName) -#if (! $featureInfo.name().equals("")) -${featureDesc}.setName(#localizeString("$featureInfo.name()")); -#else -${featureDesc}.setName("$defaultName"); -#end -#if (! $featureInfo.displayName().equals("")) -${featureDesc}.setDisplayName(#localizeString("$featureInfo.displayName()")); -#else -${featureDesc}.setDisplayName("$defaultName"); -#end -${featureDesc}.setShortDescription(#localizeString("$featureInfo.shortDescription()")); -${featureDesc}.setExpert($featureInfo.isExpert()); -${featureDesc}.setHidden($featureInfo.isHidden()); -${featureDesc}.setPreferred($featureInfo.isPreferred()); -## -## Reading arrays of annotation type instances is broken under JDK1.5.0b51 -## -###foreach ($featureAttr in $featureInfo.attributes()) -##${featureDesc}.setValue("$featureAttr.name()","$featureAttr.value()"); -###end -#end -## -## Begin - Main body for ControlBeanInfo class template -## -#if (!$bean.isRootPackage()) -package $bean.package; -#end - -import java.beans.BeanDescriptor; -import java.beans.EventSetDescriptor; -import java.beans.IntrospectionException; -import java.beans.MethodDescriptor; -import java.beans.ParameterDescriptor; -import java.beans.PropertyDescriptor; -import java.beans.PropertyEditor; -import java.lang.reflect.Method; -import java.util.HashMap; - -import org.apache.beehive.controls.api.ControlException; -import org.apache.beehive.controls.runtime.bean.BeanPersistenceDelegate; -import org.apache.beehive.controls.runtime.packaging.ControlEventSetDescriptor; - -@SuppressWarnings("all") -public class ${bean.shortName}BeanInfo -#if ($intf.superClass) - extends ${bean.superClass.className}BeanInfo -#else - extends org.apache.beehive.controls.runtime.bean.ControlBeanInfo -#end -{ - #if ($intf.operations.size() != 0 || $intf.eventSets.size() != 0) - #declareMethodStatics() - - static - { - #initMethodStatics() - } - #end - - /** - * Default null-arg constructor used to create a new BeanInfo instance - */ - public ${bean.shortName}BeanInfo() - { - super(${bean.className}.class); - } - - /** - * Protected constructor used if this BeanInfo class is extended. - */ - protected ${bean.shortName}BeanInfo(Class beanClass) - { - super(beanClass); - } - - // java.beans.BeanInfo.getBeanDescriptor - public BeanDescriptor getBeanDescriptor() - { - BeanDescriptor bd = new BeanDescriptor(${bean.className}.class); - #if ($intf.featureInfo) - #initFeatureDescriptor("bd" $intf.featureInfo $bean.shortName) - #else - bd.setName(#localizeString("$bean.shortName")); - bd.setDisplayName(#localizeString("$bean.shortName")); - #end - - // - // The org.apache.beehive.controls.runtime.bean.BeanPersistenceDelegate class - // implements the XMLDecode delegation model for all Control JavaBean types. It - // provides optimized XML persistance based upon the Control runtime architecture. - // The 'persistenceDelegate' attribute of a BeanDescriptor is used by XMLEncoder to - // locate a delegate for a particular JavaBean type. - // - bd.setValue("persistenceDelegate", new BeanPersistenceDelegate()); - - return bd; - } - - /** - * Stores MethodDescriptor descriptors for this bean and its superclasses into - * an array, starting at the specified index - */ - protected void initMethodDescriptors(MethodDescriptor [] methodDescriptors, int index) - throws java.beans.IntrospectionException - { - #if ($intf.operations.size() > 0) - String [] __bc_paramNames; - ParameterDescriptor [] __bc_paramDescriptors; - MethodDescriptor md; - #end - - #foreach ($operation in $intf.operations) - // - // Declare MethodDescriptor for ${operation.name}(${operation.argList}) - // - __bc_paramNames = _methodParamMap.get($operation.methodField); - __bc_paramDescriptors = new ParameterDescriptor[__bc_paramNames.length]; - for (int j = 0; j < __bc_paramNames.length; j++) - { - __bc_paramDescriptors[j] = new ParameterDescriptor(); - __bc_paramDescriptors[j].setName(__bc_paramNames[j]); - __bc_paramDescriptors[j].setDisplayName(__bc_paramNames[j]); - } - md = new MethodDescriptor($operation.methodField, __bc_paramDescriptors); - #if ($operation.featureInfo) - #initFeatureDescriptor("md" $operation.featureInfo $operation.name) - #end - methodDescriptors[index++] = md; - - #end - - #if ($intf.superClass) - // - // Add method descriptors from parent BeanInfo - // - super.initMethodDescriptors(methodDescriptors, index); - #end - } - - public MethodDescriptor [] getMethodDescriptors() - { - MethodDescriptor [] __bc_methodDescriptors = new MethodDescriptor[$intf.operationCount]; - try - { - initMethodDescriptors(__bc_methodDescriptors, 0); - } - catch (java.beans.IntrospectionException __bc_ie) - { - throw new ControlException("Unable to create MethodDescriptor", __bc_ie); - } - return __bc_methodDescriptors; - } - - /** - * Stores PropertyDescriptor descriptors for this bean and its superclasses into - * an array, starting at the specified index - */ - protected void initPropertyDescriptors(PropertyDescriptor [] propDescriptors, int index) - throws java.beans.IntrospectionException - { - PropertyDescriptor pd; - - #foreach ($propertySet in $intf.propertySets) - #foreach ($property in $propertySet.properties) - #if ($property.getType().equals("boolean")) - #set ( $getterName = "is${property.accessorName}" ) - #else - #set ( $getterName = "get${property.accessorName}" ) - #end - #if ($propertySet.hasSetters()) - #set ( $setterName = "set${property.accessorName}" ) - #if ($propertySet.isOptional()) - pd = new PropertyDescriptor(#localizeString("$property.name"), ${bean.className}.class, null, "$setterName"); - #else - pd = new PropertyDescriptor(#localizeString("$property.name"), ${bean.className}.class, "$getterName", "$setterName"); - #end - #else - #if (! $propertySet.isOptional()) - pd = new PropertyDescriptor(#localizeString("$property.name"), ${bean.className}.class, "$getterName", null ); - #end - #end - #if ($propertySet.hasSetters() || !$propertySet.isOptional()) - #if ($property.propertyInfo) - pd.setBound($property.propertyInfo.bound()); - pd.setConstrained($property.propertyInfo.constrained()); - #if ($property.editorClass) - pd.setPropertyEditorClass(${property.editorClass}.class); - #end - #end - #if ($property.featureInfo) - #initFeatureDescriptor("pd" $property.featureInfo $property.name) - #end - propDescriptors[index++] = pd; - #end - #end - #end - - #if ($intf.interfaceProperties.size() > 0) - // - // add property descriptors for any getter/setters defined in control interface - // - #end - #foreach ($intfprop in $intf.interfaceProperties) - #if ($intfprop.getterName && $intfprop.setterName) - pd = new PropertyDescriptor(#localizeString("$intfprop.name"), ${bean.className}.class, "$intfprop.getterName", "$intfprop.setterName"); - propDescriptors[index++] = pd; - #elseif ($intfprop.getterName) - pd = new PropertyDescriptor(#localizeString("$intfprop.name"), ${bean.className}.class, "$intfprop.getterName", null); - propDescriptors[index++] = pd; - #elseif ($intfprop.setterName) - pd = new PropertyDescriptor(#localizeString("$intfprop.name"), ${bean.className}.class, null, "$intfprop.setterName"); - propDescriptors[index++] = pd; - #end - #end - - #if ($intf.superClass) - // - // Add property descriptors from parent BeanInfo - // - super.initPropertyDescriptors(propDescriptors, index); - #end - } - - // java.beans.BeanInfo.getPropertyDescriptors - public PropertyDescriptor [] getPropertyDescriptors() - { - PropertyDescriptor [] __bc_propDescriptors = new PropertyDescriptor[$intf.propertyCount]; - try - { - initPropertyDescriptors(__bc_propDescriptors, 0); - } - catch (java.beans.IntrospectionException __bc_ie) - { - throw new ControlException("Unable to create PropertyDescriptor", __bc_ie); - } - return __bc_propDescriptors; - } - - #foreach ($eventSet in $intf.eventSets) - // - // Adds the EventDescriptors for $eventSet.shortName to the EventDescriptor array, starting - // at index - // - protected void ${eventSet.infoInitializer}(MethodDescriptor [] eventDescriptors, int index) - { - String [] __bc_paramNames; - ParameterDescriptor [] __bc_paramDescriptors; - MethodDescriptor md; - - // - // Build a method descriptor for each event method in the event set - // - #foreach ($event in $eventSet.events) - - // - // Declare MethodDescriptor for ${event.name}(${event.argList}) - // - __bc_paramNames = _methodParamMap.get($event.methodField); - __bc_paramDescriptors = new ParameterDescriptor[__bc_paramNames.length]; - for (int k = 0; k < __bc_paramNames.length; k++) - { - __bc_paramDescriptors[k] = new ParameterDescriptor(); - __bc_paramDescriptors[k].setName(__bc_paramNames[k]); - __bc_paramDescriptors[k].setDisplayName(__bc_paramNames[k]); - } - md = new MethodDescriptor($event.methodField, __bc_paramDescriptors); - #if ($event.featureInfo) - #initFeatureDescriptor("md" $event.featureInfo $event.name) - #end - eventDescriptors[index++] = md; - #end - - #if ($eventSet.superEventSet) - // - // Add events from the parent EventSet - // - ${eventSet.superEventSet.infoInitializer}(eventDescriptors, index); - #end - } - - #end - - protected void initEventSetDescriptors(EventSetDescriptor [] eventSetDescriptors, int index) - throws java.beans.IntrospectionException - { - #if ($intf.eventSets.size() > 0) - MethodDescriptor [] __bc_eventDescriptors; - EventSetDescriptor __bc_esd; - Method __bc_addListener, __bc_removeListener, __bc_getListeners; - Class __bc_eventIntf; - #end - - #foreach ($eventSet in $intf.eventSets) - __bc_eventIntf = ${eventSet.className}.class; - - // - // Find the add/remove listener methods - // - try - { - __bc_addListener = - ${bean.className}.class.getDeclaredMethod("$eventSet.addListenerMethod", - new Class [] { __bc_eventIntf }); - __bc_removeListener = - ${bean.className}.class.getDeclaredMethod("$eventSet.removeListenerMethod", - new Class [] { __bc_eventIntf }); - __bc_getListeners = - ${bean.className}.class.getDeclaredMethod("$eventSet.getListenersMethod", - new Class [] {}); - } - catch (NoSuchMethodException __bc_nsme) - { - // This is moderately lame, but there is no checked exception declared for this - // method. This could only happen as a result of a mismatch between bean class - // and introspector codegen. - throw new ControlException("Unable to locate listener method", __bc_nsme); - } - - // - // Build the MethodDescriptor array contain all event set events - // - __bc_eventDescriptors = new MethodDescriptor[$eventSet.eventCount]; - ${eventSet.infoInitializer}(__bc_eventDescriptors, 0); - - try - { - __bc_esd = new ControlEventSetDescriptor(localizeString("$eventSet.descriptorName"), - __bc_eventIntf, __bc_eventDescriptors, __bc_addListener, __bc_removeListener, __bc_getListeners); - #if ($eventSet.featureInfo) - #initFeatureDescriptor("esd" $eventSet.featureInfo $eventSet.descriptorName) - #end - __bc_esd.setUnicast($eventSet.unicast); - } - catch (IntrospectionException __bc_ie) - { - throw new ControlException("Unable to create EventDescriptor", __bc_ie); - } - eventSetDescriptors[index++] = __bc_esd; - - #end - - #if ($intf.superClass) - // - // Add event set descriptors from parent BeanInfo - // - super.initEventSetDescriptors(eventSetDescriptors, index); - #end - } - - // java.beans.BeanInfo.getEventSetDescriptors - public EventSetDescriptor [] getEventSetDescriptors() - { - EventSetDescriptor [] __bc_eventSetDescriptors = new EventSetDescriptor[$intf.eventSetCount]; - try - { - initEventSetDescriptors(__bc_eventSetDescriptors, 0); - } - catch (java.beans.IntrospectionException __bc_ie) - { - throw new ControlException("Unable to create EventSetDescriptor", __bc_ie); - } - return __bc_eventSetDescriptors; - } -} diff --git a/beehive-controls/src/main/resources/org/apache/beehive/controls/runtime/generator/ControlMacros.vm b/beehive-controls/src/main/resources/org/apache/beehive/controls/runtime/generator/ControlMacros.vm deleted file mode 100644 index 6881a50..0000000 --- a/beehive-controls/src/main/resources/org/apache/beehive/controls/runtime/generator/ControlMacros.vm +++ /dev/null @@ -1,93 +0,0 @@ -## -## The Velocity code generation template file containing various method macro utilities -## -## 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. -## -## $Header:$ -## -## The following context variables are used by this template: -## $bean - a ControlBean instance that defines the attributes of the bean -## $intf - a ControlInterface instance that defines the attributes of the public interface -## -## The actual class template apears at the end of this file, and is preceded by a number of -## supporting macros that define elements of the template. -## -## SUPPORTING MACROS -## -## A simple helper macro that converts a primitive type to the equivalent object -## -#macro (toObject $type)#if ($type == "int")Integer#elseif ($type == "long")Long#elseif ($type == "boolean")Boolean#elseif ($type == "byte")Byte#elseif ($type == "short")Short#elseif ($type == "char")Character#elseif ($type == "float")Float#elseif ($type == "double")Double#else${type}#end#end -## -## A simple helper macro that converts a object type to the equivalent primitive -## -## This macro provides the template for declaring the static final Method fields that -## are associated with all declared operations -## -#macro (declareMethodStatics) - #foreach ($operation in $intf.operations) - static final Method $operation.methodField; - #end - #foreach ($eventSet in $intf.eventSets) - #foreach ($event in $eventSet.events) - static final Method $event.methodField; - #end - #end - - // - // This HashMap will map from a Method to the array of names for parameters of the - // method. This is necessary because parameter name data isn't carried along in the - // class file, but if available can enable ease of use by referencing parameters by - // the declared name (vs. by index). - // - // This map should be read-only after its initialization in the static block, hence - // using a plain HashMap is thread-safe. - // - static HashMap _methodParamMap = new HashMap(); -#end -## -## This macros provides the template for initializing the static final Method fields that -## are associated with declared operations -## -#macro (initMethodStatics) - - ## First verify that if an eventSet was defined it is not empty. - #set($eCount=0) - #foreach($eventSet in $intf.eventSets) - #foreach($event in $eventSet.events) - #set($eCount=$eCount+1) - #end - #end - - #if ($intf.operations.size() > 0 || $eCount > 0) - try - { - #foreach ($operation in $intf.operations) - $operation.methodField = ${intf.className}.class.getMethod("${operation.name}", new Class [] {$operation.argTypes}); - _methodParamMap.put($operation.methodField, new String [] { $operation.getArgList(true) }); - #end - #foreach ($eventSet in $intf.eventSets) - #foreach ($event in $eventSet.events) - $event.methodField = ${eventSet.className}.class.getMethod("${event.name}", new Class [] {$event.argTypes}); - _methodParamMap.put($event.methodField, new String [] { $event.getArgList(true) }); - #end - #end - } - catch (NoSuchMethodException __bc_nsme) - { - throw new ExceptionInInitializerError(__bc_nsme); - } - #end -#end diff --git a/beehive-controls/src/main/resources/org/apache/beehive/controls/runtime/generator/ControlManifest.vm b/beehive-controls/src/main/resources/org/apache/beehive/controls/runtime/generator/ControlManifest.vm deleted file mode 100644 index 5e830c2..0000000 --- a/beehive-controls/src/main/resources/org/apache/beehive/controls/runtime/generator/ControlManifest.vm +++ /dev/null @@ -1,42 +0,0 @@ -## -## The Velocity code generation template for the JAR manifest file (META-INF/MANIFEST.MF) -## entries associated with a control bean and its public interface or extension class. -## -## 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. -## -## $Header:$ -## -## The following context variables are used by this template: -## $bean - a ControlBean instance that defines the attributes of the bean -## $intf - a ControlInterface instance that defines the attributes of the public interface -## -## -## THE CONTROL BEAN MANIFEST.MF TEMPLATE -## -## This template defines the JAR manifest contents that will be injected into any JAR file -## containing Beehive controls. The template is used to generate per-control manifest files, -## which are then merged by the org.apache.beehive.controls.runtime.packaging.ControlJarTask -## ant task into a single JAR manifest file. -## -Manifest-Version: 1.0 - -Name: $bean.manifestName -Java-Bean: true -Beehive-Control: true -#set ($attrs = $intf.manifestAttributes) -#foreach ($name in $attrs.keySet()) -${name}: ${attrs.get($name)} -#end diff --git a/beehive-controls/src/main/resources/org/apache/beehive/controls/runtime/generator/ImplInitializer.vm b/beehive-controls/src/main/resources/org/apache/beehive/controls/runtime/generator/ImplInitializer.vm deleted file mode 100644 index 86f2f3b..0000000 --- a/beehive-controls/src/main/resources/org/apache/beehive/controls/runtime/generator/ImplInitializer.vm +++ /dev/null @@ -1,281 +0,0 @@ -## -## The Velocity code generation template for the Initializer class generated from a Control -## implementation class -## -## 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. -## -## $Header:$ -## -## The following context variables are used by this template: -## $init - a ImplInitializer instance that defines the attributes of the intializer -## -## The actual class template apears at the end of this file, and is preceded by a number of -## supporting macros that define elements of the template. -## -## SUPPORTING MACROS -## -## -## This macro defines any static final Field values needed for field initialization -## -#macro (declareReflectFields) - #foreach ($field in $init.reflectFields) - static final Field $field.reflectField; - #end -#end -## -## This macro initializes the value of any static final Field values for field initialization -## -#macro (initReflectFields) - try - { - #foreach ($field in $init.reflectFields) - $field.reflectField = ${impl.className}.class.getDeclaredField("$field.name"); - ${field.reflectField}.setAccessible(true); - #end - } - catch (NoSuchFieldException __bc_nsfe) - { - throw new ExceptionInInitializerError(__bc_nsfe); - } -#end -## -## This macro declares a new event adaptor class that maps events from an EventSet to -## a set of implemented handlers on a control implementation -## -#macro (declareEventAdaptor $adaptor) - #set ($eventSet = $adaptor.eventSet) - protected static class $adaptor.className implements $eventSet.className, java.io.Serializable - { - private static final long serialVersionUID = 1L; - - $impl.className __bc_impl; - - ${adaptor.className}($impl.className impl) { __bc_impl = impl; } - - #foreach ($event in $eventSet.events) - public ${event.returnType} ${event.name}(${event.argDecl}) $event.throwsClause - { - #if ($adaptor.hasHandler($event)) - #if ($event.returnType != "void") return #end __bc_impl.${adaptor.getHandler($event).name}(${event.argList}); - #elseif ($event.returnType != "void") - return $event.defaultReturnValue; - #end - } - #end - } - -#end -## -## This macros declares any generated class that act as event adaptors between an event -## source (control or context) and implementation class event handlers. -## -#macro (declareEventAdaptors) - #foreach ($context in $impl.contexts) - #foreach ($adaptor in $context.eventAdaptors) - #declareEventAdaptor($adaptor) - #end - #end -#end -## -## This macro initializes any event adaptors for a nested control -## -#macro (initEventAdaptors $control) - #foreach ($adaptor in $control.eventAdaptors) - ${control.localName}.${adaptor.eventSet.addListenerMethod}(new ${adaptor.className}(__bc_impl)); - #end -#end -## -## This macro defines the initialization of a contextual service -## -#macro (initContext $context) - #if ($context.getType().equals("org.apache.beehive.controls.api.context.ControlBeanContext")) - $context.type $context.localName = __bc_beanContext; - #else - $context.type $context.localName = ($context.type)__bc_beanContext.getService(${context.type}.class, null); - #end - if ($context.localName == null) - throw new ControlException("Contextual service $context.type is not available"); - #initEventAdaptors($context) - #if ($init.needsReflection($context)) - ${context.reflectField}.set(__bc_impl, $context.localName); - #else - __bc_impl.$context.name = $context.localName; - #end -#end -## -## This macro defines the initialization of a contextual service -## -#macro (resetContext $context) - #if ($init.needsReflection($context)) - ${context.reflectField}.set(__bc_impl, null); - #else - __bc_impl.$context.name = null; - #end -#end -## -## This macro defines the initialization of a event notification proxy -## -#macro (initEventProxy $proxy) - $proxy.className $proxy.localName = ($proxy.className)getEventNotifier(bean, ${proxy.className}.class); - #if ($init.needsReflection($proxy)) - ${proxy.reflectField}.set(__bc_impl, $proxy.localName); - #else - __bc_impl.$proxy.name = $proxy.localName; - #end -#end -## -## This macro defines the initialization method for all nested contextual services -## -#macro (declareServiceInit) - /** - * Initializes the nested contextual services required by the implementation - */ - public void initServices(ControlBean bean, Object target) - { - $impl.className __bc_impl = ($impl.className)target; - - super.initServices(bean, __bc_impl); - - ControlBeanContext __bc_beanContext = bean.getControlBeanContext(); - try - { - #foreach ($context in $impl.contexts) - #initContext($context) - #end - } - catch (RuntimeException __bc_re) { throw __bc_re; } - catch (Exception __bc_e) - { - throw new ControlException("Contextual service initialization failure", __bc_e); - } - } - - /** - * Resets all nested contextual services instances to null - */ - public void resetServices(ControlBean bean, Object target) - { - $impl.className __bc_impl = ($impl.className)target; - - super.resetServices(bean, __bc_impl); - - try - { - #foreach ($context in $impl.contexts) - #resetContext($context) - #end - } - catch (RuntimeException __bc_re) { throw __bc_re; } - catch (Exception __bc_e) - { - throw new ControlException("Contextual service reset failure", __bc_e); - } - } -#end -## -## This macro defines the initialization method for all nested control references -## -#macro (declareControlsInit) - /** - * Initializes the nested client event proxies required by the implementation - */ - public void initControls(ControlBean bean, Object target) - { - $impl.className __bc_impl = ($impl.className)target; - // DO NOT DELEGATE TO SUPERCLASS HERE. THE CONTROL CLIENT INIT HIERARCHY - // WILL INITIALIZE ALL THE WAY DOWN TO THE BASE CLASS! - - try - { - ${init.clientInitializerName}.initialize(bean.getControlBeanContext(), __bc_impl); - } - catch (RuntimeException __bc_re) { throw __bc_re; } - catch (Exception __bc_e) - { - throw new ControlException("Client event proxy initialization failure", __bc_e); - } - } -#end -## -## This macro defines the initialization method for all nested event proxies -## -#macro (declareEventProxyInit) - /** - * Initializes the nested client event proxies required by the implementation - */ - public void initEventProxies(ControlBean bean, Object target) - { - $impl.className __bc_impl = ($impl.className)target; - - super.initEventProxies(bean, __bc_impl); - - try - { - #foreach ($proxy in $impl.clients) - #initEventProxy($proxy) - #end - } - catch (RuntimeException __bc_re) { throw __bc_re; } - catch (Exception __bc_e) - { - throw new ControlException("Client event proxy initialization failure", __bc_e); - } - } -#end -## -## THE CONTROL INITIALIZER CLASS TEMPLATE -## -#if (!$init.isRootPackage()) -package $init.package; -#end - -import java.lang.reflect.Field; -import org.apache.beehive.controls.api.ControlException; -import org.apache.beehive.controls.api.context.ControlBeanContext; -import org.apache.beehive.controls.runtime.bean.ControlBean; - -@SuppressWarnings("all") -public class $init.shortName - #if ($init.hasSuperClass()) - extends $init.superClass.className - #else - extends org.apache.beehive.controls.runtime.bean.ImplInitializer - #end -{ - #if ($init.reflectFields.size() != 0) - #declareReflectFields() - static - { - #initReflectFields() - } - #end - - #if ($impl.hasContexts() || $impl.hasClients()) - #declareEventAdaptors() - #end - - #if ($impl.hasContexts()) - #declareServiceInit() - #end - - #if ($impl.hasControls()) - #declareControlsInit() - #end - - #if ($impl.hasClients()) - #declareEventProxyInit() - #end -} diff --git a/beehive-controls/src/main/resources/org/apache/beehive/controls/runtime/generator/apt/strings.properties b/beehive-controls/src/main/resources/org/apache/beehive/controls/runtime/generator/apt/strings.properties deleted file mode 100644 index 64f2fee..0000000 --- a/beehive-controls/src/main/resources/org/apache/beehive/controls/runtime/generator/apt/strings.properties +++ /dev/null @@ -1,186 +0,0 @@ -control.field.bad.interfacetype=\ -A control field's type must be annotated with @ControlInterface or @ControlExtension if it's an interface. \ -Verify the type of the control field declaration is annotated correctly. - -control.field.bad.classtype=\ -A control field's type must implement org.apache.beehive.controls.api.bean.ControlBean if it's a class. \ -Verify the type of the control field declaration implements ControlBean. - -control.field.bad.classtype.badinterface=\ -If a control field's type is a class, that class must implement the control's public interface/extension and no other interface. \ -Verify the type of the control field declaration implements only the public interface/extension. - -control.field.type.malformed=\ -The type of the control field is malformed. Verify that the source of the type has no errors. - -control.field.bad.version=\ -Control field {0} fails version requirement: requires interface version {1}.{2}, found interface version {3}.{4} - -control.field.in.inner.class=\ -A control field can exist only within the top-level class. \ -Move fields marked with the Control annotation to just inside the top-level class. - -control.field.override=\ -This control field conflicts with another of the same name in superclass {0}. - -control.public.interface.not.found = \ -Cannot find the public interface for this control. \ -Verify that the public interface for this control is available in this project. - -transient.control.field =\ -A control can not be declared as transient. \ -Remove the transient modifier from the control declaration. - -static.control.field =\ -A control can not be declared as static. \ -Remove the static modifier from the control declaration. - -controls.client.manifest.ioerror= \ -An error occurred writing the controls client manifest. - -propertyset.illegal.argument.error=\ -A value assigned to a control property does not satisfy \ -its constraints. Cause: {0} - -control.member.type.invalid.date.value.error=\ -The value assigned to a date property must be in the format specified. - -control.member.type.invalid.date.format.error=\ -The date format specified is not valid, please see java.text.SimpleDateFormat for valid formats. - -control.reference.bad.interfacetype=\ -Types listed in @ControlReferences must be control interfaces (ie, interfaces annotated with @ControlInterface or @ControlExtension). \ -Verify the types listed in @ControlReferences are control interface types. - -control.interface.annotation.badlocation=\ -The ControlInterface or ControlExtension annotation may only be used on a Java interface. - -control.extension.badinterface=\ -Interfaces annotated with ControlExtension must extend an interface annotated with ControlInterface. - -control.interface.badinterface=\ -An interface annotated with @ControlInterface can only extend another ControlInterface. It is not valid for \ -a ControlInterface to extend a ControlExtension. - -property.primitive.without.default=\ -Primitive property {0} must specify a default value. - -propertyset.illegal.usage=\ -The PropertySet annotation may only be used on a Java annotation interface. - -propertyset.illegal.usage.2=\ -The @PropertySet annotation should only be used within an interface annotated with @ControlInterface, \ -never @ControlExtension. An extension can only use existing properties, not declare new ones. - -extpropertyset.illegal.usage=\ -The @ExternalPropertySets annotation should only be used on an interface annotated with \ -@ControlInterface, never @ControlExtension. An extension can only use existing properties, not declare new one. - -extpropertyset.type.not.found=\ -Unable to load type declaration for externally referenced PropertySet {0}. - -propertyset.not.annotation.type=\ -The PropertySet annotation must be on an Annotation type. - -propertyset.missing.retention=\ -The PropertySet annotation must be used in conjuction with @Retention(RetentionPolicy.RUNTIME). - -propertyset.duplicate.property.names=\ -Duplicate property name {0} found on property set '{1}'. Consider using the PropertySet 'prefix' \ -attribute to disambiguate. - -eventset.illegal.usage=\ -The EventSet annotation must be on an interface declaration. - -eventset.formal.parameter.mismatch=\ -Any EventSet formal type parameters must match ones declared on the associated control type. \ -No new formal type parameters may be introduced. - -eventset.illegal.multicast=\ -Event methods declared within a multicast EventSet cannot return a value. Change the return \ -type of this method declaration to void, or use the unicast attribute of @EventSet to change to a unicast event set. - -manifestattribute.illegal.name.1=\ -@ManifestAttribute name cannot be a zero-length string. - -manifestattribute.illegal.name.2=\ -@ManifestAttribute name must begin with an alphanumeric character. - -manifestattribute.illegal.name.3=\ -@ManifestAttribute name contains an invalid character: {0}. - -manifestattribute.illegal.name.4=\ -@ManifestAttribute value cannot be a zero-length string. - -versionrequired.illegal.usage=\ -Illegal usage of @VersionRequired: not permitted on interfaces annotated with @ControlInterface. - -versionrequired.failed=\ -Control extension {0} fails version requirement: requires interface version {1}.{2}, found interface \ -version {3}.{4}. - -control.interface.illegal.checker=\ -Control interface {0} specifies a checker class {1} that doesn't implement ControlChecker. - -control.interface.checker.load.failed=\ -Control interface {0} specifies a checker class {1} which cannot be loaded. Verify that the \ -apt -classpath value is correct. - -control.implementation.badclass=\ -The ControlImplementation annotation may only be used on a Java class. - -control.implementation.unserializable=\ -A ControlImplementation class must implement the java.io.Serializable interface or set the isTransient \ -attribute of @ControlImplementation to true. - -control.implementation.missing.interface=\ -Control implementations must implement a control interface. - -eventhandler.field.not.found=\ -Cannot find event source field: {0}. - -eventhandler.eventset.not.found=\ -Cannot find EventSet interface: {0}. - -eventhandler.method.is.private=\ -Methods annotated with the EventHandler annotation can not be private. - -eventhandler.method.not.found=\ -No event method with matching name and signature found on EventSet: {0}. - -eventhandler.throws.mismatch=\ -Handler method {0} 'throws' clause is not a proper subset of the eventset method's 'throws' clause. \ -Handlers may only throw throwables declared by the eventset method. - -versionsupported.failed=\ -Control implementation {0} fails version support requirement: highest supported interface version is \ -{1}.{2}, found interface version {3}.{4}. - -control.illegal.usage=\ -The Control annotation may only be used in a Java class. - -context.field.badinterface=\ -@Context field type must be an interface. - -control.field.bad.type=\ -@Control field type must be a valid ControlBean class or control interface. \ -Verify that the type of the field declaration is a control class or interface. - -control.field.bad.type.2=\ -Unable to identify control type of field. - - - - - - - - - - - - - - - - diff --git a/beehive-controls/src/main/resources/org/apache/beehive/controls/test/util/strings.properties b/beehive-controls/src/main/resources/org/apache/beehive/controls/test/util/strings.properties deleted file mode 100644 index e69de29..0000000 diff --git a/beehive-ejb-control/pom.xml b/beehive-ejb-control/pom.xml deleted file mode 100644 index 6945fbe..0000000 --- a/beehive-ejb-control/pom.xml +++ /dev/null @@ -1,45 +0,0 @@ - - - - - 4.0.0 - - com.moparisthebest.beehive - beehive - 1.0.5-SNAPSHOT - - beehive-ejb-control - beehive-ejb-control - - - com.moparisthebest.beehive - beehive-controls - ${project.version} - - - com.moparisthebest.aptIn16 - netui-compiler - - - org.apache.geronimo.specs - geronimo-j2ee_1.4_spec - - - \ No newline at end of file diff --git a/beehive-ejb-control/src/main/java/org/apache/beehive/controls/system/ejb/EJBControl.java b/beehive-ejb-control/src/main/java/org/apache/beehive/controls/system/ejb/EJBControl.java deleted file mode 100644 index 0dbf789..0000000 --- a/beehive-ejb-control/src/main/java/org/apache/beehive/controls/system/ejb/EJBControl.java +++ /dev/null @@ -1,133 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.system.ejb; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -import org.apache.beehive.controls.api.bean.AnnotationMemberTypes; -import org.apache.beehive.controls.api.bean.ControlInterface; -import org.apache.beehive.controls.api.bean.AnnotationConstraints.MembershipRule; -import org.apache.beehive.controls.api.bean.AnnotationConstraints.MembershipRuleValues; -import org.apache.beehive.controls.api.properties.PropertySet; - -/** - * Enterprise Java Bean Control base interface - */ -@ControlInterface (defaultBinding="org.apache.beehive.controls.system.ejb.EJBControlImpl") -public interface EJBControl -{ - /** - * EJBHome specifies the target EJB's home interface for the EJB control using the following attributes: - *

      - *
    • jndiName specifies the JNDI name of the target EJB's home interface - * (e.g. EJBNameHome). This value may also be an URL using the "JNDI:" - * protocol (e.g. jndi://username:password@host:port/EJBNameHome). - *
    • - *
    • ejbLink specifies the name of the target EJB using the application - * relative path to the EJB JAR. This syntax causes the runtime to - * use an application scoped name when locating the referenced EJB. - * The naming syntax is jarfile.jar#ejb-name (e.g. ejbModule.jar#HelloBean). - *
    • - *
    - * An EJB Control in a web application would reference an EJB type using the - * fully qualified name of the control interface with the suffix "jcx". For example, - * a control of type controls.HelloEjbControl would resolve the EJB using - * the following entry in web.xml: - *
    -     * <ejb-ref>
    -     *     <ejb-ref-name>controls.HelloEjbControl.jcx</ejb-ref-name>
    -     *     <ejb-ref-type>Session</ejb-ref-type>
    -     *     <home>ejbs.HelloBeanHome</home>
    -     *     <remote>ejbs.HelloBeanRemote</remote>
    -     *     <ejb-link>ejbModule.jar#HelloBean</ejb-link>
    -     * </ejb-ref>
    -     * 
    - */ - @PropertySet - @Retention(RetentionPolicy.RUNTIME) - @Target({ElementType.TYPE, ElementType.FIELD}) // allow override on declaration - @MembershipRule(MembershipRuleValues.EXACTLY_ONE) - public @interface EJBHome - { - String jndiName() default ""; - String ejbLink() default ""; - } - - /** - * JNDIContextEnv specifies the environment properties for the JNDI context that will - * be used to lookup the target EJB. This attribute is optional. If you are using - * an URL with the "JNDI:" protocol or if you want to use a JNDI context with the - * default envirnoment properties, you do not need a specify any values for this attribute. - */ - @PropertySet - @Retention(RetentionPolicy.RUNTIME) - @Target({ElementType.TYPE, ElementType.FIELD}) // allow override on declaration - public @interface JNDIContextEnv - { - @AnnotationMemberTypes.Optional - String contextFactory() default ""; - - @AnnotationMemberTypes.Optional - String providerURL() default ""; - - @AnnotationMemberTypes.Optional - String principal() default ""; - - @AnnotationMemberTypes.Optional - String credentials() default ""; - } - - /** - * Returns an instance of the home interface associated with - * the target bean component. - */ - public Object getEJBHomeInstance(); - - /** - * Returns true if the EJB control currently has a target bean instance - * upon which bean business interface methods may be invoked. This will - * be true after a successful create() or single select finder method - * execution, or in cases where implicit creation or find has occurred - * by the control on the control users behalf. This provides a simple - * way to procedurally check the status of explicit or implicit - * bean instance creation or find operations. - */ - public boolean hasEJBBeanInstance(); - - /** - * Returns the current target instance of the bean business interface - * used for business interface method invocations. This API is - * provided for advanced use cases were direct access to the local/ - * remote interfaces outside of the control is required. It will - * return null if no target instance is currently - * selected. - */ - public Object getEJBBeanInstance(); - - /** - * Returns the last EJB exception serviced by the EJB control on the - * developers behalf. This can be used to discover or log additional - * information, for example when a create or find method is unable to - * locate a target bean instance. - */ - public Throwable getEJBException(); -} diff --git a/beehive-ejb-control/src/main/java/org/apache/beehive/controls/system/ejb/EJBControlAssembler.java b/beehive-ejb-control/src/main/java/org/apache/beehive/controls/system/ejb/EJBControlAssembler.java deleted file mode 100644 index 666a5e4..0000000 --- a/beehive-ejb-control/src/main/java/org/apache/beehive/controls/system/ejb/EJBControlAssembler.java +++ /dev/null @@ -1,299 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.system.ejb; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; -import javax.xml.transform.Transformer; -import javax.xml.transform.TransformerConfigurationException; -import javax.xml.transform.TransformerException; -import javax.xml.transform.TransformerFactory; -import javax.xml.transform.OutputKeys; -import javax.xml.transform.dom.DOMSource; -import javax.xml.transform.stream.StreamResult; - -import org.apache.beehive.controls.api.assembly.ControlAssembler; -import org.apache.beehive.controls.api.assembly.ControlAssemblyContext; -import org.apache.beehive.controls.api.assembly.ControlAssemblyException; -import org.apache.beehive.controls.system.ejb.internal.EJBJarDescriptorHandler; -import org.apache.beehive.controls.system.ejb.internal.WebDescriptorHandler; -import org.w3c.dom.Document; -import org.w3c.dom.DocumentType; -import org.xml.sax.SAXException; - -/** - * The EJBControl needs to inject EJB reference entries into the - * DD of its containing module for cases where ejb-link is used. - */ -public class EJBControlAssembler implements ControlAssembler -{ - public void assemble(ControlAssemblyContext cac) - throws ControlAssemblyException { - cac.getMessager().printNotice("EJBControlAssembler.assemble() called"); - - Class controlInterface = cac.getControlType(); - EJBInfo ei = new EJBInfo( controlInterface ); - - EJBControl.EJBHome ea = cac.getControlAnnotation(EJBControl.EJBHome.class); - if ( ea == null ) { - cac.getMessager().printError("Missing EJBHome annotation on control?!"); - return; - } - - String ejbLinkValue = ea.ejbLink(); - if ( ejbLinkValue == null || ejbLinkValue.length() == 0 ) - // Not using ejb-link, so no ejb-ref injection needed - return; - - if (cac instanceof ControlAssemblyContext.EJBModule) - // insert any required entries into the deployment descriptor - updateEJBJar((ControlAssemblyContext.EJBModule)cac, ei, ejbLinkValue ); - else if (cac instanceof ControlAssemblyContext.WebAppModule) - updateWebApp((ControlAssemblyContext.WebAppModule)cac, ei, ejbLinkValue ); - else cac.getMessager().printNotice("EJBControlAssembler - no work to do, assembly context is not EJB."); - } - - protected void updateEJBJar(ControlAssemblyContext.EJBModule ejbAssemblyContext, - EJBInfo ejbInfo, - String ejbLinkValue) - throws ControlAssemblyException { - ControlAssemblyContext cac = (ControlAssemblyContext)ejbAssemblyContext; - - cac.getMessager().printNotice("EJBControlAssembler.updateEJBJar() called"); - cac.getMessager().printNotice(" ejbInfo=" + ejbInfo ); - cac.getMessager().printNotice(" ejbLinkValue=" + ejbLinkValue ); - - File ejbJarFile = ejbAssemblyContext.getEjbJarXml(); - FileInputStream ejbJarStream; - try { - ejbJarStream = new FileInputStream( ejbJarFile ); - } - catch (FileNotFoundException fnfe) { - String msg = "EJBControlAssembler aborted: " + - "caught FileNotFoundException attempting to read file " + - ejbJarFile.getAbsolutePath() + - ". Message: " + - fnfe.getMessage(); - cac.getMessager().printWarning(msg); - return; - } - - try - { - // get the existing XBean from the stream - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - dbf.setValidating(false); - DocumentBuilder db = dbf.newDocumentBuilder(); - Document ejbDoc = db.parse(ejbJarStream); - - ejbJarStream.close(); - ejbJarStream = null; - - EJBJarDescriptorHandler ejbHandler = EJBJarDescriptorHandler.getInstance(); - ejbHandler.assemble(ejbDoc, ejbInfo, ejbLinkValue); - - // overwrite existing ejb-jar.xml file with new document - writeXML(cac, ejbDoc, ejbJarFile); - } - catch(IOException ioe) { - String msg = "EJBControlAssembler: caught IOException " + - "attempting to write to file " + - ejbJarFile.getAbsolutePath() + - ". Message: " + - ioe.getMessage(); - cac.getMessager().printError(msg); - } - catch (ParserConfigurationException e) { - String msg = "EJBControlAssembler: caught ParserConfigurationException " + - "attempting to read to file " + - ejbJarFile.getAbsolutePath() + - ". Message: " + - e.getMessage(); - cac.getMessager().printError(msg); - } - catch (SAXException e) { - String msg = "EJBControlAssembler: caught SAXException " + - "attempting to read to file " + - ejbJarFile.getAbsolutePath() + - ". Message: " + - e.getMessage(); - cac.getMessager().printError(msg); - } - finally { - try { - if (ejbJarStream != null) - ejbJarStream.close(); - } - catch(IOException e) { /* ignore */ } - } - } - - protected void updateWebApp(ControlAssemblyContext.WebAppModule webAssemblyContext, - EJBInfo ejbInfo, - String ejbLinkValue) - throws ControlAssemblyException - { - ControlAssemblyContext cac = (ControlAssemblyContext)webAssemblyContext; - - System.err.println("EJBControlAssembler.updateWebApp() called"); - System.err.println("ejbInfo =" + ejbInfo); - System.err.println("ejbLinkValue =" + ejbLinkValue ); - File webXmlFile = webAssemblyContext.getWebXml(); - FileInputStream webXmlStream; - try { - webXmlStream = new FileInputStream( webXmlFile ); - } - catch (FileNotFoundException fnfe) { - String msg = "EJBControlAssembler: " + - "caught FileNotFoundException attempting to read file " + - webXmlFile.getAbsolutePath() + ". Message: " + - fnfe.getMessage(); - cac.getMessager().printError(msg); - return; - } - - try - { - // parse the web.xml file - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - dbf.setValidating(false); - DocumentBuilder db = dbf.newDocumentBuilder(); - Document webAppDoc = db.parse(webXmlStream); - - webXmlStream.close(); - webXmlStream = null; - - WebDescriptorHandler webHandler = WebDescriptorHandler.getInstance(); - webHandler.assemble(webAppDoc, ejbInfo, ejbLinkValue); - - // overwrite existing web.xml file with new document - writeXML(cac, webAppDoc, webXmlFile); - } - catch(IOException ioe) { - String msg = "EJBControlAssembler: caught IOException " + - "attempting to write to file " + - webXmlFile.getAbsolutePath() + - ". Message: " + - ioe.getMessage(); - cac.getMessager().printError(msg); - } - catch (ParserConfigurationException e) { - String msg = "EJBControlAssembler: caught ParserConfigurationException " + - "attempting to read to file " + - webXmlFile.getAbsolutePath() + - ". Message: " + - e.getMessage(); - cac.getMessager().printError(msg); - } - catch (SAXException e) { - String msg = "EJBControlAssembler: caught SAXException " + - "attempting to read to file " + - webXmlFile.getAbsolutePath() + - ". Message: " + - e.getMessage(); - cac.getMessager().printError(msg); - } - finally { - try { - if (webXmlStream != null) - webXmlStream.close(); - } - catch(IOException e) { /* ignore */ } - } - - } - - private void writeXML(ControlAssemblyContext cac, Document doc, File outputFile) { - - TransformerFactory transformerFactory = TransformerFactory.newInstance(); - try { - transformerFactory.setAttribute("indent-number", 2); - } catch (IllegalArgumentException e) { - // not a fatal error, just means underlying parser implementation does not support indent-number. - String msg = "EJBControlAssembler: Warning -- Caught IllegalArgumentException " + - "attempting to set transformer factory attribute: 'indent-number'. Message: " + - e.getMessage(); - - cac.getMessager().printNotice(msg); - } - - Transformer transformer; - FileOutputStream fos = null; - try { - transformer= transformerFactory.newTransformer(); - try { - transformer.setOutputProperty(OutputKeys.INDENT, "yes"); - DocumentType docType = doc.getDoctype(); - if (docType != null) { - transformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, docType.getPublicId()); - transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, docType.getSystemId()); - } - } catch (IllegalArgumentException e) { - // just keep going not a fatal error, just means underlying parser implementation - // does not support one of these options. - String msg = "EJBControlAssembler: Warning -- Caught IllegalArgumentException " + - "attempting to set transformer option. Message: " + - e.getMessage(); - - cac.getMessager().printNotice(msg); - } - - DOMSource source = new DOMSource(doc); - fos = new FileOutputStream(outputFile); - StreamResult stream = new StreamResult(fos); - transformer.transform(source, stream); - - } - catch (TransformerConfigurationException e) { - String msg = "EJBControlAssembler: caught TransformerConfigurationException " + - "attempting to write to file " + outputFile.getAbsolutePath() + - ". Message: " + e.getMessage(); - cac.getMessager().printError(msg); - } - catch (FileNotFoundException e) { - String msg = "EJBControlAssembler aborted: " + - "caught FileNotFoundException attempting to write file " + - outputFile.getAbsolutePath() + - ". Message: " + - e.getMessage(); - cac.getMessager().printError(msg); - } - catch (TransformerException e) { - String msg = "EJBControlAssembler: caught TransformerException " + - "attempting to write to file " + - outputFile.getAbsolutePath() + - ". Message: " + - e.getMessage(); - cac.getMessager().printError(msg); - } - finally { - if (fos != null) { - try { - fos.close(); - } catch (IOException e) { /* ignore */ } - } - } - } -} diff --git a/beehive-ejb-control/src/main/java/org/apache/beehive/controls/system/ejb/EJBControlImpl.java b/beehive-ejb-control/src/main/java/org/apache/beehive/controls/system/ejb/EJBControlImpl.java deleted file mode 100644 index 7cb822a..0000000 --- a/beehive-ejb-control/src/main/java/org/apache/beehive/controls/system/ejb/EJBControlImpl.java +++ /dev/null @@ -1,489 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.system.ejb; - -import java.io.IOException; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.net.MalformedURLException; -import java.net.URL; -import java.net.URLConnection; -import java.util.Hashtable; - -import javax.ejb.CreateException; -import javax.ejb.EJBObject; -import javax.ejb.FinderException; -import javax.ejb.Handle; -import javax.naming.InitialContext; -import javax.naming.NamingException; -import javax.naming.NameNotFoundException; -import javax.rmi.PortableRemoteObject; - -import org.apache.beehive.controls.api.ControlException; -import org.apache.beehive.controls.api.bean.ControlImplementation; -import org.apache.beehive.controls.api.bean.Extensible; -import org.apache.beehive.controls.api.bean.ControlExtension; -import org.apache.beehive.controls.api.context.Context; -import org.apache.beehive.controls.api.context.ControlBeanContext; -import org.apache.beehive.controls.api.context.ControlBeanContext.LifeCycle; -import org.apache.beehive.controls.api.context.ResourceContext; -import org.apache.beehive.controls.api.context.ResourceContext.ResourceEvents; -import org.apache.beehive.controls.api.events.EventHandler; -import org.apache.commons.logging.LogFactory; -import org.apache.commons.logging.Log; - -/** - * The Enterprise Java Bean Control implementation class - */ -@ControlImplementation -public abstract class EJBControlImpl - implements EJBControl, Extensible, java.io.Serializable { - - static final long serialVersionUID = 1L; - private static final Log LOGGER = LogFactory.getLog(EJBControlImpl.class); - - public static final int SESSION_BEAN = 1; - public static final int ENTITY_BEAN = 2; - - public static final String JNDI_GLOBAL_PREFIX = "jndi:"; - public static final String JNDI_APPSCOPED_PREFIX = "java:comp/env/"; - - @EventHandler(field = "context", eventSet = LifeCycle.class, eventName = "onCreate") - public void onCreate() { - - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Enter: onCreate()"); - } - - EJBHome ejbHome = context.getControlPropertySet(EJBHome.class); - if (ejbHome == null) - throw new ControlException("No @EJBHome property is defined"); - - _jndiName = ejbHome.jndiName(); - if (_jndiName == null || _jndiName.length() == 0) { - String ejbLink = ejbHome.ejbLink(); - if (ejbLink.length() == 0) { - // - // Should be caught by the compiler - // - throw new ControlException("Either the jndiName() or ejbLink() member of @EJBHome must be defined."); - } - - // - // Generate a unique local jndi name to associate w/ the link, - // based upon the local control service uri and control id - // - _jndiName = JNDI_APPSCOPED_PREFIX + EJBInfo.getEJBRefName(context.getControlInterface()); - } - - // Obtain the JCX interface and identify the home/remote - // interfaces. - EJBInfo beanInfo = new EJBInfo(context.getControlInterface()); - _homeInterface = beanInfo._homeInterface; - _beanInterface = beanInfo._beanInterface; - _beanType = beanInfo._beanType.equals("Session") ? SESSION_BEAN : ENTITY_BEAN; - } - - protected static boolean methodThrows(Method m, Class exceptionClass) { - Class [] exceptions = m.getExceptionTypes(); - for (int j = 0; j < exceptions.length; j++) - if (exceptionClass.isAssignableFrom(exceptions[j])) - return true; - return false; - } - - protected boolean isHomeMethod(Method m) { - return m.getDeclaringClass().isAssignableFrom(_homeInterface); - } - - /** - * Return true if the method is from the ControlBean. - * @param m Method to check. - */ - protected boolean isControlBeanMethod(Method m) { - return (m.getDeclaringClass().getAnnotation(ControlExtension.class) != null); - } - - /** - * Map a control bean method to an EJB method. - * - * @param m The control bean method. - * @return The corresponding method of the EJB. - */ - protected Method mapControlBeanMethodToEJB(Method m) { - Method ejbMethod = findEjbMethod(m, _homeInterface); - if (ejbMethod == null) { - if (_beanInstance == null) { - _beanInstance = resolveBeanInstance(); - if (_beanInstance == null) { - throw new ControlException("Unable to resolve bean instance"); - } - } - ejbMethod = findEjbMethod(m, _beanInstance.getClass()); - if (ejbMethod == null) { - throw new ControlException("Unable to map ejb control interface method to EJB method: " + m.getName()); - } - } - return ejbMethod; - } - - /** - * Find the method which has the same signature in the specified class. - * - * @param controlBeanMethod Method signature find. - * @param ejbInterface Class to search for method signature. - * @return Method from ejbInterface if found, null if not found. - */ - protected Method findEjbMethod(Method controlBeanMethod, Class ejbInterface) { - final String cbMethodName = controlBeanMethod.getName(); - final Class cbMethodReturnType = controlBeanMethod.getReturnType(); - final Class[] cbMethodParams = controlBeanMethod.getParameterTypes(); - - Method[] ejbMethods = ejbInterface.getMethods(); - for (Method m : ejbMethods) { - if (!cbMethodName.equals(m.getName()) - || !cbMethodReturnType.equals(m.getReturnType())) { - continue; - } - - Class[] params = m.getParameterTypes(); - if (cbMethodParams.length == params.length) { - int i; - for (i = 0; i < cbMethodParams.length; i++) { - if (cbMethodParams[i] != params[i]) break; - } - if (i == cbMethodParams.length) - return m; - } - } - return null; - } - - protected static boolean isCreateMethod(Method m) { - return methodThrows(m, CreateException.class); - } - - protected static boolean isFinderMethod(Method m) { - if (!m.getName().startsWith("find")) // EJB enforced pattern - return false; - return methodThrows(m, FinderException.class); - } - - protected boolean isSelectorMethod(Method m) { - return isHomeMethod(m) && m.getReturnType().equals(_beanInterface); - } - - static protected boolean isRemoveMethod(Method m) { - if (!m.getName().equals("remove") || (m.getParameterTypes().length != 0)) - return false; - else return true; - } - - protected Object homeNarrow(Object obj) { - if (javax.ejb.EJBHome.class.isAssignableFrom(_homeInterface)) - return PortableRemoteObject.narrow(obj, _homeInterface); - else return obj; - } - - protected Object beanNarrow(Object obj) { - if (javax.ejb.EJBObject.class.isAssignableFrom(_beanInterface)) - return PortableRemoteObject.narrow(obj, _beanInterface); - else return obj; - } - - /* - * This method is implemented by the appropriate bean type-specific - * control to provide auto create/find semantics for bean instances. - * - * IT SHOULD ALWAYS THROW A RUNTIME EXCEPTION WITH A TYPE-SPECIFIC - * ERROR MESSAGE IF RESOLUTION CANNOT TAKE PLACE. IT SHOULD _NEVER_ - * HAVE A NON-EXCEPTED RETURN WHERE _beanInstance == null. - */ - abstract protected Object resolveBeanInstance(); - - // - // Is there is a cached EJB handle associated with this bean, then - // is it to restore the associate EJB object reference. - // - protected Object resolveBeanInstanceFromHandle() { - if (_beanHandle == null) - return null; - - try { - return _beanHandle.getEJBObject(); - } - catch (java.rmi.RemoteException re) { - throw new ControlException("Unable to convert EJB handle to object", re); - } - } - - // - // Attempts to save the contents of the current bean reference in persisted - // control state. Returns true if state could be saved, false otherwise - // - protected boolean saveBeanInstance() { - // Nothing to save == success - if (_beanInstance == null) - return true; - - // - // Save using a bean handle, but handles only exist for remote objects. - // - if (_beanInstance instanceof EJBObject) { - try { - _beanHandle = ((EJBObject) _beanInstance).getHandle(); - } - catch (java.rmi.RemoteException re) { - throw new ControlException("Unable to get bean instance from handle", re); - } - - return true; - } - return false; - } - - // - // This is called whenever a bean reference is being dropped, and is the - // provides an opportunity to reset cached state or release non-persisted - // resources associated with the instance. - // - protected void releaseBeanInstance(boolean alreadyRemoved) { - _beanInstance = null; - _beanHandle = null; - } - - protected javax.naming.Context getInitialContext() throws NamingException { - if (_context == null) { - //If naming context information is provided, then use that to create the initial context - JNDIContextEnv env = context.getControlPropertySet(JNDIContextEnv.class); - String value = env.contextFactory(); - if (value != null && value.length() > 0) { - Hashtable ht = new Hashtable(); - ht.put(javax.naming.Context.INITIAL_CONTEXT_FACTORY, value); - value = env.providerURL(); - if (value != null && value.length() > 0) - ht.put(javax.naming.Context.PROVIDER_URL, value); - value = env.principal(); - if (value != null && value.length() > 0) - ht.put(javax.naming.Context.SECURITY_PRINCIPAL, value); - value = env.credentials(); - if (value != null && value.length() > 0) - ht.put(javax.naming.Context.SECURITY_CREDENTIALS, value); - _context = new InitialContext(ht); - } - else { - _context = new InitialContext(); - } - } - return _context; - - } - - @EventHandler(field = "resourceContext", eventSet = ResourceEvents.class, eventName = "onAcquire") - public void onAcquire() { - - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Enter: onAquire()"); - } - - // Compute the home instance cache lookup key. The Service URI must - // be taken into account because different services use different - // class loaders. The JNDI home must be taken into account because - // it is possible to be a remote client of the same bean type on two - // different providers. - // - if (_homeInstance == null) { - // If JNDI name is an URL using a JNDI protocol - if (_jndiName.toLowerCase().startsWith(JNDI_GLOBAL_PREFIX)) { - - try { - URL url = new URL(_jndiName); - URLConnection jndiConn = url.openConnection(); - _homeInstance = jndiConn.getContent(); - } - catch (MalformedURLException mue) { - throw new ControlException(_jndiName + " is not a valid JNDI URL", mue); - } - catch (IOException ioe) { - throw new ControlException("Error during JNDI lookup from " + _jndiName, ioe); - } - } - else { - - try { - _homeInstance = lookupHomeInstance(); - } - catch (NamingException ne) { - throw new ControlException("Error during JNDI lookup from " + _jndiName, ne); - } - } - - if (!_homeInterface.isAssignableFrom(_homeInstance.getClass())) { - throw new ControlException("JNDI lookup of " + _jndiName + " failed to return an instance of " + _homeInterface); - } - } - } - - @EventHandler(field = "resourceContext", eventSet = ResourceEvents.class, eventName = "onRelease") - public void onRelease() { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Enter: onRelease()"); - } - releaseBeanInstance(false); - } - - //@EventHandler(field="context", eventSet=LifeCycle.class, eventName="onReset") - public void onReset() { - _lastException = null; - // other work in onRelease(), delivered prior to reset event - } - - /** - * Extensible.invoke - * Handles all extended interface methods (i.e. EJB home and remote - * interface invocation) - */ - public Object invoke(Method m, Object[] args) throws Throwable { - Object retval = null; - - if (isControlBeanMethod(m)) { - m = mapControlBeanMethodToEJB(m); - } - - if (isHomeMethod(m)) { - try { - retval = m.invoke(_homeInstance, args); - } - catch (Exception e) { - Throwable t = e; - if (e instanceof InvocationTargetException) - t = ((InvocationTargetException) e).getTargetException(); - _lastException = t; - throw t; - } - - // If the method was successful and returns an instance of - // the bean interface class, then reset the target instance. - if (isSelectorMethod(m)) { - releaseBeanInstance(false); - retval = beanNarrow(retval); - _beanInstance = retval; - } - - return retval; - } - // is remote / bean interface - else { - if (_beanInstance == null) - _beanInstance = resolveBeanInstance(); - - // By convention, the below cond should never be true. The bean - // type-specific resolve should throw an appropriate exception - // that is more specific. This is a safety net. - if (_beanInstance == null) - throw new ControlException("Unable to resolve bean instance"); - - try { - return m.invoke(_beanInstance, args); - } - catch (Exception e) { - Throwable t = e; - if (e instanceof InvocationTargetException) - t = ((InvocationTargetException) e).getTargetException(); - _lastException = t; - - throw t; - } - finally { - // Handle remove method properly - if (isRemoveMethod(m)) - releaseBeanInstance(true); - } - } - } - - /** - * EJBControl.getEJBHomeInstance() - */ - public Object getEJBHomeInstance() { - return _homeInstance; - } - - /** - * EJBControl.getEJBBeanInstance() - */ - public boolean hasEJBBeanInstance() { - return _beanInstance != null; - } - - /** - * EJBControl.getEJBBeanInstance() - */ - public Object getEJBBeanInstance() { - return _beanInstance; - } - - /** - * EJBControl.getEJBException() - */ - public Throwable getEJBException() { - return _lastException; - } - - /** - * Do a JNDI lookup for the home instance of the ejb. Attempt the lookup - * first using an app scoped jndi prefix, if not successful, attempt without - * the prefix. - * - * @return HomeInstance object. - * @throws NamingException If HomeInstance cannot be found in JNDI registry. - */ - private Object lookupHomeInstance() throws NamingException { - - javax.naming.Context ctx = getInitialContext(); - - try { - return ctx.lookup(_jndiName); - } - catch (NameNotFoundException nnfe) { - // attempt again without application scoping - if (!_jndiName.startsWith(JNDI_APPSCOPED_PREFIX)) { - throw nnfe; - } - } - return ctx.lookup(_jndiName.substring(JNDI_APPSCOPED_PREFIX.length())); - } - - @Context - ControlBeanContext context; - - @Context - ResourceContext resourceContext; - - protected Class _controlInterface; - protected Class _homeInterface; - protected Class _beanInterface; - protected int _beanType; - protected String _jndiName; - protected Handle _beanHandle; - protected transient javax.naming.Context _context; // don't persist - protected transient Throwable _lastException; // don't persist - protected transient Object _beanInstance; // don't persist - protected transient Object _homeInstance; // don't persist -} diff --git a/beehive-ejb-control/src/main/java/org/apache/beehive/controls/system/ejb/EJBInfo.java b/beehive-ejb-control/src/main/java/org/apache/beehive/controls/system/ejb/EJBInfo.java deleted file mode 100644 index 37a7184..0000000 --- a/beehive-ejb-control/src/main/java/org/apache/beehive/controls/system/ejb/EJBInfo.java +++ /dev/null @@ -1,223 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.system.ejb; - -import java.lang.reflect.Method; -import java.util.HashMap; -import java.util.Vector; -import javax.ejb.EJBLocalHome; -import javax.ejb.FinderException; - -import org.apache.beehive.controls.api.ControlException; - -/** - * The EJBInfo class is a support class that derives EJB information by - * reflecting on an EJB control interface. This is implemented by a - * static inner class to make this functionality accesible in both static - * and non-static contexts - */ -public class EJBInfo { - - /** - * @deprecated Use the JavaBean getter / setter instead - */ - public String _refName; - - /** - * @deprecated Use the JavaBean getter / setter instead - */ - public Class _homeInterface; - - /** - * @deprecated Use the JavaBean getter / setter instead - */ - public Class _beanInterface; - - /** - * @deprecated Use the JavaBean getter / setter instead - */ - public String _beanType; - - /** - * @deprecated Use the JavaBean getter / setter instead - */ - public boolean _isLocal; - - /** - * Derives bean attributes from the control interface - */ - public EJBInfo(Class controlInterface) { - _refName = getEJBRefName(controlInterface); - - Class localHome = null; - Class localBean = null; - Class remoteHome = null; - Class remoteBean = null; - - // - // To identify the identify home and bean interfaces, we - // must reflect the interface hierarchy of the provided - // class. - // - Vector checkList = new Vector(); - Class [] subintfs = controlInterface.getInterfaces(); - for (int i = 0; i < subintfs.length; i++) - checkList.add(subintfs[i]); - - HashMap derivesFrom = new HashMap(); - for (int i = 0; i < checkList.size(); i++) { - Class intf = (Class) checkList.elementAt(i); - - if (javax.ejb.EJBHome.class.isAssignableFrom(intf)) - remoteHome = intf; - else if (javax.ejb.EJBLocalHome.class.isAssignableFrom(intf)) - localHome = intf; - else if (javax.ejb.EJBObject.class.isAssignableFrom(intf)) - remoteBean = intf; - else if (javax.ejb.EJBLocalObject.class.isAssignableFrom(intf)) - localBean = intf; - else { - // - // If none of the above, add any new subinterfaces to - // the search list. - // - subintfs = intf.getInterfaces(); - for (int j = 0; j < subintfs.length; j++) { - if (!checkList.contains(subintfs[j])) { - checkList.add(subintfs[j]); - derivesFrom.put(subintfs[j], intf); - } - } - } - } - - // - // From the located methods, identify the home/bean interfaces. - // - if (remoteHome != null) { - if (localHome != null) - throw new ControlException(controlInterface + " extends multiple EJB home interfaces."); - _homeInterface = getRoot(remoteHome, derivesFrom); - } - else if (localHome != null) - _homeInterface = getRoot(localHome, derivesFrom); - else throw new ControlException(controlInterface + " does not extend the EJBHome or EJBLocalHome interfaces"); - - if (remoteBean != null) { - if (localBean != null) - throw new ControlException("Interface " + controlInterface + " extends multiple EJB object interfaces."); - _beanInterface = getRoot(remoteBean, derivesFrom); - } - else if (localBean != null) - _beanInterface = getRoot(localBean, derivesFrom); - else throw new ControlException("Interface " + controlInterface + " does not extend the EJBObject or EJBLocalObject interfaces"); - - // Identify the bean type via bean interface reflection - _beanType = "Session"; - Method [] homeMethods = _homeInterface.getMethods(); - for (int i = 0; i < homeMethods.length; i++) { - if (isFinderMethod(homeMethods[i])) { - _beanType = "Entity"; - break; - } - } - - _isLocal = (EJBLocalHome.class.isAssignableFrom(_homeInterface)); - } - - /** - * Unwinds the results of reflecting through the interface inheritance - * hierachy to find the original root class from a derived class - */ - public Class getRoot(Class clazz, HashMap derivesFrom) { - while (derivesFrom.containsKey(clazz)) clazz = (Class) derivesFrom.get(clazz); - return clazz; - } - - /** - * Computes a unique local ejb ref name based upon the JCX class name - */ - public static String getEJBRefName(Class jcxClass) { - return jcxClass.getName() + ".jcx"; - } - - public String getRefName() { - return _refName; - } - - public void setRefName(String refName) { - _refName = refName; - } - - public Class getHomeInterface() { - return _homeInterface; - } - - public void setHomeInterface(Class homeInterface) { - _homeInterface = homeInterface; - } - - public Class getBeanInterface() { - return _beanInterface; - } - - public void setBeanInterface(Class beanInterface) { - _beanInterface = beanInterface; - } - - public String getBeanType() { - return _beanType; - } - - public void setBeanType(String beanType) { - _beanType = beanType; - } - - public boolean isLocal() { - return _isLocal; - } - - public void setLocal(boolean local) { - _isLocal = local; - } - - public String toString() { - return - "{refname=" + _refName + - " home=" + _homeInterface.getName() + - " remote=" + _beanInterface.getName() + - " type=" + _beanType + - " local=" + _isLocal + "}"; - } - - protected static boolean isFinderMethod(Method m) { - if (!m.getName().startsWith("find")) // EJB enforced pattern - return false; - return methodThrows(m, FinderException.class); - } - - protected static boolean methodThrows(Method m, Class exceptionClass) { - Class [] exceptions = m.getExceptionTypes(); - for (int j = 0; j < exceptions.length; j++) - if (exceptionClass.isAssignableFrom(exceptions[j])) - return true; - return false; - } -} - diff --git a/beehive-ejb-control/src/main/java/org/apache/beehive/controls/system/ejb/EntityEJBControl.java b/beehive-ejb-control/src/main/java/org/apache/beehive/controls/system/ejb/EntityEJBControl.java deleted file mode 100644 index dfff692..0000000 --- a/beehive-ejb-control/src/main/java/org/apache/beehive/controls/system/ejb/EntityEJBControl.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.system.ejb; - -import org.apache.beehive.controls.api.bean.ControlInterface; - -/** - * As part of the EJB control, this interface simplifies access to - * entity Enterprise JavaBeans (EJBs). You do not need to call - * methods of this interface. - *

    - * The EJB control is actually made up of two main interfaces, - * one for access to entity EJBs - * and another for access to session EJBs. The presence of these - * two interfaces is invisible when you use the EJB control; their - * methods are called behind the scenes. - *

    - * Typically, you use the EJB control by adding the control to - * a component design (such as a web service or pageflow design), - * then calling the methods it provides. Those methods are not - * exposed by these control interfaces, but rather - * are extensions of the EJB itself that are generated when you add - * the EJB control. - *

    - * For more information about using the EJB control, see - * EJB Control. - */ -@ControlInterface (defaultBinding="org.apache.beehive.controls.system.ejb.EntityEJBControlImpl") -public interface EntityEJBControl - extends EJBControl -{ - /** - * Supports iteration through a Collection of entity bean instances - * returned by a multi-select finder method. This method selects - * the next bean instance in the collection as the internal control - * instance, and returns the bean instance. The method will return - * null if no additional instances remain to be processed. - * - * @return The next bean instance if any remain; otherwise, null. - */ - public Object getEJBNextBeanInstance(); -} diff --git a/beehive-ejb-control/src/main/java/org/apache/beehive/controls/system/ejb/EntityEJBControlImpl.java b/beehive-ejb-control/src/main/java/org/apache/beehive/controls/system/ejb/EntityEJBControlImpl.java deleted file mode 100644 index 3071593..0000000 --- a/beehive-ejb-control/src/main/java/org/apache/beehive/controls/system/ejb/EntityEJBControlImpl.java +++ /dev/null @@ -1,196 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.system.ejb; - -import java.io.Serializable; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.rmi.RemoteException; -import java.util.Collection; -import java.util.Iterator; -import javax.ejb.EJBLocalObject; -import javax.ejb.EJBObject; - -import org.apache.beehive.controls.api.ControlException; -import org.apache.beehive.controls.api.bean.ControlImplementation; - -/** - * The EntityEJBControlImpl class is the control implementation class for - * Entity EJBs. - */ -@ControlImplementation(assembler = EJBControlAssembler.class) -public class EntityEJBControlImpl - extends EJBControlImpl - implements EntityEJBControl, java.io.Serializable { - - static final long serialVersionUID = 1L; - - // - // Implements auto-find semantics for entity beans - // - protected Object resolveBeanInstance() { - // Already resolved and cached - if (_beanInstance != null) - return _beanInstance; - - // Attempt to resolve from a cached handle - _beanInstance = resolveBeanInstanceFromHandle(); - if (_beanInstance != null) - return _beanInstance; - - // Attempt to resolve bean instance from cached primary key - if (_lastKey == null) - throw new ControlException("Unable to locate a target bean instance, because a successful create or finder method has not been executed."); - - Class [] findArgType = new Class[]{_lastKey.getClass()}; - try { - Method finder = _homeInterface.getMethod("findByPrimaryKey", findArgType); - return finder.invoke(_homeInstance, new Object []{_lastKey}); - } - catch (NoSuchMethodException nsme) { - throw new ControlException("Unable to locate findByPrimaryKey method on home interface", nsme); - } - catch (InvocationTargetException ite) { - _lastException = ite.getTargetException(); - throw new ControlException("Failure to locate entity instance associated with the last primary key", _lastException); - } - catch (Exception e) { - throw new ControlException("Unexpected exception in auto-find", e); - } - } - - protected boolean saveBeanInstance() { - // - // First, delegate to parent (handle-based persistence) - // - if (super.saveBeanInstance()) - return true; - - // - // Fall back to persistence using a saved primary key value - // - try { - if (_beanInstance instanceof EJBObject) - _lastKey = (Serializable) ((EJBObject) _beanInstance).getPrimaryKey(); - else - _lastKey = (Serializable) ((EJBLocalObject) _beanInstance).getPrimaryKey(); - } - catch (RemoteException re) { - throw new ControlException("Unable to save bean instance", re); - } - return true; - } - - // - // Release the bean instance. Entity bean instances are *never* removed, except via - // direct client calls to the remove method. - // - protected void releaseBeanInstance(boolean alreadyRemoved) { - super.releaseBeanInstance(alreadyRemoved); - - // Release any cached primary key value - _lastKey = null; - } - - private boolean isMultiSelectorMethod(Method m) { - return isFinderMethod(m) && m.getReturnType().isAssignableFrom(Collection.class); - } - - // - // This method wraps the base EJBControlImpl invoke, doing the additional - // work to maintain the primary key cache for methods which alter the - // target bean instance. - // - public Object invoke(Method m, Object [] args) throws Throwable { - Throwable invokeException = null; - Object retval = null; - Object currentBeanInstance = _beanInstance; - try { - retval = super.invoke(m, args); - } - catch (Exception t) { - // a tasty treat, but I'll throw up later - invokeException = t; - } - - if (isControlBeanMethod(m)) { - m = mapControlBeanMethodToEJB(m); - } - - if (isMultiSelectorMethod(m)) { - releaseBeanInstance(false); - - Collection collection = (Collection) retval; - if (collection != null && !collection.isEmpty()) { - _colIter = collection.iterator(); - _beanInstance = beanNarrow(_colIter.next()); - } - else releaseBeanInstance(false); - } - else if (isSelectorMethod(m)) { - // Release collection results if a single select method is called. - _colIter = null; - } - - if (invokeException != null) - throw invokeException; - - return retval; - } - - /** - * EntityEJBControl.getEJBNextBeanInstance() - */ - public Object getEJBNextBeanInstance() { - if (_colIter == null) - return null; - - if (!_colIter.hasNext()) { - releaseBeanInstance(false); - return null; - } - - _beanInstance = beanNarrow(_colIter.next()); - return _beanInstance; - } - - // - // Override the onCreate event handler that was already defined in EJBControlImpl to - // add additional processing. - // - public void onCreate() { - super.onCreate(); - if (_beanType != EJBControlImpl.ENTITY_BEAN) { - throw new ControlException("Attempting to use a entity bean control with a bean that is not a entity bean"); - } - } - - // - // Override the onReset event handler that was already defined in EJBControlImpl to - // add additional processing. - // - public void onReset() { - super.onReset(); - _lastKey = null; - _colIter = null; - } - - private Serializable _lastKey; // primary key of the selected instance - private transient Iterator _colIter; // multi-finder result iterator -} diff --git a/beehive-ejb-control/src/main/java/org/apache/beehive/controls/system/ejb/SessionEJBControl.java b/beehive-ejb-control/src/main/java/org/apache/beehive/controls/system/ejb/SessionEJBControl.java deleted file mode 100644 index 55b04ab..0000000 --- a/beehive-ejb-control/src/main/java/org/apache/beehive/controls/system/ejb/SessionEJBControl.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.system.ejb; - -import org.apache.beehive.controls.api.bean.ControlInterface; - -/** - * As part of the EJB control, this interface simplifies access to - * session Enterprise JavaBeans (EJBs). You do not need to use - * this interface directly. - *

    - * The EJB control is actually made up of two main interfaces, - * one for access to entity EJBs - * and another for access to session EJBs. The presence of these - * two interfaces is invisible when you use the EJB control; their - * methods are called behind the scenes. - *

    - * Typically, you use the EJB control by adding the control to a - * component design (such as a web service or pageflow design), - * then calling the methods it provides. Those methods are not - * exposed by these control interfaces, but rather are extensions - * of the EJB itself that are generated when you add - * the EJB control. - *

    - * For more information about using the EJB control, see - * EJB Control. - */ -@ControlInterface (defaultBinding="org.apache.beehive.controls.system.ejb.SessionEJBControlImpl") -public interface SessionEJBControl - extends EJBControl -{ -} diff --git a/beehive-ejb-control/src/main/java/org/apache/beehive/controls/system/ejb/SessionEJBControlImpl.java b/beehive-ejb-control/src/main/java/org/apache/beehive/controls/system/ejb/SessionEJBControlImpl.java deleted file mode 100644 index 2df3d33..0000000 --- a/beehive-ejb-control/src/main/java/org/apache/beehive/controls/system/ejb/SessionEJBControlImpl.java +++ /dev/null @@ -1,112 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.system.ejb; - -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import javax.ejb.EJBObject; -import javax.ejb.EJBLocalObject; - -import org.apache.beehive.controls.api.ControlException; -import org.apache.beehive.controls.api.bean.ControlImplementation; - -/** - * The SessionEJBControlImpl class is the control implementation class for - * Stateless/Stateful Session EJBs. - *

    - * Currently, this is a noop since no session-bean specific control APIs - * are defined, but having a unique control interface/impl class still allows - * JellyBeans to create two different control types. - */ -@ControlImplementation(assembler = EJBControlAssembler.class) -public class SessionEJBControlImpl - extends EJBControlImpl - implements SessionEJBControl, java.io.Serializable { - - static final long serialVersionUID = 1L; - - /** - * Override ejbControl.onCreate to perform additional processing - */ - public void onCreate() { - - super.onCreate(); - if (_beanType != EJBControlImpl.SESSION_BEAN) - throw new ControlException("Attempting to use a session bean control with a bean that is not a session bean"); - } - - /** - * Implements auto-create semantics for Session beans. - */ - protected Object resolveBeanInstance() { - - // First, try to resolve from a cached EJB handle (if any) - Object fromHandle = resolveBeanInstanceFromHandle(); - if (fromHandle != null) - return fromHandle; - - // Find null arg create() on the home interface, and use it to get an instance - try { - /* todo: for efficiency, this could be done once per home interface and cached */ - Method createMethod = _homeInterface.getMethod("create", new Class []{}); - Object beanInstance = createMethod.invoke(_homeInstance, (Object[])null); - _autoCreated = true; - return beanInstance; - } - catch (NoSuchMethodException e) { - throw new ControlException("Cannot auto-create session bean instance because no null argument create() method exists. To use this bean, you will need to call create() directly with the appropriate parameters"); - } - catch (InvocationTargetException e) { - _lastException = e.getTargetException(); - - throw new ControlException("Unable to create session bean instance", _lastException); - } - catch (Exception e) { - throw new ControlException("Unable to invoke home interface create method", e); - } - } - - protected void releaseBeanInstance(boolean alreadyRemoved) { - // - // For session EJBs, releasing the instance implies the physical - // removal of the bean instance. If the bean was auto-created by - // the control, it has responsibility for deleting. - // - if (_beanInstance != null && _autoCreated && !alreadyRemoved) { - try { - if (EJBObject.class.isAssignableFrom(_beanInterface)) - ((EJBObject) _beanInstance).remove(); - else - ((EJBLocalObject) _beanInstance).remove(); - } - /* RemoteException or RemoveException */ - catch (Exception e) { - _lastException = e; - } - } - - super.releaseBeanInstance(alreadyRemoved); - } - - /** - * Set to true if the EJB instance was autocreated as a result of a bean method - * call (as opposed to direct invocation of the home create() method). - */ - private boolean _autoCreated = false; -} diff --git a/beehive-ejb-control/src/main/java/org/apache/beehive/controls/system/ejb/internal/DomUtils.java b/beehive-ejb-control/src/main/java/org/apache/beehive/controls/system/ejb/internal/DomUtils.java deleted file mode 100644 index 88c4f49..0000000 --- a/beehive-ejb-control/src/main/java/org/apache/beehive/controls/system/ejb/internal/DomUtils.java +++ /dev/null @@ -1,193 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.system.ejb.internal; - -import java.util.ArrayList; -import java.util.List; - -import org.w3c.dom.Attr; -import org.w3c.dom.Element; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; -import org.w3c.dom.Text; - -/** - * Some simple DOM utility methods. - */ -final class DomUtils { - - /** - *

    Returns the first child element with the given name. Returns - * null if not found.

    - * - * @param parent parent element - * @param name name of the child element - * @return child element - */ - static Element getChildElementByName(Element parent, String name) { - NodeList children = parent.getChildNodes(); - - for (int i = 0; i < children.getLength(); i++) { - Node node = children.item(i); - if (node.getNodeType() == Node.ELEMENT_NODE) { - Element element = (Element) node; - if (element.getTagName().equals(name)) { - return element; - } - } - } - - return null; - } - - /** - *

    Returns a list of child elements with the given - * name. Returns an empty list if there are no such child - * elements.

    - * - * @param parent parent element - * @param name name of the child element - * @return child elements - */ - static List getChildElementsByName(Element parent, String name) { - List elements = new ArrayList(); - - NodeList children = parent.getChildNodes(); - - for (int i = 0; i < children.getLength(); i++) { - Node node = children.item(i); - if (node.getNodeType() == Node.ELEMENT_NODE) { - Element element = (Element) node; - if (element.getTagName().equals(name)) { - elements.add(element); - } - } - } - - return elements; - } - - /** - *

    Returns the text value of a child element. Returns - * null if there is no child element found.

    - * - * @param parent parent element - * @param name name of the child element - * @return text value - */ - static String getChildElementText(Element parent, String name) { - // Get children - List list = DomUtils.getChildElementsByName(parent, name); - - if (list.size() == 1) { - Element child = (Element) list.get(0); - - StringBuffer buf = new StringBuffer(); - - NodeList children = child.getChildNodes(); - for (int i = 0; i < children.getLength(); i++) { - Node node = children.item(i); - if (node.getNodeType() == Node.TEXT_NODE || - node.getNodeType() == Node.CDATA_SECTION_NODE) { - Text text = (Text) node; - buf.append(text.getData().trim()); - } - } - - return buf.toString(); - } else { - return null; - } - } - - /** - *

    Returns the text value of a child element. Returns - * null if there is no child element found.

    - * - * @param element element - * @return text value - */ - static String getElementText(Element element) { - StringBuffer buf = new StringBuffer(); - - NodeList children = element.getChildNodes(); - for (int i = 0; i < children.getLength(); i++) { - Node node = children.item(i); - if (node.getNodeType() == Node.TEXT_NODE || - node.getNodeType() == Node.CDATA_SECTION_NODE) { - Text text = (Text) node; - buf.append(text.getData().trim()); - } - } - - return buf.toString(); - } - - /** - *

    Returns an array of text values of a child element. Returns - * null if there is no child element found.

    - * - * @param parent parent element - * @param name name of the child element - * @return text value - */ - static String[] getChildElementTextArr(Element parent, String name) { - // Get all the elements - List children = getChildElementsByName(parent, name); - - String str[] = new String[children.size()]; - - for (int i = 0; i < children.size(); i++) { - Node child = (Node) children.get(i); - - StringBuffer buf = new StringBuffer(); - - NodeList nodes = child.getChildNodes(); - for (int j = 0; j < nodes.getLength(); j++) { - Node node = nodes.item(j); - if (node.getNodeType() == Node.TEXT_NODE || - node.getNodeType() == Node.CDATA_SECTION_NODE) { - Text text = (Text) node; - buf.append(text.getData().trim()); - } - } - - str[i] = buf.toString(); - } - - return str; - } - - /** - *

    Retutns the value of the named attribute of the given - * element. If there is no such attribute, returns null.

    - * - * @param element element - * @param name name - * @return value - */ - static String getAttributeValue(Element element, String name) { - Attr attribute = element.getAttributeNode(name); - if (attribute == null) { - return null; - } else { - return attribute.getValue(); - } - } -} diff --git a/beehive-ejb-control/src/main/java/org/apache/beehive/controls/system/ejb/internal/EJBJarDescriptorHandler.java b/beehive-ejb-control/src/main/java/org/apache/beehive/controls/system/ejb/internal/EJBJarDescriptorHandler.java deleted file mode 100644 index 464ee73..0000000 --- a/beehive-ejb-control/src/main/java/org/apache/beehive/controls/system/ejb/internal/EJBJarDescriptorHandler.java +++ /dev/null @@ -1,269 +0,0 @@ -/** - 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. - - $Header:$ - */ -package org.apache.beehive.controls.system.ejb.internal; - -import org.apache.beehive.controls.system.ejb.EJBInfo; -import org.w3c.dom.Document; -import org.w3c.dom.Element; -import org.w3c.dom.Node; - -import java.util.List; - -/** - * This class is used by the EJBControlAssembler to modify an ejb-jar.xml file's ejb-ref descriptors. - * The assembler will only invoke this class if the EJBControl's @EJBHome.ejbLink() annotation attribute - * has been set. - *

    - * The EjbJar assembler walks the ejb-jar.xml DOM tree looking for any session / entity beans - * which contain ejb-ref or ejb-local-ref elements. If an ejb-ref is found which matches the - * ejbRefName from the EJBInfo helper class it is removed and then re-created using the proper values. - */ -public class EJBJarDescriptorHandler { - - /** - * Get an instance of this class. - * @return EJBJarDescriptorHandler instance. - */ - public static EJBJarDescriptorHandler getInstance() { - return new EJBJarDescriptorHandler(); - } - - /** - * Private constructor, use getInstance() to get an instance of this class. - */ - private EJBJarDescriptorHandler() { - } - - /** - * Assemble entry point. Based on the type of EJBControl build a list of - * DOM elements of the property type (either session or entity) and process - * each entry in the list. - * - * @param document DOM tree of an ejb-jar.xml file. - * @param ejbInfo Contains information about the EJB control. - * @param ejbLinkValue The ejb-link value for the EJBs. - */ - public void assemble(Document document, EJBInfo ejbInfo, String ejbLinkValue) { - Element ejbJarType = document.getDocumentElement(); - Element entBeansType = DomUtils.getChildElementByName(ejbJarType, "enterprise-beans"); - - String beanType = ejbInfo.getBeanType(); - if (!("Session".equals(beanType) || "Entity".equals(beanType))) - { - throw new UnsupportedOperationException("Unknown EJBControl type: " - + ejbInfo.getBeanType() - + beanType - + " Expected 'Session' or 'Entity'"); - } - - /* TODO: Currently, we update all session and entity bean entries with a ejb ref, even - if the control is not used from the ejb. We should probably only add an ejb ref - to a given session or entity bean if the control is referenced by it. */ - List sessionEjbList = DomUtils.getChildElementsByName(entBeansType, "session"); - insertEJBRefsInEJBJar(document, ejbInfo, ejbLinkValue, sessionEjbList); - - List entityEjbList = DomUtils.getChildElementsByName(entBeansType, "entity"); - insertEJBRefsInEJBJar(document, ejbInfo, ejbLinkValue, entityEjbList); - } - - /** - * Insert EJB references in all of the descriptors of the EJB's in the supplied list - * - * @param document DOM tree of an ejb-jar.xml file. - * @param ejbInfo Contains information about the EJB control. - * @param ejbLinkValue The ejb-link value for the EJBs. - * @param ejbList The list of EJB's - */ - private void insertEJBRefsInEJBJar(Document document, EJBInfo ejbInfo, String ejbLinkValue, List ejbList) { - for (Object ejb : ejbList) { - if (ejbInfo.isLocal()) - insertEJBLocalRefInEJBJar((Element)ejb, ejbInfo, ejbLinkValue, document); - else - insertEJBRefInEJBJar((Element)ejb, ejbInfo, ejbLinkValue, document); - } - } - - /** - * Insert a remote ejb-ref into the specified EJB's descriptor, if an ejb-ref already - * exists with the same name, remove it before adding a new ref. - * - * @param ejb Root DOM element of the EJB descriptor. - * @param ei EJBInfo helper. - * @param ejbLinkValue New ejb-link value. - * @param ejbDoc The ejb-jar DOM root. - */ - private void insertEJBRefInEJBJar(Element ejb, EJBInfo ei, String ejbLinkValue, Document ejbDoc) { - - List ejbRefArray = DomUtils.getChildElementsByName(ejb, "ejb-ref"); - String insertedEjbRefName = ei.getRefName(); - - Node nextSibling = null; - for (int j = ejbRefArray.size() - 1; j >= 0; j--) { - Element ejbRef = (Element) ejbRefArray.get(j); - String ejbRefName = DomUtils.getChildElementText(ejbRef, "ejb-ref-name"); - if (insertedEjbRefName.equals(ejbRefName)) { - nextSibling = ejbRef.getNextSibling(); - ejb.removeChild(ejbRef); - break; - } - } - - // insert a new entry and fill in the values - Element insertedEjbRef = ejbDoc.createElement("ejb-ref"); - if (nextSibling != null) { - ejb.insertBefore(insertedEjbRef, nextSibling); - } - else { - ejb.insertBefore(insertedEjbRef, findEjbRefInsertPoint(ejb)); - } - - Element ejbRefName = ejbDoc.createElement("ejb-ref-name"); - ejbRefName.setTextContent(insertedEjbRefName); - insertedEjbRef.appendChild(ejbRefName); - - Element ejbRefType = ejbDoc.createElement("ejb-ref-type"); - ejbRefType.setTextContent(ei.getBeanType()); - insertedEjbRef.appendChild(ejbRefType); - - Element homeType = ejbDoc.createElement("home"); - homeType.setTextContent(ei.getHomeInterface().getName()); - insertedEjbRef.appendChild(homeType); - - Element remoteType = ejbDoc.createElement("remote"); - remoteType.setTextContent(ei.getBeanInterface().getName()); - insertedEjbRef.appendChild(remoteType); - - Element ejbLink = ejbDoc.createElement("ejb-link"); - ejbLink.setTextContent(ejbLinkValue); - insertedEjbRef.appendChild(ejbLink); - } - - /** - * Insert a local ejb-ref into the specified EJB's descriptor, if an ejb-ref already - * exists with the same name, remove it before adding a new ref. - * - * @param ejb Root DOM element of the EJB descriptor. - * @param ei EJBInfo helper. - * @param ejbLinkValue New ejb-link value. - * @param ejbDoc The ejb-jar DOM root. - */ - private void insertEJBLocalRefInEJBJar(Element ejb, EJBInfo ei, String ejbLinkValue, Document ejbDoc) { - - List ejbLocalRefArray = DomUtils.getChildElementsByName(ejb, "ejb-local-ref"); - String insertedEjbRefName = ei.getRefName(); - - Node nextSibling = null; - for (int j = ejbLocalRefArray.size() - 1; j >= 0; j--) { - Element ejbLocalRef = (Element) ejbLocalRefArray.get(j); - String ejbRefName = DomUtils.getChildElementText(ejbLocalRef, "ejb-ref-name"); - if (insertedEjbRefName.equals(ejbRefName)) { - nextSibling = ejbLocalRef.getNextSibling(); - ejb.removeChild(ejbLocalRef); - break; - } - } - - // insert a new entry and fill in the values - Element insertedEjbLocalRef = ejbDoc.createElement("ejb-local-ref"); - if (nextSibling != null) { - ejb.insertBefore(insertedEjbLocalRef, nextSibling); - } - else { - ejb.insertBefore(insertedEjbLocalRef, findEjbLocalRefInsertPoint(ejb)); - } - - Element ejbRefName = ejbDoc.createElement("ejb-ref-name"); - ejbRefName.setTextContent(insertedEjbRefName); - insertedEjbLocalRef.appendChild(ejbRefName); - - Element ejbRefType = ejbDoc.createElement("ejb-ref-type"); - ejbRefType.setTextContent(ei.getBeanType()); - insertedEjbLocalRef.appendChild(ejbRefType); - - Element homeType = ejbDoc.createElement("local-home"); - homeType.setTextContent(ei.getHomeInterface().getName()); - insertedEjbLocalRef.appendChild(homeType); - - Element localType = ejbDoc.createElement("local"); - localType.setTextContent(ei.getBeanInterface().getName()); - insertedEjbLocalRef.appendChild(localType); - - Element ejbLink = ejbDoc.createElement("ejb-link"); - ejbLink.setTextContent(ejbLinkValue); - insertedEjbLocalRef.appendChild(ejbLink); - } - - /** - * ejb-refs must be inserted before any ejb-local-ref tags. - * - * @param parent The 'session' or 'entity' XML element. - * @return A suitable node to insert the ejb-ref BEFORE. - */ - private Node findEjbRefInsertPoint(Element parent) { - - Element e = DomUtils.getChildElementByName(parent, "ejb-local-ref"); - if (e != null) - return e; - - return findEjbLocalRefInsertPoint(parent); - } - - /** - * The local ref must be inserted into the ejb-jar file at the proper - * location based on the ejb-jar schema definition. Check for elements which - * can immediatly FOLLOW an ejb-ref from the closest to farthest as - * defined by the schema. - * - * @param parent The 'session' or 'entity' XML element. - * @return A suitable node to insert the ejb-local-ref BEFORE. - */ - private Node findEjbLocalRefInsertPoint(Element parent) { - - Element e = DomUtils.getChildElementByName(parent, "service-ref"); - if (e != null) - return e; - - e = DomUtils.getChildElementByName(parent, "resource-ref"); - if (e != null) - return e; - - e = DomUtils.getChildElementByName(parent, "resource-env-ref"); - if (e != null) - return e; - - e = DomUtils.getChildElementByName(parent, "message-destination-ref"); - if (e != null) - return e; - - e = DomUtils.getChildElementByName(parent, "security-role-ref"); - if (e != null) - return e; - - e = DomUtils.getChildElementByName(parent, "security-identity"); - if (e != null) - return e; - - // only applies to entity beans - e = DomUtils.getChildElementByName(parent, "query"); - if (e != null) - return e; - - return null; - } -} diff --git a/beehive-ejb-control/src/main/java/org/apache/beehive/controls/system/ejb/internal/WebDescriptorHandler.java b/beehive-ejb-control/src/main/java/org/apache/beehive/controls/system/ejb/internal/WebDescriptorHandler.java deleted file mode 100644 index 955e8ed..0000000 --- a/beehive-ejb-control/src/main/java/org/apache/beehive/controls/system/ejb/internal/WebDescriptorHandler.java +++ /dev/null @@ -1,169 +0,0 @@ -/** - 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. - - $Header:$ - */ -package org.apache.beehive.controls.system.ejb.internal; - -import java.util.List; - -import org.apache.beehive.controls.system.ejb.EJBInfo; -import org.w3c.dom.Element; -import org.w3c.dom.Document; -import org.w3c.dom.Node; - -/** - * - */ -public class WebDescriptorHandler { - - public static WebDescriptorHandler getInstance() { - return new WebDescriptorHandler(); - } - - private WebDescriptorHandler() {} - - public void assemble(Document document, EJBInfo ejbInfo, String ejbLinkValue) { - Element webAppType = document.getDocumentElement(); - - if (ejbInfo.isLocal()) - insertEJBLocalRefInWebApp(webAppType, ejbInfo, ejbLinkValue, document); - else - insertEJBRefInWebApp(webAppType, ejbInfo, ejbLinkValue, document); - } - - private void insertEJBRefInWebApp(Element webAppType, EJBInfo ei, String ejbLinkValue, Document webAppDoc) { - List ejbRefArray = DomUtils.getChildElementsByName(webAppType, "ejb-ref"); - - String insertedEjbRefName = ei.getRefName(); - Node nextSibling = null; - for (int j = ejbRefArray.size() - 1; j >= 0; j--) { - Element ejbRef = (Element) ejbRefArray.get(j); - String ejbRefName = DomUtils.getChildElementText(ejbRef, "ejb-ref-name"); - if (insertedEjbRefName.equals(ejbRefName)) { - nextSibling = ejbRef.getNextSibling(); - webAppType.removeChild(ejbRef); - break; - } - } - - // insert a new entry and fill in the values - Element insertedEjbRef = webAppDoc.createElement("ejb-ref"); - if (nextSibling != null) - webAppType.insertBefore(insertedEjbRef, nextSibling); - else webAppType.insertBefore(insertedEjbRef, findEjbRefInsertPoint(webAppType)); - - Element ejbRefName = webAppDoc.createElement("ejb-ref-name"); - ejbRefName.setTextContent(insertedEjbRefName); - insertedEjbRef.appendChild(ejbRefName); - - Element ejbRefType = webAppDoc.createElement("ejb-ref-type"); - ejbRefType.setTextContent(ei.getBeanType()); - insertedEjbRef.appendChild(ejbRefType); - - Element homeType = webAppDoc.createElement("home"); - homeType.setTextContent(ei.getBeanInterface().getName()); - insertedEjbRef.appendChild(homeType); - - Element remoteType = webAppDoc.createElement("remote"); - remoteType.setTextContent(ei.getBeanInterface().getName()); - insertedEjbRef.appendChild(remoteType); - - Element ejbLink = webAppDoc.createElement("ejb-link"); - ejbLink.setTextContent(ejbLinkValue); - insertedEjbRef.appendChild(ejbLink); - } - - private void insertEJBLocalRefInWebApp(Element webAppType, EJBInfo ei, String ejbLinkValue, Document webAppDoc) - { - List ejbLocalRefArray = DomUtils.getChildElementsByName(webAppType, "ejb-local-ref"); - String insertedEjbRefName = ei.getRefName(); - - Node nextSibling = null; - for (int j = ejbLocalRefArray.size() - 1; j >= 0; j--) { - Element ejbLocalRef = (Element) ejbLocalRefArray.get(j); - String ejbRefName = DomUtils.getChildElementText(ejbLocalRef, "ejb-ref-name"); - if (insertedEjbRefName.equals(ejbRefName)) { - nextSibling = ejbLocalRef.getNextSibling(); - webAppType.removeChild(ejbLocalRef); - break; - } - } - - // insert a new entry and fill in the values - Element insertedEjbLocalRef = webAppDoc.createElement("ejb-local-ref"); - if (nextSibling != null) - webAppType.insertBefore(insertedEjbLocalRef, nextSibling); - else webAppType.insertBefore(insertedEjbLocalRef, findEjbLocalRefInsertPoint(webAppType)); - - Element ejbRefName = webAppDoc.createElement("ejb-ref-name"); - ejbRefName.setTextContent(insertedEjbRefName); - insertedEjbLocalRef.appendChild(ejbRefName); - - Element ejbRefType = webAppDoc.createElement("ejb-ref-type"); - ejbRefType.setTextContent(ei.getBeanType()); - insertedEjbLocalRef.appendChild(ejbRefType); - - Element homeType = webAppDoc.createElement("local-home"); - homeType.setTextContent(ei.getHomeInterface().getName()); - insertedEjbLocalRef.appendChild(homeType); - - Element localType = webAppDoc.createElement("local"); - localType.setTextContent(ei.getBeanInterface().getName()); - insertedEjbLocalRef.appendChild(localType); - - Element ejbLink = webAppDoc.createElement("ejb-link"); - ejbLink.setTextContent(ejbLinkValue); - insertedEjbLocalRef.appendChild(ejbLink); - } - - private Node findEjbRefInsertPoint(Element parent) { - Element e = DomUtils.getChildElementByName(parent, "ejb-local-ref"); - if (e != null) - return e; - - return findEjbLocalRefInsertPoint(parent); - } - - private Node findEjbLocalRefInsertPoint(Element parent) { - - Element e = DomUtils.getChildElementByName(parent, "service-ref"); - if (e != null) - return e; - - e = DomUtils.getChildElementByName(parent, "resource-ref"); - if (e != null) - return e; - - e = DomUtils.getChildElementByName(parent, "resource-env-ref"); - if (e != null) - return e; - - e = DomUtils.getChildElementByName(parent, "message-destination-ref"); - if(e != null) - return e; - - e = DomUtils.getChildElementByName(parent, "message-destination"); - if (e != null) - return e; - - e = DomUtils.getChildElementByName(parent, "locale-encoding-mapping-list"); - if (e != null) - return e; - - return null; - } -} diff --git a/beehive-jdbc-control/pom.xml b/beehive-jdbc-control/pom.xml deleted file mode 100644 index 7e043d6..0000000 --- a/beehive-jdbc-control/pom.xml +++ /dev/null @@ -1,52 +0,0 @@ - - - - - 4.0.0 - - com.moparisthebest.beehive - beehive - 1.0.5-SNAPSHOT - - beehive-jdbc-control - beehive-jdbc-control - - - com.moparisthebest.beehive - beehive-controls - ${project.version} - - - com.moparisthebest.beehive - beehive-jdbc-mapper - ${project.version} - - - com.moparisthebest.aptIn16 - netui-compiler - compile - true - - - xmlbeans - xbean - - - \ No newline at end of file diff --git a/beehive-jdbc-control/src/main/java/org/apache/beehive/controls/system/jdbc/AbstractResultSetMapper.java b/beehive-jdbc-control/src/main/java/org/apache/beehive/controls/system/jdbc/AbstractResultSetMapper.java deleted file mode 100644 index ec53eed..0000000 --- a/beehive-jdbc-control/src/main/java/org/apache/beehive/controls/system/jdbc/AbstractResultSetMapper.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.system.jdbc; - -/** - * Extend this class to create new ResultSet mappers. The extended class will be invoked by the JdbcController - * when it is time to map a ResultSet to a method's return type. - * - * ResultSet mappers are specified on a per method basis using the SQL annotation's resultSetMapper field. - */ -public abstract class AbstractResultSetMapper implements ResultSetMapper { - - /** - * Can the ResultSet which this mapper uses be closed by the Jdbc control? - * @return true if the ResultSet can be closed by the JdbcControl - */ - public boolean canCloseResultSet() { return true; } -} diff --git a/beehive-jdbc-control/src/main/java/org/apache/beehive/controls/system/jdbc/DefaultIteratorResultSetMapper.java b/beehive-jdbc-control/src/main/java/org/apache/beehive/controls/system/jdbc/DefaultIteratorResultSetMapper.java deleted file mode 100644 index 72516ea..0000000 --- a/beehive-jdbc-control/src/main/java/org/apache/beehive/controls/system/jdbc/DefaultIteratorResultSetMapper.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ - -package org.apache.beehive.controls.system.jdbc; - -import org.apache.beehive.controls.api.context.ControlBeanContext; - -import java.lang.reflect.Method; -import java.sql.ResultSet; -import java.util.Calendar; -import java.util.Iterator; - -/** - * Default ResultSetMapper implementation for Iterators. - */ -public class DefaultIteratorResultSetMapper extends AbstractResultSetMapper { - - /** - * Map a ResultSet to an object type - * Type of object to interate over is defined in the SQL annotation for the method. - * - * @param context A ControlBeanContext instance, see Beehive controls javadoc for additional information - * @param m Method assoicated with this call. - * @param resultSet Result set to map. - * @param cal A Calendar instance for time/date value resolution. - * @return The Iterator object instance resulting from the ResultSet - */ - public Iterator mapToResultType(ControlBeanContext context, Method m, ResultSet resultSet, Calendar cal) { - return new ResultSetIterator(context, m, resultSet, cal); - } - - /** - * Can the ResultSet which this mapper uses be closed by the database control on return from its invoke() method? - * @return always returns false - */ - public boolean canCloseResultSet() { return false; } -} diff --git a/beehive-jdbc-control/src/main/java/org/apache/beehive/controls/system/jdbc/DefaultJndiContextFactory.java b/beehive-jdbc-control/src/main/java/org/apache/beehive/controls/system/jdbc/DefaultJndiContextFactory.java deleted file mode 100644 index c5515e4..0000000 --- a/beehive-jdbc-control/src/main/java/org/apache/beehive/controls/system/jdbc/DefaultJndiContextFactory.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ - -package org.apache.beehive.controls.system.jdbc; - -import javax.naming.InitialContext; -import javax.naming.NamingException; -import javax.naming.Context; - -/** - * Default context factory implementation. - * May be overridden in class's ConnectionDataSource annotation. - */ -class DefaultJndiContextFactory extends JdbcControl.JndiContextFactory { - - /** - * Return a Jndi InitialContext - * @return InitialContext instance - * @throws NamingException on error. - */ - public Context getContext() throws NamingException { - return (Context) new InitialContext(); - } -} diff --git a/beehive-jdbc-control/src/main/java/org/apache/beehive/controls/system/jdbc/DefaultObjectResultSetMapper.java b/beehive-jdbc-control/src/main/java/org/apache/beehive/controls/system/jdbc/DefaultObjectResultSetMapper.java deleted file mode 100644 index 72fe59b..0000000 --- a/beehive-jdbc-control/src/main/java/org/apache/beehive/controls/system/jdbc/DefaultObjectResultSetMapper.java +++ /dev/null @@ -1,123 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ - -package org.apache.beehive.controls.system.jdbc; - -import org.apache.beehive.controls.api.ControlException; -import org.apache.beehive.controls.api.context.ControlBeanContext; -import org.apache.beehive.controls.system.jdbc.JdbcControl.SQL; - -import java.lang.reflect.Method; -import java.lang.reflect.Array; -import java.sql.ResultSet; -import java.sql.ResultSetMetaData; -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.Calendar; - -/** - * Default ResultSetMapper implementation for Objects. - */ -public class DefaultObjectResultSetMapper extends AbstractResultSetMapper { - - /** - * static reference to the TypeMappingsFactory for this class - */ - protected static final TypeMappingsFactory _tmf = TypeMappingsFactory.getInstance(); - - /** - * Map the ResultSet to the method's return type. The object type returned is defined by the return type of the method. - * - * @param context A ControlBeanContext instance, see Beehive controls javadoc for additional information - * @param m Method assoicated with this call. - * @param resultSet Result set to map. - * @param cal A Calendar instance for time/date value resolution. - * @return The Object resulting from the ResultSet - */ - public Object mapToResultType(ControlBeanContext context, Method m, ResultSet resultSet, Calendar cal) { - - final Class returnType = m.getReturnType(); - final boolean isArray = returnType.isArray(); - - try { - if (isArray) { - final SQL methodSQL = context.getMethodPropertySet(m, SQL.class); - return arrayFromResultSet(resultSet, methodSQL.arrayMaxLength(), returnType, cal); - } else { - if (!resultSet.next()) { - return _tmf.fixNull(m.getReturnType()); - } - return RowMapperFactory.getRowMapper(resultSet, returnType, cal).mapRowToReturnType(); - } - } catch (SQLException e) { - throw new ControlException(e.getMessage(), e); - } - } - - // - // ////////////////////////////////// PRIVATE METHODS ////////////////////////////////////////// - // - - /** - * Invoked when the return type of the method is an array type. - * - * @param rs ResultSet to process. - * @param maxRows The maximum size of array to create, a value of 0 indicates that the array - * size will be the same as the result set size (no limit). - * @param arrayClass The class of object contained within the array - * @param cal A calendar instance to use for date/time values - * @return An array of the specified class type - * @throws SQLException On error. - */ - protected Object arrayFromResultSet(ResultSet rs, int maxRows, Class arrayClass, Calendar cal) - throws SQLException { - - ArrayList list = new ArrayList(); - Class componentType = arrayClass.getComponentType(); - RowMapper rowMapper = RowMapperFactory.getRowMapper(rs, componentType, cal); - - // a value of zero indicates that all rows from the resultset should be included. - if (maxRows == 0) { - maxRows = -1; - } - - int numRows; - boolean hasMoreRows = rs.next(); - for (numRows = 0; numRows != maxRows && hasMoreRows; numRows++) { - list.add(rowMapper.mapRowToReturnType()); - hasMoreRows = rs.next(); - } - - Object array = Array.newInstance(componentType, numRows); - try { - for (int i = 0; i < numRows; i++) { - Array.set(array, i, list.get(i)); - } - } catch (IllegalArgumentException iae) { - ResultSetMetaData md = rs.getMetaData(); - // assuming no errors in resultSetObject() this can only happen - // for single column result sets. - throw new ControlException("The declared Java type for array " + componentType.getName() - + "is incompatible with the SQL format of column " + md.getColumnName(1) - + md.getColumnTypeName(1) + "which returns objects of type + " - + list.get(0).getClass().getName()); - } - return array; - } -} diff --git a/beehive-jdbc-control/src/main/java/org/apache/beehive/controls/system/jdbc/DefaultResultSetMapper.java b/beehive-jdbc-control/src/main/java/org/apache/beehive/controls/system/jdbc/DefaultResultSetMapper.java deleted file mode 100644 index f5172ba..0000000 --- a/beehive-jdbc-control/src/main/java/org/apache/beehive/controls/system/jdbc/DefaultResultSetMapper.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ - -package org.apache.beehive.controls.system.jdbc; - -import org.apache.beehive.controls.api.context.ControlBeanContext; - -import java.lang.reflect.Method; -import java.sql.ResultSet; -import java.util.Calendar; - -/** - * Default ResultSetMapper implementation for ResultSets. - */ -public class DefaultResultSetMapper extends AbstractResultSetMapper { - - /** - * Maps a ResultSet to a ResultSet. The default implementation is a NOOP. - * - * @param context A ControlBeanContext instance. - * @param m Method assoicated with this call. - * @param resultSet Result set to map. - * @param cal A Calendar instance for resolving date/time values. - * @return An object. - */ - public Object mapToResultType(ControlBeanContext context, Method m, ResultSet resultSet, Calendar cal) { - return resultSet; - } - - /** - * Can the ResultSet which this mapper uses be closed by the database control? - * @return always false - */ - public boolean canCloseResultSet() { return false; } -} diff --git a/beehive-jdbc-control/src/main/java/org/apache/beehive/controls/system/jdbc/DefaultRowSetResultSetMapper.java b/beehive-jdbc-control/src/main/java/org/apache/beehive/controls/system/jdbc/DefaultRowSetResultSetMapper.java deleted file mode 100644 index 10a93df..0000000 --- a/beehive-jdbc-control/src/main/java/org/apache/beehive/controls/system/jdbc/DefaultRowSetResultSetMapper.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ - -package org.apache.beehive.controls.system.jdbc; - -import com.sun.rowset.CachedRowSetImpl; -import org.apache.beehive.controls.api.ControlException; -import org.apache.beehive.controls.api.context.ControlBeanContext; -import org.apache.beehive.controls.system.jdbc.JdbcControl.SQL; - -import javax.sql.RowSet; -import java.lang.reflect.Method; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.Calendar; - -/** - * Default ResultSetMapper implementation for RowSets. - */ -public class DefaultRowSetResultSetMapper extends AbstractResultSetMapper { - - /** - * Map a ResultSet to a RowSet. Type of RowSet is defined by the SQL annotation for the method. - * - * @param context A ControlBeanContext instance. - * @param m Method assoicated with this call. - * @param resultSet Result set to map. - * @param cal A Calendar instance for resolving date/time values. - * @return A RowSet object. - */ - public RowSet mapToResultType(ControlBeanContext context, Method m, ResultSet resultSet, Calendar cal) { - final SQL methodSQL = (SQL) context.getMethodPropertySet(m, SQL.class); - final int maxrows = methodSQL.maxRows(); - - try { - CachedRowSetImpl rows = new CachedRowSetImpl(); - - if (maxrows > 0) { - rows.setMaxRows(maxrows); - } - - rows.populate(resultSet); - return rows; - } catch (SQLException e) { - throw new ControlException(e.getMessage(), e); - } - } - - /** - * Can the ResultSet which this mapper uses be closed by the database control? - * - * @return always false - */ - public boolean canCloseResultSet() { return false; } -} diff --git a/beehive-jdbc-control/src/main/java/org/apache/beehive/controls/system/jdbc/DefaultXmlObjectResultSetMapper.java b/beehive-jdbc-control/src/main/java/org/apache/beehive/controls/system/jdbc/DefaultXmlObjectResultSetMapper.java deleted file mode 100644 index 3b8ed9c..0000000 --- a/beehive-jdbc-control/src/main/java/org/apache/beehive/controls/system/jdbc/DefaultXmlObjectResultSetMapper.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ - -package org.apache.beehive.controls.system.jdbc; - -import org.apache.beehive.controls.api.ControlException; -import org.apache.beehive.controls.api.context.ControlBeanContext; -import org.apache.beehive.controls.system.jdbc.JdbcControl.SQL; - -import java.lang.reflect.Method; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.Calendar; - -/** - * Default ResultSetMapper implementation for XmlObjects. - */ -public class DefaultXmlObjectResultSetMapper extends DefaultObjectResultSetMapper { - - /** - * Map a ResultSet to an XmlObject. Object type is defined by the return type of the method. - * - * @param context A ControlBeanContext instance. - * @param m Method associated with this call. - * @param resultSet Result set to map. - * @param cal A Calendar instance for resolving date/time values. - * @return An XmlObject - */ - public Object mapToResultType(ControlBeanContext context, Method m, ResultSet resultSet, Calendar cal) { - - final Class returnType = m.getReturnType(); - final boolean isArray = returnType.isArray(); - - try { - if (isArray) { - final SQL methodSQL = (SQL) context.getMethodPropertySet(m, SQL.class); - return arrayFromResultSet(resultSet, methodSQL.arrayMaxLength(), returnType, cal); - } else { - - if (!resultSet.next()) { - return _tmf.fixNull(m.getReturnType()); - } - - return RowMapperFactory.getRowMapper(resultSet, returnType, cal).mapRowToReturnType(); - } - } catch (SQLException e) { - throw new ControlException(e.getMessage(), e); - } - } -} diff --git a/beehive-jdbc-control/src/main/java/org/apache/beehive/controls/system/jdbc/JdbcControl.java b/beehive-jdbc-control/src/main/java/org/apache/beehive/controls/system/jdbc/JdbcControl.java deleted file mode 100644 index df105c6..0000000 --- a/beehive-jdbc-control/src/main/java/org/apache/beehive/controls/system/jdbc/JdbcControl.java +++ /dev/null @@ -1,641 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ - -package org.apache.beehive.controls.system.jdbc; - -import org.apache.beehive.controls.api.bean.AnnotationConstraints; -import org.apache.beehive.controls.api.bean.AnnotationMemberTypes; -import org.apache.beehive.controls.api.bean.ControlInterface; -import org.apache.beehive.controls.api.properties.PropertySet; - -import javax.naming.NamingException; -import javax.naming.Context; -import java.lang.annotation.ElementType; -import java.lang.annotation.Inherited; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; -import java.sql.Connection; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Types; -import java.sql.SQLData; -import java.util.Calendar; -import java.util.List; -import java.util.Arrays; - -/** - * Simplifies access to a relational database from your Java code using SQL commands. - * The Jdbc Control handles the work of connecting to, sending queries to, and ResultSet mapping from - * the database. You don't need to know how to use JDBC in order to use the Jdbc Control, just basic SQL. - *

    - * To use a Jdbc Control create a .jcx file (java file with a .jcx extension) which extends this interface. - * Add annotations to the jcx to tell the Jdbc Control how to connect to your database instance (either - * ConnectionDataSource or ConnectionDriver), then add methods which include SQL annotations to access the database. - */ -@ControlInterface( checker = JdbcControlChecker.class ) -public interface JdbcControl { - - - /** - * Returns a database connection to the server associated - * with the control. It is typically not necessary to call this method - * when using the control. - * - * @return A Connection a database. - */ - public Connection getConnection() throws SQLException; - - /** - * Sets the Calendar instance that should be used when setting and getting - * {@link java.sql.Date Date}, {@link java.sql.Time Time}, and - * {@link java.sql.Timestamp Timestamp} values. - * - * @see java.sql.ResultSet#getDate(int, Calendar) java.sql.ResultSet#getDate(int, Calendar) - * @see java.sql.ResultSet#getTime(int, Calendar) java.sql.ResultSet#getTime(int, Calendar) - * @see java.sql.ResultSet#getTimestamp(int, Calendar) java.sql.ResultSet#getTimestamp(int, Calendar) - * @see java.sql.PreparedStatement#setDate(int, java.sql.Date, Calendar) java.sql.PreparedStatement#setDate(int, Date, Calendar) - * @see java.sql.PreparedStatement#setTime(int, java.sql.Time, Calendar) java.sql.PreparedStatement#setTime(int, Time, Calendar) - * @see java.sql.PreparedStatement#setTimestamp(int, java.sql.Timestamp, Calendar) java.sql.PreparedStatement#setTimestamp(int, Timestamp, Calendar) - */ - public void setDataSourceCalendar(Calendar cal); - - /** - * Gets the Calendar instance used when setting and getting - * {@link java.sql.Date Date}, {@link java.sql.Time Time}, and - * {@link java.sql.Timestamp Timestamp} values. This is the Calendar - * set by the setDataSourceCalendar method. - * - * @return The Calendar instance. - */ - public Calendar getDataSourceCalendar(); - - - - -// ******************************************************************************************************************** -// ******************************************************************************************************************** -// Class-level Database Connection Annotations and Supporting Constructs -// ******************************************************************************************************************** -// ******************************************************************************************************************** - - - /** - * Abstract base class for a user defined Jndi Context factory which can be used - * as a value for the jndiContextFactory member of the ConnectionDataSource - * annotation. - */ - public static abstract class JndiContextFactory { - - /** - * Get a JNDI InitialContext instance. - * - * @return InitialContext instance - * @throws NamingException if context could not be found. - */ - public abstract Context getContext() throws NamingException; - } - - /** - * Class-level annotation for making a DataSource available for use with the Jdbc Control. Either this annotation or - * the ConnectionDriver annotation must be set for a jcx which extends the JdbcControl interface. - */ - @PropertySet(prefix = "ConnectionDataSource") - @Inherited - @AnnotationConstraints.AllowExternalOverride - @Retention(RetentionPolicy.RUNTIME) - @Target({ElementType.TYPE, ElementType.FIELD}) - public @interface ConnectionDataSource { - - /** - * The jndi name of the DataSource. This is a required element for this annotation. - */ - @AnnotationMemberTypes.JndiName(resourceType = AnnotationMemberTypes.JndiName.ResourceType.DATASOURCE) - String jndiName(); - - /** - * The name of a class which implements the IJndiContextFactory interface. This is an optional element of this annotation. - */ - @AnnotationMemberTypes.Optional - Class jndiContextFactory() default DefaultJndiContextFactory.class; - } - - - /** - * Class-level annotation for making a ConnectionDriver available for use with the Jdbc Control. Either this - * annotation or the ConnectionDataSource annotation must be set for a jcx which extends the JdbcControl interface. - * See java.sql.DatabaseConnection for additional information about the elements of this annotation. - */ - @PropertySet(prefix = "ConnectionDriver") - @Inherited - @AnnotationConstraints.AllowExternalOverride - @Retention(RetentionPolicy.RUNTIME) - @Target({ElementType.TYPE, ElementType.FIELD}) - public @interface ConnectionDriver { - - /** - * A String containing the fully qualified name of the database driver class. Required element. - */ - String databaseDriverClass(); - - /** - * A String containing the database URL to connect to. Required element. - */ - String databaseURL(); - - /** - * A String containing the user name to connect to the database as. Optional element. - */ - @AnnotationMemberTypes.Optional - String userName() default ""; - - /** - * A String containing the password associated with userName. Optional element. - */ - @AnnotationMemberTypes.Optional - String password() default ""; - - /** - * A String containing a semicolon seperated list of name/value pairs for the DatabaseConnection. - * The string must have the format of propertyName=propertyValue;propertyName=propertyValue;... - * The properties will only be used if the userName and password elements of this annotation are - * NOT set. - * - * Optional element. - */ - @AnnotationMemberTypes.Optional - String properties() default ""; - } - - - /** - * Class level annotation used to set options on the JDBC connnection. - */ - @PropertySet(prefix = "ConnectionOptions") - @Inherited - @AnnotationConstraints.AllowExternalOverride - @Retention(RetentionPolicy.RUNTIME) - @Target({ElementType.TYPE, ElementType.FIELD}) - public @interface ConnectionOptions { - - /** - * If set to true, database connection will optimize for read only queries, writes still permitted. - * Optional, defaults to false. - */ - @AnnotationMemberTypes.Optional - boolean readOnly() default false; - - /** - * Specifies ResultSet holdability for the connection. May be overridden at method level. - * Optional, defaults to jdbc driver's default setting. - */ - @AnnotationMemberTypes.Optional - HoldabilityType resultSetHoldability() default HoldabilityType.DRIVER_DEFAULT; - - /** - * Specifies type mappings for SQL user defined types (UDTs). Any type mappings set here will be used - * by the underlying JDBC Connection for UDT type mappings. These mappings can be overridden by using - * the SQL annotations methodTypeMappers element. Optional element. - */ - @AnnotationMemberTypes.Optional - TypeMapper[] typeMappers() default {}; - } - - /** - * Class / method level annotation for mapping SQL user defined types (UDTs) to and from java objects. - * The mapper class element must implement the java.sql.SQLData interface. - */ - @PropertySet(prefix = "TypeMapper") - @Inherited - @AnnotationConstraints.AllowExternalOverride - @Retention(RetentionPolicy.RUNTIME) - @Target({ElementType.TYPE, ElementType.METHOD}) - public @interface TypeMapper { - String UDTName(); - Class mapperClass(); - } - - - - -// ******************************************************************************************************************** -// ******************************************************************************************************************** -// SQL Method-level Annotation and Supporting Constructs -// ******************************************************************************************************************** -// ******************************************************************************************************************** - - /** - * This constant can be used as the value for the maxRows element of the SQL annotation. - * It indicates that all rows should be returned (i.e. no limit) - */ - public final int MAXROWS_ALL = 0; - - /** - * The default fetch size for result sets, indicates the database should determine the fetch size. - */ - public final int DEFAULT_FETCH_SIZE = 0; - - /** - * Default value for the iteratorElementType element of the - * SQL annotation. It signals that no type has been defined for the method - * (common if the method return type isn't itself an iterator) - */ - public interface UndefinedIteratorType { - } - - /** - * Default value for the resultSetMapper element of the - * SQL annotation. It signals that no type has been defined for the method. - */ - public interface UndefinedResultSetMapper { - } - - /** - * Enumeration of supported types of scrolling ResultSets - */ - public enum ScrollType { - DRIVER_DEFAULT (-1, -1), - FORWARD_ONLY (ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY), - SCROLL_INSENSITIVE (ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY), - SCROLL_SENSITIVE (ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY), - FORWARD_ONLY_UPDATABLE (ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE), - SCROLL_INSENSITIVE_UPDATABLE (ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE), - SCROLL_SENSITIVE_UPDATABLE (ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); - - private final int _type; - private final int _concurrencyType; - - ScrollType(int scrollType, int concurrencyType) { - _type = scrollType; - _concurrencyType = concurrencyType; - } - - public int getType() { return _type; } - - public int getConcurrencyType() { return _concurrencyType; } - - public String toString() { - StringBuilder sb = new StringBuilder(); - if (_type == ResultSet.TYPE_FORWARD_ONLY) { - sb.append("Foward Only, "); - } else if (_type == ResultSet.TYPE_SCROLL_INSENSITIVE) { - sb.append("Scroll Insensitive, "); - } else if (_type == ResultSet.TYPE_SCROLL_SENSITIVE) { - sb.append("Scroll Sensitive, "); - } else { - sb.append("Jdbc Driver Default Direction"); - } - - if (_concurrencyType == ResultSet.CONCUR_READ_ONLY) { - sb.append("Read Only"); - } else if (_concurrencyType == ResultSet.CONCUR_UPDATABLE) { - sb.append("Updatable"); - } else { - sb.append("Jdbc Driver Default"); - } - return sb.toString(); - } - } - - /** - * Enumeration of supported fetch directions. - */ - public enum FetchDirection { - FORWARD (ResultSet.FETCH_FORWARD), - REVERSE (ResultSet.FETCH_REVERSE), - UNKNOWN (ResultSet.FETCH_UNKNOWN); - - private final int _direction; - - FetchDirection(int direction) { - _direction = direction; - } - - public int getDirection() { return _direction; } - } - - /** - * Enumeration of supported fetch directions. - */ - public enum HoldabilityType { - DRIVER_DEFAULT (0), - HOLD_CURSORS (ResultSet.HOLD_CURSORS_OVER_COMMIT), - CLOSE_CURSORS (ResultSet.CLOSE_CURSORS_AT_COMMIT); - - private final int _holdability; - - HoldabilityType(int holdability) { - _holdability = holdability; - } - - public int getHoldability() { return _holdability; } - - public String toString() { - if (_holdability == ResultSet.HOLD_CURSORS_OVER_COMMIT) { - return "HOLD_CURSORS_OVER_COMMIT"; - } else if (_holdability == ResultSet.CLOSE_CURSORS_AT_COMMIT) { - return "CLOSE_CURSORS_AT_COMMIT"; - } else { - return "Default driver holdability"; - } - } - } - - /** - * Method-level annotation for methods in a jcx which wish to access a database instance. - */ - @PropertySet(prefix = "SQL") - @Inherited - @Retention(RetentionPolicy.RUNTIME) - @AnnotationConstraints.AllowExternalOverride - @Target({ElementType.METHOD}) - public @interface SQL { - - /** - * The SQL statement to send to the database. Required annotation element. - */ - String statement(); - - - /** - * Maximum array length. - * Optional element. - * This element has no effect on the call unless the method return type is an array. - * When used in conjunction with the maxRows element, the size of the array generated - * from the result set will be the smaller of maxRows and arrayMaxLength. - *

    - * arrayMaxLength's default value is 1024, but may be set to zero to specify that - * there is no size limit for the array generated from the ResultSet. - * Since the generated array is stored in-memory, care should be taken when dealing - * with very large ResultSets when the value of this element is set to zero. - */ - @AnnotationMemberTypes.Optional - int arrayMaxLength() default -1; - - - /** - * Max number of ResultSet rows to return. - * If used with arrayMaxLength the smaller value is used. - * Optional element, default value is no limit on number of rows returned. - */ - @AnnotationMemberTypes.Optional - int maxRows() default MAXROWS_ALL; - - - /** - * Execute the SQL statement as a batch update. - * Methods which have this element set to true must return an array of ints. - * Optional element, defaults to false. - */ - @AnnotationMemberTypes.Optional - boolean batchUpdate() default false; - - - /** - * Specify the fetch size for the ResultSet. Optional element, defaults to 0. - */ - @AnnotationMemberTypes.Optional - int fetchSize() default DEFAULT_FETCH_SIZE; - - - /** - * Specify the fetch direction for the ResultSEt. Optional element, defaults to FORWARD. - */ - @AnnotationMemberTypes.Optional - FetchDirection fetchDirection() default FetchDirection.FORWARD; - - - /** - * Return the generated key values generated by the SQL statement. Optional element, defaults to false. - */ - @AnnotationMemberTypes.Optional - boolean getGeneratedKeys() default false; - - - /** - * Specify generated key columns by column names to return when the getGeneratedKeys element is true. - * May only be set if getGeneratedKeys is set to true, otherwise a compile time error is generated. - * Optional element. - */ - @AnnotationMemberTypes.Optional - String[] generatedKeyColumnNames() default {}; - - - /** - * Specify generated key columns by column number to return when the getGeneratedKeys element is true. - * May only be set if getGeneratedKeys is set to true, otherwise a compile time error is generated - * Optional element. - */ - @AnnotationMemberTypes.Optional - int[] generatedKeyColumnIndexes() default {}; - - - /** - * Specify the holdability type for the annotated method. Overrides the holability annotation element - * of the ConnectionOptions annotation. The holdability type will be in effect for the duration of this - * method call. Optional, defaults to DRIVER_DEFAULT. - */ - @AnnotationMemberTypes.Optional - HoldabilityType resultSetHoldabilityOverride() default HoldabilityType.DRIVER_DEFAULT; - - - /** - * Specifies type mappings for SQL user defined types (UDTs). Any type mappings set here will be used - * by the underlying JDBC Connection for UDT type mappings. These type mappings will REPLACE any set on - * the JDBC connection for the duration of the method call. Optional element. - */ - @AnnotationMemberTypes.Optional - TypeMapper[] typeMappersOverride() default {}; - - - /** - * Specify the type of element to be interated over when the method's return type is java.util.Iterator. - * Optional element. - */ - @AnnotationMemberTypes.Optional - Class iteratorElementType() default UndefinedIteratorType.class; - - - /** - * Specify a custom result set mapper for the ResultSet generated by the SQL statement. - * ResultSet mappers must extend the ResultSetMapper abstract base class. If a value is specified - * it will be used to map the ResultSet of the query to the return type of the method. - * See org.apache.beehive.controls.system.jdbc.ResultSetMapper for additional information. - * Optional element. - */ - @AnnotationMemberTypes.Optional - Class resultSetMapper() default UndefinedResultSetMapper.class; - - - /** - * Specify that the ResultSet returned by the method is scrollable. Valid only for methods which - * return a ResultSet, otherwise a compile-time error will occur. Valid element values - * are defined by the ScrollType enumeration. - * Optional element, defaults to JDBC driver's default setting. - */ - @AnnotationMemberTypes.Optional - ScrollType scrollableResultSet() default ScrollType.DRIVER_DEFAULT; - } // SQL annotation declaration - - -// ******************************************************************************************************************** -// ******************************************************************************************************************** -// Inner Classes -// ******************************************************************************************************************** -// ******************************************************************************************************************** - - /** - * Nested class used for specifing parameters for a callable statement. If a method in a control extension takes an array of - * SQLParameter, the JdbcControl treats the SQL as a CallableStatement and inserts values into the statement from - * the SQLParameter array. After the CallableStatement executes, results are mapped into OUT type parameters found - * int the SQLParameter array. - * NOTE: To invoke a callable statement which does not take any arguments, an SQLParameter array of size zero must - * be passed to the JDBCControl method. - */ - public static class SQLParameter { - /** - * IN direction constant. - */ - public static final int IN = 1; - /** - * OUT direction constant. - */ - public static final int OUT = 2; - /** - * IN and OUT directions constant. - */ - public static final int INOUT = IN | OUT; - - /** - * Parameter value. For parameters of type OUT this value should be set to null. - */ - public Object value = null; - - /** - * Parameter SQL data type. See java.sql.Types. - */ - public int type = Types.NULL; - - /** - * Parameter direction. - */ - public int dir = IN; - - /** - * Create a new SQLParameter with the specified value. - * - * @param value The parameter value. - */ - public SQLParameter(Object value) { - this.value = value; - } - - /** - * Create a new SQLParameter with the specified value and SQL data type. - * - * @param value The parameter value. - * @param type SQL data type. - */ - public SQLParameter(Object value, int type) { - this(value); - this.type = type; - } - - /** - * Create a new SQLParameter with the specified value, SQL data type and direction. - * - * @param value The parameter value. - * @param type SQL data type. - * @param dir IN / OUT or INOUT - */ - public SQLParameter(Object value, int type, int dir) { - this(value, type); - this.dir = dir; - } - - /** - * Clone this parameter. - * - * @return A copy of this parameter. - */ - public Object clone() { - return new SQLParameter(value, type, dir); - } - } - - /** - * A ComplexSqlFragment can be used as a return value from a parameter reflection operation for - * return values which contain BOTH SQL text and parameters. For Example, the text portion - * could be something like 'where NAME = ?' and the parameter value is 'Fred'. - */ - public static class ComplexSqlFragment { - - protected CharSequence sql; - protected List parameters; - - /** - * Create a new SQLFragment. - */ - public ComplexSqlFragment() { - sql = null; - parameters = null; - } - - /** - * Create a new SQLFragment with the specified SQL and parameter list. - * - * @param sql SQL contents of the fragment. - * @param parameters Substitution parameters. - */ - public ComplexSqlFragment(String sql, SQLParameter[] parameters) { - this.sql = sql; - if (null != parameters) - this.parameters = Arrays.asList(parameters); - } - - /** - * Get the SQL of this fragment. - * - * @return String. - */ - public String getSQL() { - return sql.toString(); - } - - /** - * Get the parameters contained within this fragment. - * Returns a zero-based array. - * - * @return SQLParameter array. - */ - public SQLParameter[] getParameters() { - if (null == parameters) - return new SQLParameter[0]; - return parameters.toArray(new SQLParameter[parameters.size()]); - } - - /** - * Get the SQL string contained within this fragment. - * @return String. - */ - public String toString() { - return sql.toString(); - } - } -} diff --git a/beehive-jdbc-control/src/main/java/org/apache/beehive/controls/system/jdbc/JdbcControlChecker.java b/beehive-jdbc-control/src/main/java/org/apache/beehive/controls/system/jdbc/JdbcControlChecker.java deleted file mode 100644 index 88699ea..0000000 --- a/beehive-jdbc-control/src/main/java/org/apache/beehive/controls/system/jdbc/JdbcControlChecker.java +++ /dev/null @@ -1,247 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ - -package org.apache.beehive.controls.system.jdbc; - -import com.sun.mirror.apt.AnnotationProcessorEnvironment; -import com.sun.mirror.declaration.Declaration; -import com.sun.mirror.declaration.FieldDeclaration; -import com.sun.mirror.declaration.MethodDeclaration; -import com.sun.mirror.declaration.TypeDeclaration; -import com.sun.mirror.type.ArrayType; -import com.sun.mirror.type.DeclaredType; -import com.sun.mirror.type.InterfaceType; -import com.sun.mirror.type.MirroredTypeException; -import com.sun.mirror.type.PrimitiveType; -import com.sun.mirror.type.TypeMirror; -import com.sun.mirror.type.VoidType; -import org.apache.beehive.controls.api.ControlException; -import org.apache.beehive.controls.api.bean.ControlChecker; -import org.apache.beehive.controls.system.jdbc.parser.ParameterChecker; -import org.apache.beehive.controls.system.jdbc.parser.SqlParser; -import org.apache.beehive.controls.system.jdbc.parser.SqlStatement; - -import java.util.Collection; -import java.util.ResourceBundle; -import java.util.Locale; -import java.text.MessageFormat; - -/** - * Annotation checker for the JdbcControl. Invoked at compile time by the controls framework. - */ -public class JdbcControlChecker implements ControlChecker { - - private Locale _locale; - - /** - * Invoked by the control build-time infrastructure to process a declaration of - * a control extension (ie, an interface annotated with @ControlExtension), or - * a field instance of a control type. - */ - public void check(Declaration decl, AnnotationProcessorEnvironment env) { - - _locale = Locale.getDefault(); - - if (decl instanceof TypeDeclaration) { - - // - // Check method annotations - // - Collection methods = ((TypeDeclaration) decl).getMethods(); - for (MethodDeclaration method : methods) { - checkSQL(method, env); - - } - } else if (decl instanceof FieldDeclaration) { - - // - // NOOP - // - } else { - - // - // NOOP - // - } - } - - /** - * Check the SQL method annotation. Lots to check here, stop checking as soon as an error is found. - * - * @param method Method to check. - * @param env Processor env. - */ - private void checkSQL(MethodDeclaration method, AnnotationProcessorEnvironment env) { - - final JdbcControl.SQL methodSQL = method.getAnnotation(JdbcControl.SQL.class); - if (methodSQL == null) { - return; - } - - // - // check for empty SQL statement member - // - if (methodSQL.statement() == null || methodSQL.statement().length() == 0) { - env.getMessager().printError(method.getPosition(), - getResourceString("jdbccontrol.empty.statement", method.getSimpleName())); - return; - } - - // - // Make sure maxrows is not set to some negative number other than -1 - // - int maxRows = methodSQL.maxRows(); - if (maxRows < JdbcControl.MAXROWS_ALL) { - env.getMessager().printError(method.getPosition(), - getResourceString("jdbccontrol.bad.maxrows", method.getSimpleName(),maxRows)); - return; - } - - // - // - // parse the SQL - // - // - SqlParser _p = new SqlParser(); - SqlStatement _statement; - try { - _statement = _p.parse(methodSQL.statement()); - } catch (ControlException ce) { - env.getMessager().printError(method.getPosition(), getResourceString("jdbccontrol.bad.parse", - method.getSimpleName(), - ce.toString())); - return; - } - - // - // Check that the any statement element params (delimited by '{' and '}' can be - // matched to method parameter names. NOTE: This check is only valid on non-compiled files, - // once compiled to a class file method parameter names are replaced with 'arg0', 'arg1', etc. - // and cannot be used for this check. - // - try { - ParameterChecker.checkReflectionParameters(_statement, method); - } catch (ControlException e) { - env.getMessager().printError(method.getPosition(), e.getMessage()); - return; - } - - // - // check for case of generatedKeyColumns being set, when getGeneratedKeys is not set to true - // - final boolean getGeneratedKeys = methodSQL.getGeneratedKeys(); - final String[] generatedKeyColumnNames = methodSQL.generatedKeyColumnNames(); - final int[] generatedKeyIndexes = methodSQL.generatedKeyColumnIndexes(); - if (!getGeneratedKeys && (generatedKeyColumnNames.length != 0 || generatedKeyIndexes.length != 0)) { - env.getMessager().printError(method.getPosition(), - getResourceString("jdbccontrol.genkeys", method.getSimpleName())); - return; - } - - // - // check that both generatedKeyColumnNames and generatedKeyColumnIndexes are not set - // - if (generatedKeyColumnNames.length > 0 && generatedKeyIndexes.length > 0) { - env.getMessager().printError(method.getPosition(), - getResourceString("jdbccontrol.genkeycolumns", method.getSimpleName())); - - return; - } - - // - // batch update methods must return int[] - // - final boolean batchUpdate = methodSQL.batchUpdate(); - final TypeMirror returnType = method.getReturnType(); - if (batchUpdate) { - if (returnType instanceof ArrayType) { - final TypeMirror aType = ((ArrayType) returnType).getComponentType(); - if (aType instanceof PrimitiveType == false - || ((PrimitiveType) aType).getKind() != PrimitiveType.Kind.INT) { - env.getMessager().printError(method.getPosition(), - getResourceString("jdbccontrol.batchupdate", method.getSimpleName())); - return; - } - } else if (returnType instanceof VoidType == false) { - env.getMessager().printError(method.getPosition(), - getResourceString("jdbccontrol.batchupdate", method.getSimpleName())); - return; - } - - } - - // - // iterator type check match - // - if (returnType instanceof InterfaceType) { - String iName = ((InterfaceType) returnType).getDeclaration().getQualifiedName(); - if ("java.util.Iterator".equals(iName)) { - String iteratorClassName = null; - try { - // this should always except - methodSQL.iteratorElementType(); - } catch (MirroredTypeException mte) { - iteratorClassName = mte.getQualifiedName(); - } - - if ("org.apache.beehive.controls.system.jdbc.JdbcControl.UndefinedIteratorType".equals(iteratorClassName)) { - env.getMessager().printError(method.getPosition(), - getResourceString("jdbccontrol.iterator.returntype", - method.getSimpleName())); - return; - } - } - } - - // - // scrollable result set check - // - final JdbcControl.ScrollType scrollable = methodSQL.scrollableResultSet(); - switch (scrollable) { - case SCROLL_INSENSITIVE: - case SCROLL_SENSITIVE: - case SCROLL_INSENSITIVE_UPDATABLE: - case SCROLL_SENSITIVE_UPDATABLE: - case FORWARD_ONLY_UPDATABLE: - String typeName = null; - if (returnType instanceof DeclaredType) { - typeName = ((DeclaredType) returnType).getDeclaration().getQualifiedName(); - } - - if (typeName == null || !"java.sql.ResultSet".equals(typeName)) { - env.getMessager().printError(method.getPosition(), - getResourceString("jdbccontrol.scrollresultset", - method.getSimpleName())); - return; - } - case FORWARD_ONLY: - default: - break; - } - - return; - } // checkSQL - - private String getResourceString( String id, Object... args ) - { - ResourceBundle rb = ResourceBundle.getBundle(this.getClass().getPackage().getName() + ".strings", _locale ); - String pattern = rb.getString(id); - return MessageFormat.format(pattern, args); - } -} diff --git a/beehive-jdbc-control/src/main/java/org/apache/beehive/controls/system/jdbc/JdbcControlImpl.java b/beehive-jdbc-control/src/main/java/org/apache/beehive/controls/system/jdbc/JdbcControlImpl.java deleted file mode 100644 index 2a7d0c3..0000000 --- a/beehive-jdbc-control/src/main/java/org/apache/beehive/controls/system/jdbc/JdbcControlImpl.java +++ /dev/null @@ -1,506 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.system.jdbc; - -import java.lang.reflect.Method; -import java.sql.CallableStatement; -import java.sql.Connection; -import java.sql.DatabaseMetaData; -import java.sql.DriverManager; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.Calendar; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; -import java.util.Properties; -import java.util.Vector; -import javax.naming.NamingException; -import javax.naming.Context; -import javax.sql.DataSource; - -import org.apache.beehive.controls.api.ControlException; -import org.apache.beehive.controls.api.bean.ControlImplementation; -import org.apache.beehive.controls.api.bean.Extensible; -import org.apache.beehive.controls.api.context.ControlBeanContext; -import org.apache.beehive.controls.api.context.ResourceContext; -import org.apache.beehive.controls.api.context.ResourceContext.ResourceEvents; -import org.apache.beehive.controls.api.events.EventHandler; -import org.apache.beehive.controls.system.jdbc.parser.SqlParser; -import org.apache.beehive.controls.system.jdbc.parser.SqlStatement; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -/** - * The implementation class for the database controller. - */ -@ControlImplementation -public class JdbcControlImpl implements JdbcControl, Extensible, java.io.Serializable { - - // - // contexts provided by the beehive controls runtime - // - @org.apache.beehive.controls.api.context.Context - protected ControlBeanContext _context; - @org.apache.beehive.controls.api.context.Context - protected ResourceContext _resourceContext; - - protected transient Connection _connection; - protected transient ConnectionDataSource _connectionDataSource; - protected transient DataSource _dataSource; - protected transient ConnectionDriver _connectionDriver; - - private Calendar _cal; - private transient Vector _resources; - - private static final String EMPTY_STRING = ""; - private static final Log LOGGER = LogFactory.getLog(JdbcControlImpl.class); - private static final ResultSetMapper DEFAULT_MAPPER = new NewDefaultObjectResultSetMapper(); - private static final SqlParser _sqlParser = new SqlParser(); - - protected static final HashMap _resultMappers = new HashMap(); - protected static Class _xmlObjectClass; - - // - // initialize the result mapper table - // - static { - _resultMappers.put(ResultSet.class, new DefaultResultSetMapper()); - - try { - _xmlObjectClass = Class.forName("org.apache.xmlbeans.XmlObject"); - _resultMappers.put(_xmlObjectClass, new DefaultXmlObjectResultSetMapper()); - } catch (ClassNotFoundException e) { - // noop: OK if not found, just can't support mapping to an XmlObject - } - } - - /** - * Constructor - */ - public JdbcControlImpl() { } - - /** - * Invoked by the controls runtime when a new instance of this class is aquired by the runtime - */ - @EventHandler(field = "_resourceContext", eventSet = ResourceEvents.class, eventName = "onAcquire") - public void onAquire() { - - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Enter: onAquire()"); - } - - try { - getConnection(); - } catch (SQLException se) { - throw new ControlException("SQL Exception while attempting to connect to database.", se); - } - } - - /** - * Invoked by the controls runtime when an instance of this class is released by the runtime - */ - @EventHandler(field = "_resourceContext", eventSet = ResourceContext.ResourceEvents.class, eventName = "onRelease") - public void onRelease() { - - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Enter: onRelease()"); - } - - for (PreparedStatement ps : getResources()) { - try { - ps.close(); - } catch (SQLException sqe) { - } - } - getResources().clear(); - - if (_connection != null) { - try { - _connection.close(); - } catch (SQLException e) { - throw new ControlException("SQL Exception while attempting to close database connection.", e); - } - } - - _connection = null; - _connectionDataSource = null; - _connectionDriver = null; - } - - /** - * Returns a database connection to the server associated with the control. - * The connection type is specified by a ConnectionDataSource or ConnectionDriver annotation on the control class - * which extends this control. - *

    - * It is typically not necessary to call this method when using the control. - */ - public Connection getConnection() throws SQLException { - - if (_connection == null) { - - _connectionDataSource = _context.getControlPropertySet(ConnectionDataSource.class); - _connectionDriver = _context.getControlPropertySet(ConnectionDriver.class); - final ConnectionOptions connectionOptions = _context.getControlPropertySet(ConnectionOptions.class); - - if (_connectionDataSource != null && _connectionDataSource.jndiName() != null) { - _connection = getConnectionFromDataSource(_connectionDataSource.jndiName(), - _connectionDataSource.jndiContextFactory()); - - } else if (_connectionDriver != null && _connectionDriver.databaseDriverClass() != null) { - _connection = getConnectionFromDriverManager(_connectionDriver.databaseDriverClass(), - _connectionDriver.databaseURL(), - _connectionDriver.userName(), - _connectionDriver.password(), - _connectionDriver.properties()); - } else { - throw new ControlException("no @\'" + ConnectionDataSource.class.getName() - + "\' or \'" + ConnectionDriver.class.getName() + "\' property found."); - } - - // - // set any specifed connection options - // - if (connectionOptions != null) { - - if (_connection.isReadOnly() != connectionOptions.readOnly()) { - _connection.setReadOnly(connectionOptions.readOnly()); - } - - DatabaseMetaData dbMetadata = _connection.getMetaData(); - - final HoldabilityType holdability = connectionOptions.resultSetHoldability(); - if (holdability != HoldabilityType.DRIVER_DEFAULT) { - if (dbMetadata.supportsResultSetHoldability(holdability.getHoldability())) { - _connection.setHoldability(holdability.getHoldability()); - } else { - throw new ControlException("Database does not support ResultSet holdability type: " - + holdability.toString()); - } - } - - setTypeMappers(connectionOptions.typeMappers()); - } - } - - return _connection; - } - - - /** - * Called by the Controls runtime to handle calls to methods of an extensible control. - * - * @param method The extended operation that was called. - * @param args Parameters of the operation. - * @return The value that should be returned by the operation. - * @throws Throwable any exception declared on the extended operation may be - * thrown. If a checked exception is thrown from the implementation that is not declared - * on the original interface, it will be wrapped in a ControlException. - */ - public Object invoke(Method method, Object[] args) throws Throwable { - - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Enter: invoke()"); - } - assert _connection.isClosed() == false : "invoke(): JDBC Connection has been closed!!!!"; - return execPreparedStatement(method, args); - } - - /** - * Sets the {@link Calendar} used when working with time/date types - */ - public void setDataSourceCalendar(Calendar cal) { - _cal = (Calendar) cal.clone(); - } - - /** - * Returns the {@link Calendar} used when working with time/date types. - * - * @return the {@link Calendar} to use with this {@link DataSource} - */ - public Calendar getDataSourceCalendar() { - return _cal; - } - -// /////////////////////////////////////////// Protected Methods //////////////////////////////////////////// - - - /** - * Create and exec a {@link PreparedStatement} - * - * @param method the method to invoke - * @param args the method's arguments - * @return the return value from the {@link PreparedStatement} - * @throws Throwable any exception that occurs; the caller should handle these appropriately - */ - protected Object execPreparedStatement(Method method, Object[] args) - throws Throwable { - - final SQL methodSQL = (SQL) _context.getMethodPropertySet(method, SQL.class); - if (methodSQL == null || methodSQL.statement() == null) { - throw new ControlException("Method " + method.getName() + " is missing @SQL annotation"); - } - - setTypeMappers(methodSQL.typeMappersOverride()); - - // - // build the statement and execute it - // - - PreparedStatement ps = null; - try { - Class returnType = method.getReturnType(); - - SqlStatement sqlStatement = _sqlParser.parse(methodSQL.statement()); - ps = sqlStatement.createPreparedStatement(_context, _connection, _cal, method, args); - - if (LOGGER.isInfoEnabled()) { - LOGGER.info("PreparedStatement: " - + sqlStatement.createPreparedStatementString(_context, _connection, method, args)); - } - - // - // special processing for batch updates - // - if (sqlStatement.isBatchUpdate()) { - return ps.executeBatch(); - } - - // - // execute the statement - // - boolean hasResults = ps.execute(); - - - // - // callable statement processing - // - if (sqlStatement.isCallableStatement()) { - SQLParameter[] params = (SQLParameter[]) args[0]; - for (int i = 0; i < params.length; i++) { - if (params[i].dir != SQLParameter.IN) { - params[i].value = ((CallableStatement) ps).getObject(i + 1); - } - } - return null; - } - - - // - // process returned data - // - ResultSet rs = null; - int updateCount = ps.getUpdateCount(); - - if (hasResults) { - rs = ps.getResultSet(); - } - - if (sqlStatement.getsGeneratedKeys()) { - rs = ps.getGeneratedKeys(); - hasResults = true; - } - - if (!hasResults && updateCount > -1) { - boolean moreResults = ps.getMoreResults(); - int tempUpdateCount = ps.getUpdateCount(); - - while ((moreResults && rs == null) || tempUpdateCount > -1) { - if (moreResults) { - rs = ps.getResultSet(); - hasResults = true; - moreResults = false; - tempUpdateCount = -1; - } else { - moreResults = ps.getMoreResults(); - tempUpdateCount = ps.getUpdateCount(); - } - } - } - - Object returnObject = null; - if (hasResults) { - - // - // if a result set mapper was specified in the methods annotation, use it - // otherwise find the mapper for the return type in the hashmap - // - final Class resultSetMapperClass = methodSQL.resultSetMapper(); - final ResultSetMapper rsm; - if (!UndefinedResultSetMapper.class.isAssignableFrom(resultSetMapperClass)) { - if (ResultSetMapper.class.isAssignableFrom(resultSetMapperClass)) { - rsm = (ResultSetMapper) resultSetMapperClass.newInstance(); - } else { - throw new ControlException("Result set mappers must be subclasses of ResultSetMapper.class!"); - } - } else { - if (_resultMappers.containsKey(returnType)) { - rsm = _resultMappers.get(returnType); - } else { - if (_xmlObjectClass != null && _xmlObjectClass.isAssignableFrom(returnType)) { - rsm = _resultMappers.get(_xmlObjectClass); - } else { - rsm = DEFAULT_MAPPER; - } - } - } - - returnObject = rsm.mapToResultType(_context, method, rs, _cal); - if (rsm.canCloseResultSet() == false) { - getResources().add(ps); - } - - // - // empty ResultSet - // - } else { - if (returnType.equals(Void.TYPE)) { - returnObject = null; - } else if (returnType.equals(Integer.TYPE)) { - returnObject = new Integer(updateCount); - } else if (!sqlStatement.isCallableStatement()) { - throw new ControlException("Method " + method.getName() + "is DML but does not return void or int"); - } - } - return returnObject; - - } finally { - // Keep statements open that have in-use result sets - if (ps != null && !getResources().contains(ps)) { - ps.close(); - } - } - } - -// /////////////////////////////////////////// Private Methods //////////////////////////////////////////// - - /** - * Get a connection from a DataSource. - * - * @param jndiName Specifed in the subclasse's ConnectionDataSource annotation - * @param jndiFactory Specified in the subclasse's ConnectionDataSource Annotation. - * @return null if a connection cannot be established - * @throws SQLException - */ - private Connection getConnectionFromDataSource(String jndiName, - Class jndiFactory) - throws SQLException - { - - Connection con = null; - try { - JndiContextFactory jf = (JndiContextFactory) jndiFactory.newInstance(); - Context jndiContext = jf.getContext(); - _dataSource = (DataSource) jndiContext.lookup(jndiName); - con = _dataSource.getConnection(); - } catch (IllegalAccessException iae) { - throw new ControlException("IllegalAccessException:", iae); - } catch (InstantiationException ie) { - throw new ControlException("InstantiationException:", ie); - } catch (NamingException ne) { - throw new ControlException("NamingException:", ne); - } - return con; - } - - /** - * Get a JDBC connection from the DriverManager. - * - * @param dbDriverClassName Specified in the subclasse's ConnectionDriver annotation. - * @param dbUrlStr Specified in the subclasse's ConnectionDriver annotation. - * @param userName Specified in the subclasse's ConnectionDriver annotation. - * @param password Specified in the subclasse's ConnectionDriver annotation. - * @return null if a connection cannot be established. - * @throws SQLException - */ - private Connection getConnectionFromDriverManager(String dbDriverClassName, String dbUrlStr, - String userName, String password, String propertiesString) - throws SQLException - { - - Connection con = null; - try { - Class.forName(dbDriverClassName); - if (!EMPTY_STRING.equals(userName)) { - con = DriverManager.getConnection(dbUrlStr, userName, password); - } else if (!EMPTY_STRING.equals(propertiesString)) { - Properties props = parseProperties(propertiesString); - if (props == null) { - throw new ControlException("Invalid properties annotation value: " + propertiesString); - } - con = DriverManager.getConnection(dbUrlStr, props); - } else { - con = DriverManager.getConnection(dbUrlStr); - } - } catch (ClassNotFoundException e) { - throw new ControlException("Database driver class not found!", e); - } - return con; - } - - /** - * Get the Vector of Statements which we need to keep open. - * @return Vector of PreparedStatement - */ - private Vector getResources() { - if (_resources == null) { - _resources = new Vector(); - } - return _resources; - } - - /** - * Parse the propertiesString into a Properties object. The string must have the format of: - * propertyName=propertyValue;propertyName=propertyValue;... - * - * @param propertiesString - * @return A Properties instance or null if parse fails - */ - private Properties parseProperties(String propertiesString) { - Properties properties = null; - String[] propPairs = propertiesString.split(";"); - if (propPairs.length > 0) { - properties = new Properties(); - for (String propPair : propPairs) { - int eq = propPair.indexOf('='); - assert eq > -1 : "Invalid properties syntax: " + propertiesString; - properties.put(propPair.substring(0, eq), propPair.substring(eq + 1, propPair.length())); - } - } - return properties; - } - - /** - * Set any custom type mappers specifed in the annotation for the connection. Used for mapping SQL UDTs to - * java classes. - * - * @param typeMappers An array of TypeMapper. - */ - private void setTypeMappers(TypeMapper[] typeMappers) throws SQLException { - - if (typeMappers.length > 0) { - Map> mappers = _connection.getTypeMap(); - for (TypeMapper t : typeMappers) { - mappers.put(t.UDTName(), t.mapperClass()); - } - _connection.setTypeMap(mappers); - } - } -} diff --git a/beehive-jdbc-control/src/main/java/org/apache/beehive/controls/system/jdbc/NewDefaultObjectResultSetMapper.java b/beehive-jdbc-control/src/main/java/org/apache/beehive/controls/system/jdbc/NewDefaultObjectResultSetMapper.java deleted file mode 100644 index e98c468..0000000 --- a/beehive-jdbc-control/src/main/java/org/apache/beehive/controls/system/jdbc/NewDefaultObjectResultSetMapper.java +++ /dev/null @@ -1,60 +0,0 @@ -package org.apache.beehive.controls.system.jdbc; - -import org.apache.beehive.controls.api.context.ControlBeanContext; - -import java.lang.reflect.Method; -import java.lang.reflect.ParameterizedType; -import java.lang.reflect.Type; -import java.sql.ResultSet; -import java.util.*; - -/** - * Refer to org.apache.beehive.controls.system.jdbc.ResultSetMapper for how this class operates - */ -public class NewDefaultObjectResultSetMapper extends com.moparisthebest.jdbc.CaseInsensitiveMapResultSetMapper implements org.apache.beehive.controls.system.jdbc.ResultSetMapper { - public NewDefaultObjectResultSetMapper() { - super(-1); - } - - /** - * Map the ResultSet to the method's return type. The object type returned is defined by the return type of the method. - * - * @param context A ControlBeanContext instance, see Beehive controls javadoc for additional information - * @param m Method assoicated with this call. - * @param rs Result set to map. - * @param cal A Calendar instance for time/date value resolution. - * @return The Object resulting from the ResultSet - */ - @SuppressWarnings({"unchecked"}) - public Object mapToResultType(ControlBeanContext context, Method m, ResultSet rs, Calendar cal) { - final Class returnType = m.getReturnType(); - if (returnType.isArray()) { - return toArray(rs, returnType.getComponentType(), context.getMethodPropertySet(m, JdbcControl.SQL.class).arrayMaxLength(), cal); - } else if (Collection.class.isAssignableFrom(returnType)) { - return toCollection(rs, returnType, (Class) getActualTypeArguments(m)[0], context.getMethodPropertySet(m, JdbcControl.SQL.class).arrayMaxLength(), cal); - } else if (Map.class.isAssignableFrom(returnType)) { - Type[] types = getActualTypeArguments(m); - if (types[1] instanceof ParameterizedType) { // for collectionMaps - ParameterizedType pt = (ParameterizedType) types[1]; - Class collectionType = (Class) pt.getRawType(); - if (Collection.class.isAssignableFrom(collectionType)) - return toMapCollection(rs, returnType, (Class) types[0], collectionType, (Class) pt.getActualTypeArguments()[0], context.getMethodPropertySet(m, JdbcControl.SQL.class).arrayMaxLength(), cal); - } - return toMap(rs, com.moparisthebest.jdbc.ResultSetMapper.instantiateClass((Class)returnType, HashMap.class), (Class) types[0], (Class) types[1], context.getMethodPropertySet(m, JdbcControl.SQL.class).arrayMaxLength(), cal); - } else if (Iterator.class.isAssignableFrom(returnType)) { - return ListIterator.class.isAssignableFrom(returnType) ? - toListIterator(rs, (Class) getActualTypeArguments(m)[0], context.getMethodPropertySet(m, JdbcControl.SQL.class).arrayMaxLength(), cal) : - toIterator(rs, (Class) getActualTypeArguments(m)[0], context.getMethodPropertySet(m, JdbcControl.SQL.class).arrayMaxLength(), cal); - } else { - return toObject(rs, returnType, cal); - } - } - - private static Type[] getActualTypeArguments(Method m) { - return ((ParameterizedType) m.getGenericReturnType()).getActualTypeArguments(); - } - - public boolean canCloseResultSet() { - return true; - } -} diff --git a/beehive-jdbc-control/src/main/java/org/apache/beehive/controls/system/jdbc/ResultSetHashMap.java b/beehive-jdbc-control/src/main/java/org/apache/beehive/controls/system/jdbc/ResultSetHashMap.java deleted file mode 100644 index 5aff8c9..0000000 --- a/beehive-jdbc-control/src/main/java/org/apache/beehive/controls/system/jdbc/ResultSetHashMap.java +++ /dev/null @@ -1,99 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.system.jdbc; - -import java.sql.ResultSet; -import java.sql.ResultSetMetaData; -import java.sql.SQLException; -import java.util.HashMap; - -/** - * The ResultSetHashMap class extends a standard HashMap and populates it with data derived from a JDBC ResultSet. - *

    - * Note: the keys are treated case-insensitively, and therefore requests made on the map are - * case-insensitive. Any direct access to the keys will yield uppercase keys. - *

    - * Note: only the row associated with the current cursor position is used. - */ -public class ResultSetHashMap extends HashMap { - - /** - * Default constructor. - */ - ResultSetHashMap() { - super(); - } - - /** - * Constructor that initializes the map to a specific size. - * @param size the size - */ - ResultSetHashMap(int size) { - super(size); - } - - /** - * This constructor is optimized for being called in a loop. It also canonicalizes the - * column names into upper case so that values in a map can be looked up using either - * upper, lower, or mixed case strings. - * - * @param rs the ResultSet to map - * @param keys an array of key objects to store in the map - * @throws SQLException if an error occurs while reading from the ResultSet - */ - ResultSetHashMap(ResultSet rs, String[] keys) throws SQLException { - super(keys.length); - - assert keys.length == rs.getMetaData().getColumnCount() + 1; - - for (int i = 1; i < keys.length; i++) { - assert keys[i].equals(keys[i].toUpperCase()); - put(keys[i], rs.getObject(i)); - } - } - - ResultSetHashMap(ResultSet rs) throws SQLException { - super(); - ResultSetMetaData md = rs.getMetaData(); - for (int i = 1; i <= md.getColumnCount(); i++) { - put(md.getColumnName(i), rs.getObject(i)); - } - } - - public boolean containsKey(Object key) { - return super.containsKey(canonicalizeKey(key)); - } - - public Object get(Object key) { - return super.get(canonicalizeKey(key)); - } - - public Object put(String key, Object value) { - return super.put(canonicalizeKey(key), value); - } - - public Object remove(Object key) { - return super.remove(canonicalizeKey(key)); - } - - private String canonicalizeKey(Object object) { - return object == null ? null : object.toString().toUpperCase(); - } -} - diff --git a/beehive-jdbc-control/src/main/java/org/apache/beehive/controls/system/jdbc/ResultSetIterator.java b/beehive-jdbc-control/src/main/java/org/apache/beehive/controls/system/jdbc/ResultSetIterator.java deleted file mode 100644 index 35ca302..0000000 --- a/beehive-jdbc-control/src/main/java/org/apache/beehive/controls/system/jdbc/ResultSetIterator.java +++ /dev/null @@ -1,109 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.system.jdbc; - -import org.apache.beehive.controls.api.ControlException; -import org.apache.beehive.controls.api.context.ControlBeanContext; - -import java.lang.reflect.Method; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.Calendar; -import java.util.NoSuchElementException; - -/** - * Used by DefaultIteratorResultSetMapper for mapping a ResultSet to an Iterator type. - */ -public class ResultSetIterator implements java.util.Iterator { - - private final Class _returnClass; - private final ResultSet _rs; - private final RowMapper _rowMapper; - - private boolean _primed = false; - - /** - * Create a new ResultSetIterator. - * @param context A ControlBeanContext. - * @param method The annotated method. - * @param rs The ResultSet to map. - * @param cal A Calendar instance for mapping date/time values. - */ - ResultSetIterator(ControlBeanContext context, Method method, ResultSet rs, Calendar cal) { - _rs = rs; - - JdbcControl.SQL methodSQL = (JdbcControl.SQL) context.getMethodPropertySet(method, JdbcControl.SQL.class); - _returnClass = methodSQL.iteratorElementType(); - - if (_returnClass == null) { - throw new ControlException("Invalid return class declared for Iterator:" + _returnClass.getName()); - } - - _rowMapper = RowMapperFactory.getRowMapper(rs, _returnClass, cal); - } - - /** - * Does this iterater have more elements? - * @return true if there is another element - */ - public boolean hasNext() { - if (_primed) { - return true; - } - - try { - _primed = _rs.next(); - } catch (SQLException sqle) { - return false; - } - return _primed; - } - - /** - * Get the next element in the iteration. - * @return The next element in the iteration. - */ - public Object next() { - try { - if (!_primed) { - _primed = _rs.next(); - if (!_primed) { - throw new NoSuchElementException(); - } - } - // reset upon consumption - _primed = false; - return _rowMapper.mapRowToReturnType(); - } catch (SQLException e) { - // Since Iterator interface is locked, all we can do - // is put the real exception inside an expected one. - NoSuchElementException xNoSuch = new NoSuchElementException("ResultSet exception: " + e); - xNoSuch.initCause(e); - throw xNoSuch; - } - } - - /** - * Remove is currently not supported. - */ - public void remove() { - throw new UnsupportedOperationException("remove not supported"); - } -} - diff --git a/beehive-jdbc-control/src/main/java/org/apache/beehive/controls/system/jdbc/ResultSetMapper.java b/beehive-jdbc-control/src/main/java/org/apache/beehive/controls/system/jdbc/ResultSetMapper.java deleted file mode 100644 index e32852d..0000000 --- a/beehive-jdbc-control/src/main/java/org/apache/beehive/controls/system/jdbc/ResultSetMapper.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.system.jdbc; - -import org.apache.beehive.controls.api.context.ControlBeanContext; - -import java.lang.reflect.Method; -import java.sql.ResultSet; -import java.util.Calendar; - -/** - * Extend this class to create new ResultSet mappers. The extended class will be invoked by the JdbcController - * when it is time to map a ResultSet to a method's return type. - * - * ResultSet mappers are specified on a per method basis using the SQL annotation's resultSetMapper field. - */ -public interface ResultSetMapper { - - /** - * Map a ResultSet to an object type - * - * @param context A ControlBeanContext instance, see Beehive controls javadoc for additional information - * @param m Method assoicated with this call. - * @param resultSet Result set to map. - * @param cal A Calendar instance for time/date value resolution. - * @return The Object resulting from the ResultSet - */ - public Object mapToResultType(ControlBeanContext context, Method m, ResultSet resultSet, Calendar cal); - - /** - * Can the ResultSet which this mapper uses be closed by the Jdbc control? - * @return true if the ResultSet can be closed by the JdbcControl - */ - public boolean canCloseResultSet(); -} diff --git a/beehive-jdbc-control/src/main/java/org/apache/beehive/controls/system/jdbc/RowMapper.java b/beehive-jdbc-control/src/main/java/org/apache/beehive/controls/system/jdbc/RowMapper.java deleted file mode 100644 index efb4b55..0000000 --- a/beehive-jdbc-control/src/main/java/org/apache/beehive/controls/system/jdbc/RowMapper.java +++ /dev/null @@ -1,242 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ - -package org.apache.beehive.controls.system.jdbc; - -import org.apache.beehive.controls.api.ControlException; - -import java.sql.ResultSet; -import java.sql.ResultSetMetaData; -import java.sql.SQLException; -import java.util.Calendar; -import java.util.regex.Pattern; -import java.util.regex.Matcher; -import java.lang.reflect.Method; -import java.lang.reflect.Modifier; - -/** - * Abstract base class for all row mappers. - * - * RowMappers are used to map the contents of a row in a ResultSet to the return type of an annotated method. - * Supported RowMapper types include: HashMap, Map, Object, XmlObject. When a ResultSetMapper is ready to - * map a ResultSet row to an object, it requests a RowMapper for the return type of the method from the - * RowMapperFactory. - * - */ -public abstract class RowMapper { - - private static final String SETTER_NAME_REGEX = "^(set)([A-Z_]\\w*+)"; - protected static final TypeMappingsFactory _tmf = TypeMappingsFactory.getInstance(); - protected static final Pattern _setterRegex = Pattern.compile(SETTER_NAME_REGEX); - - /** ResultSet to map. */ - protected final ResultSet _resultSet; - - /** Calendar instance for date/time mappings. */ - protected final Calendar _cal; - - /** Class to map ResultSet Rows to. */ - protected final Class _returnTypeClass; - - /** - * Create a new RowMapper for the specified ResultSet and return type Class. - * @param resultSet ResultSet to map - * @param returnTypeClass Class to map ResultSet rows to. - * @param cal Calendar instance for date/time values. - */ - protected RowMapper(ResultSet resultSet, Class returnTypeClass, Calendar cal) { - _resultSet = resultSet; - _returnTypeClass = returnTypeClass; - _cal = cal; - } - - /** - * Map a ResultSet row to the return type class - * @return An instance of class. - */ - public abstract Object mapRowToReturnType(); - - - /** - * Build a String array of column names from the ResultSet. - * @return A String array containing the column names contained within the ResultSet. - * @throws SQLException on error - */ - protected String[] getKeysFromResultSet() throws SQLException { - - String[] keys; - final ResultSetMetaData md = _resultSet.getMetaData(); - final int columnCount = md.getColumnCount(); - - keys = new String[columnCount + 1]; - for (int i = 1; i <= columnCount; i++) { - keys[i] = md.getColumnName(i).toUpperCase(); - } - return keys; - } - - /** - * Determine if the given method is a java bean setter method. - * @param method Method to check - * @return True if the method is a setter method. - */ - protected boolean isSetterMethod(Method method) { - Matcher matcher = _setterRegex.matcher(method.getName()); - if (matcher.matches()) { - - if (Modifier.isStatic(method.getModifiers())) return false; - if (!Modifier.isPublic(method.getModifiers())) return false; - if (!Void.TYPE.equals(method.getReturnType())) return false; - - // method parameter checks - Class[] params = method.getParameterTypes(); - if (params.length != 1) return false; - if (TypeMappingsFactory.TYPE_UNKNOWN == _tmf.getTypeId(params[0])) return false; - - return true; - } - return false; - } - - /** - * Extract a column value from the ResultSet and return it as resultType. - * - * @param index The column index of the value to extract from the ResultSet. - * @param resultType The return type. Defined in TypeMappingsFactory. - * @return The extracted value - * @throws java.sql.SQLException on error. - */ - protected Object extractColumnValue(int index, int resultType) throws SQLException { - - switch (resultType) { - case TypeMappingsFactory.TYPE_INT: - return new Integer(_resultSet.getInt(index)); - case TypeMappingsFactory.TYPE_LONG: - return new Long(_resultSet.getLong(index)); - case TypeMappingsFactory.TYPE_FLOAT: - return new Float(_resultSet.getFloat(index)); - case TypeMappingsFactory.TYPE_DOUBLE: - return new Double(_resultSet.getDouble(index)); - case TypeMappingsFactory.TYPE_BYTE: - return new Byte(_resultSet.getByte(index)); - case TypeMappingsFactory.TYPE_SHORT: - return new Short(_resultSet.getShort(index)); - case TypeMappingsFactory.TYPE_BOOLEAN: - return _resultSet.getBoolean(index) ? Boolean.TRUE : Boolean.FALSE; - case TypeMappingsFactory.TYPE_INT_OBJ: - { - int i = _resultSet.getInt(index); - return _resultSet.wasNull() ? null : new Integer(i); - } - case TypeMappingsFactory.TYPE_LONG_OBJ: - { - long i = _resultSet.getLong(index); - return _resultSet.wasNull() ? null : new Long(i); - } - case TypeMappingsFactory.TYPE_FLOAT_OBJ: - { - float i = _resultSet.getFloat(index); - return _resultSet.wasNull() ? null : new Float(i); - } - case TypeMappingsFactory.TYPE_DOUBLE_OBJ: - { - double i = _resultSet.getDouble(index); - return _resultSet.wasNull() ? null : new Double(i); - } - case TypeMappingsFactory.TYPE_BYTE_OBJ: - { - byte i = _resultSet.getByte(index); - return _resultSet.wasNull() ? null : new Byte(i); - } - case TypeMappingsFactory.TYPE_SHORT_OBJ: - { - short i = _resultSet.getShort(index); - return _resultSet.wasNull() ? null : new Short(i); - } - case TypeMappingsFactory.TYPE_BOOLEAN_OBJ: - { - boolean i = _resultSet.getBoolean(index); - return _resultSet.wasNull() ? null : (i ? Boolean.TRUE : Boolean.FALSE); - } - case TypeMappingsFactory.TYPE_STRING: - case TypeMappingsFactory.TYPE_XMLBEAN_ENUM: - return _resultSet.getString(index); - case TypeMappingsFactory.TYPE_BIG_DECIMAL: - return _resultSet.getBigDecimal(index); - case TypeMappingsFactory.TYPE_BYTES: - return _resultSet.getBytes(index); - case TypeMappingsFactory.TYPE_TIMESTAMP: - { - if (null == _cal) - return _resultSet.getTimestamp(index); - else - return _resultSet.getTimestamp(index, _cal); - } - case TypeMappingsFactory.TYPE_TIME: - { - if (null == _cal) - return _resultSet.getTime(index); - else - return _resultSet.getTime(index, _cal); - } - case TypeMappingsFactory.TYPE_SQLDATE: - { - if (null == _cal) - return _resultSet.getDate(index); - else - return _resultSet.getDate(index, _cal); - } - case TypeMappingsFactory.TYPE_DATE: - { - // convert explicity to java.util.Date - // 12918 | knex does not return java.sql.Date properly from web service - java.sql.Timestamp ts = (null == _cal) ? _resultSet.getTimestamp(index) : _resultSet.getTimestamp(index, _cal); - if (null == ts) - return null; - return new java.util.Date(ts.getTime()); - } - case TypeMappingsFactory.TYPE_CALENDAR: - { - java.sql.Timestamp ts = (null == _cal) ? _resultSet.getTimestamp(index) : _resultSet.getTimestamp(index, _cal); - if (null == ts) - return null; - Calendar c = (null == _cal) ? Calendar.getInstance() : (Calendar) _cal.clone(); - c.setTimeInMillis(ts.getTime()); - return c; - } - case TypeMappingsFactory.TYPE_REF: - return _resultSet.getRef(index); - case TypeMappingsFactory.TYPE_BLOB: - return _resultSet.getBlob(index); - case TypeMappingsFactory.TYPE_CLOB: - return _resultSet.getClob(index); - case TypeMappingsFactory.TYPE_ARRAY: - return _resultSet.getArray(index); - case TypeMappingsFactory.TYPE_READER: - case TypeMappingsFactory.TYPE_STREAM: - throw new ControlException("streaming return types are not supported by the JdbcControl; use ResultSet instead"); - case TypeMappingsFactory.TYPE_STRUCT: - case TypeMappingsFactory.TYPE_UNKNOWN: - // JAVA_TYPE (could be any), or REF - return _resultSet.getObject(index); - default: - throw new ControlException("internal error: unknown type ID: " + Integer.toString(resultType)); - } - } -} diff --git a/beehive-jdbc-control/src/main/java/org/apache/beehive/controls/system/jdbc/RowMapperFactory.java b/beehive-jdbc-control/src/main/java/org/apache/beehive/controls/system/jdbc/RowMapperFactory.java deleted file mode 100644 index 64a35bb..0000000 --- a/beehive-jdbc-control/src/main/java/org/apache/beehive/controls/system/jdbc/RowMapperFactory.java +++ /dev/null @@ -1,171 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ - -package org.apache.beehive.controls.system.jdbc; - -import org.apache.beehive.controls.api.ControlException; - -import java.lang.reflect.Constructor; -import java.lang.reflect.InvocationTargetException; -import java.sql.ResultSet; -import java.util.Calendar; -import java.util.HashMap; -import java.util.Map; - -/** - * Factory for creating row mappers. - *

    - * Row mapper types supported by this factory include: HashMap, Map, Object, XmlObject. The factory determines the - * proper row mapper to use by checking its List of RowMappers against the type of mapping requested. When performing - * the lookup, the factory attempts to find the most specific type match. If a match can't be found the most general - * type of RowMapper is returned, RowToObjectMapper. - */ -public final class RowMapperFactory { - - private static final HashMap> _rowMappings - = new HashMap>(); - - private static Class DEFAULT_OBJ_ROWMAPPING = RowToObjectMapper.class; - - private static Class XMLOBJ_CLASS = null; - private static Class DEFAULT_XMLOBJ_ROWMAPPING = null; - private final static Class[] _params = {ResultSet.class, Class.class, Calendar.class}; - - static { - - _rowMappings.put(HashMap.class, RowToHashMapMapper.class); - _rowMappings.put(Map.class, RowToMapMapper.class); - - try { - XMLOBJ_CLASS = Class.forName("org.apache.xmlbeans.XmlObject"); - DEFAULT_XMLOBJ_ROWMAPPING = RowToXmlObjectMapper.class; - } catch (ClassNotFoundException e) { - // NOOP if apache xml beans not present - } - } - - /** - * Get a RowMapper instance which knows how to map a ResultSet row to the given return type. - * - * @param rs The ResultSet to map. - * @param returnTypeClass The class to map a ResultSet row to. - * @param cal Calendar instance for mapping date/time values. - * @return A RowMapper instance. - */ - public static RowMapper getRowMapper(ResultSet rs, Class returnTypeClass, Calendar cal) { - - Class rm = _rowMappings.get(returnTypeClass); - if (rm != null) { - return getMapper(rm, rs, returnTypeClass, cal); - } - - // - // if we made it to here, check if the default XMLObject Mapper can be used, - // otherwise use the default object mapper - // - if (XMLOBJ_CLASS != null && XMLOBJ_CLASS.isAssignableFrom(returnTypeClass)) { - return getMapper(DEFAULT_XMLOBJ_ROWMAPPING, rs, returnTypeClass, cal); - } else { - return getMapper(DEFAULT_OBJ_ROWMAPPING, rs, returnTypeClass, cal); - } - } - - /** - * Add a new row mapper to the list of available row mappers. The getRowMapper method traverses the - * list of mappers from beginning to end, checking to see if a mapper can handle the specified - * returnTypeClass. There is a default mapper which is used if a match cannot be found in the list. - * - * @param returnTypeClass Class which this mapper maps a row to. - * @param rowMapperClass The row mapper class. - */ - public static void addRowMapping(Class returnTypeClass, Class rowMapperClass) { - _rowMappings.put(returnTypeClass, rowMapperClass); - } - - /** - * Replace a row mapping. - * - * @param returnTypeClass Class which this mapper maps a row to. - * @param rowMapperClass The row mapper class. - * @return if the mapper was replaced, false mapper for returnTypeClass was not found, no action taken. - */ - public static Class replaceRowMapping(Class returnTypeClass, Class rowMapperClass) { - return _rowMappings.put(returnTypeClass, rowMapperClass); - } - - /** - * remove the row mapping for the specified class type. - * - * @param returnTypeClass - * @return the RowMapper class which was removed, null if returnTypeClass did not match any of the registered - * row mappers. - */ - public static Class removeRowMapping(Class returnTypeClass) { - return _rowMappings.remove(returnTypeClass); - } - - /** - * Sets the rowmapper for Object.class - * - * @param rowMapperClass - */ - public static Class setDefaultRowMapping(Class rowMapperClass) { - Class ret = DEFAULT_OBJ_ROWMAPPING; - DEFAULT_OBJ_ROWMAPPING = rowMapperClass; - return ret; - } - - /** - * Sets the rowmapper for XmlObject.class - * - * @param rowMapperClass - */ - public static Class setDefaultXmlRowMapping(Class mapToClass, Class rowMapperClass) { - Class ret = DEFAULT_XMLOBJ_ROWMAPPING; - DEFAULT_XMLOBJ_ROWMAPPING = rowMapperClass; - XMLOBJ_CLASS = mapToClass; - return ret; - } - - /** - * Create an instance of the RowMapper class. - * - * @param rowMapper - * @param rs ResultSet we are mapping from. - * @param returnType Class to map rows to. - * @param cal Calendar instance for date/time values. - * @return A RowMapper instance. - */ - private static RowMapper getMapper(Class rowMapper, ResultSet rs, Class returnType, Calendar cal) - { - Constructor c = null; - try { - c = rowMapper.getDeclaredConstructor(_params); - return (RowMapper) c.newInstance(new Object[]{rs, returnType, cal}); - } catch (NoSuchMethodException e) { - throw new ControlException("Failure creating new instance of RowMapper, " + e.toString(), e); - } catch (InstantiationException e) { - throw new ControlException("Failure creating new instance of RowMapper, " + e.toString(), e); - } catch (IllegalAccessException e) { - throw new ControlException("Failure creating new instance of RowMapper, " + e.toString(), e); - } catch (InvocationTargetException e) { - throw new ControlException("Failure creating new instance of RowMapper, " + e.getCause().toString(), e); - } - } -} diff --git a/beehive-jdbc-control/src/main/java/org/apache/beehive/controls/system/jdbc/RowToHashMapMapper.java b/beehive-jdbc-control/src/main/java/org/apache/beehive/controls/system/jdbc/RowToHashMapMapper.java deleted file mode 100644 index 899510e..0000000 --- a/beehive-jdbc-control/src/main/java/org/apache/beehive/controls/system/jdbc/RowToHashMapMapper.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ - -package org.apache.beehive.controls.system.jdbc; - -import org.apache.beehive.controls.api.ControlException; - -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.Calendar; - -/** - * Map a ResultSet row to a java.util.HashMap object - */ -public final class RowToHashMapMapper extends RowMapper { - - private final String[] _keys; - - - /** - * Create a new RowToHashMapMapper. - * @param resultSet ResultSet to map - * @param returnTypeClass Class to map to. - * @param cal Calendar instance for date/time mappings. - */ - RowToHashMapMapper(ResultSet resultSet, Class returnTypeClass, Calendar cal) { - super(resultSet, returnTypeClass, cal); - try { - _keys = getKeysFromResultSet(); - } catch (SQLException sql) { - throw new ControlException("RowToHashMapMapper: SQLException: " + sql.getMessage(), sql); - } - } - - /** - * Do the mapping. - * @return A ResultSetHashMap object. - * @throws ControlException on error. - */ - public Object mapRowToReturnType() { - try { - return new ResultSetHashMap(_resultSet, _keys); - } catch (SQLException e) { - throw new ControlException("Exception creating HashMap return type: ", e); - } - } -} diff --git a/beehive-jdbc-control/src/main/java/org/apache/beehive/controls/system/jdbc/RowToMapMapper.java b/beehive-jdbc-control/src/main/java/org/apache/beehive/controls/system/jdbc/RowToMapMapper.java deleted file mode 100644 index 48ec258..0000000 --- a/beehive-jdbc-control/src/main/java/org/apache/beehive/controls/system/jdbc/RowToMapMapper.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.system.jdbc; - -import org.apache.beehive.controls.api.ControlException; - -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.Collections; -import java.util.Calendar; - -/** - * Map a ResultSet row to a java.util.Map object. - */ -public final class RowToMapMapper extends RowMapper { - - private final String[] _keys; - - /** - * Create a new RowToMapMapper. - * @param resultSet ResultSet to map - * @param returnTypeClass Class to map to. - * @param cal Calendar instance for date/time mappings. - */ - RowToMapMapper(ResultSet resultSet, Class returnTypeClass, Calendar cal) { - super(resultSet, returnTypeClass, cal); - try { - _keys = getKeysFromResultSet(); - } catch (SQLException e) { - throw new ControlException("RowToMapMapper: SQLException: " + e.getMessage(), e); - } - } - - /** - * Do the mapping. - * @return A Map. - * @throws ControlException on error. - */ - public Object mapRowToReturnType() { - try { - return Collections.unmodifiableMap(new ResultSetHashMap(_resultSet, _keys)); - } catch (SQLException e) { - throw new ControlException("Exception while creating ResultSetHashMap.", e); - } - } -} diff --git a/beehive-jdbc-control/src/main/java/org/apache/beehive/controls/system/jdbc/RowToObjectMapper.java b/beehive-jdbc-control/src/main/java/org/apache/beehive/controls/system/jdbc/RowToObjectMapper.java deleted file mode 100644 index 43bdf79..0000000 --- a/beehive-jdbc-control/src/main/java/org/apache/beehive/controls/system/jdbc/RowToObjectMapper.java +++ /dev/null @@ -1,247 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ - -package org.apache.beehive.controls.system.jdbc; - -import org.apache.beehive.controls.api.ControlException; - -import java.lang.reflect.AccessibleObject; -import java.lang.reflect.Field; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.lang.reflect.Modifier; -import java.sql.ResultSet; -import java.sql.ResultSetMetaData; -import java.sql.SQLException; -import java.util.Calendar; -import java.util.HashMap; - -/** - * Map a ResultSet row to an Object. This mapper uses Java reflection to perform the mapping. The Class being mapped - * to must have setter methods which match the ResultSet column names. For example, if a column in the ResultSet - * named USERID, the object must have a setter method named setUserid(). If a setter method cannot be class fields - * are also checked, the same naming conventions applies, USERID -> userid. - */ -public class RowToObjectMapper extends RowMapper { - - private final int _columnCount; - - private AccessibleObject[] _fields; - private int[] _fieldTypes; - - private final Object[] _args = new Object[1]; - - /** - * Create a new RowToObjectMapper. - * - * @param resultSet ResultSet to map - * @param returnTypeClass Class to map to. - * @param cal Calendar instance for date/time mappings. - */ - RowToObjectMapper(ResultSet resultSet, Class returnTypeClass, Calendar cal) { - super(resultSet, returnTypeClass, cal); - - _fields = null; - - try { - _columnCount = resultSet.getMetaData().getColumnCount(); - } catch (SQLException e) { - throw new ControlException("RowToObjectMapper: SQLException: " + e.getMessage(), e); - } - } - - /** - * Do the mapping. - * - * @return An object instance. - */ - public Object mapRowToReturnType() { - - Object resultObject = null; - - // if the ResultSet only contains a single column we may be able to map directly - // to the return type -- if so we don't need to build any structures to support - // mapping - if (_columnCount == 1) { - - final int typeId = _tmf.getTypeId(_returnTypeClass); - - try { - if (typeId != TypeMappingsFactory.TYPE_UNKNOWN) { - return extractColumnValue(1, typeId); - } else { - // we still might want a single value (i.e. java.util.Date) - Object val = extractColumnValue(1, typeId); - if (_returnTypeClass.isAssignableFrom(val.getClass())) { - return val; - } - } - } catch (SQLException e) { - throw new ControlException(e.getMessage(), e); - } - } - - if (_fields == null) { - try { - getFieldMappings(); - } catch (SQLException e) { - throw new ControlException(e.getMessage(), e); - } - } - - try { - resultObject = _returnTypeClass.newInstance(); - } catch (InstantiationException e) { - throw new ControlException("InstantiationException when trying to create instance of : " - + _returnTypeClass.getName(), e); - } catch (IllegalAccessException e) { - throw new ControlException("IllegalAccessException when trying to create instance of : " - + _returnTypeClass.getName(), e); - } - - for (int i = 1; i < _fields.length; i++) { - AccessibleObject f = _fields[i]; - Object resultValue = null; - - try { - resultValue = extractColumnValue(i, _fieldTypes[i]); - if (f instanceof Field) { - ((Field) f).set(resultObject, resultValue); - } else { - _args[0] = resultValue; - ((Method) f).invoke(resultObject, _args); - } - } catch (SQLException e) { - throw new ControlException(e.getMessage(), e); - } catch (IllegalArgumentException iae) { - - try { - ResultSetMetaData md = _resultSet.getMetaData(); - if (f instanceof Field) { - throw new ControlException("The declared Java type for field " + ((Field) f).getName() - + ((Field) f).getType().toString() - + " is incompatible with the SQL format of column " + md.getColumnName(i).toString() - + md.getColumnTypeName(i).toString() - + " which returns objects of type " + resultValue.getClass().getName()); - } else { - throw new ControlException("The declared Java type for method " + ((Method) f).getName() - + ((Method) f).getParameterTypes()[0].toString() - + " is incompatible with the SQL format of column " + md.getColumnName(i).toString() - + md.getColumnTypeName(i).toString() - + " which returns objects of type " + resultValue.getClass().getName()); - } - } catch (SQLException e) { - throw new ControlException(e.getMessage(), e); - } - - } catch (IllegalAccessException e) { - if (f instanceof Field) { - throw new ControlException("IllegalAccessException when trying to access field " + ((Field) f).getName(), e); - } else { - throw new ControlException("IllegalAccessException when trying to access method " + ((Method) f).getName(), e); - } - } catch (InvocationTargetException e) { - if (f instanceof Field) { - throw new ControlException("InvocationTargetException when trying to access field " + ((Field) f).getName(), e); - } else { - throw new ControlException("InvocationTargetException when trying to access method " + ((Method) f).getName(), e); - } - } - } - return resultObject; - } - - /** - * Build the structures necessary to do the mapping - * - * @throws SQLException on error. - */ - protected void getFieldMappings() - throws SQLException { - - final String[] keys = getKeysFromResultSet(); - - // - // find fields or setters for return class - // - HashMap mapFields = new HashMap(_columnCount * 2); - for (int i = 1; i <= _columnCount; i++) { - mapFields.put(keys[i], null); - } - - // public methods - Method[] classMethods = _returnTypeClass.getMethods(); - for (Method m : classMethods) { - - if (isSetterMethod(m)) { - final String fieldName = m.getName().substring(3).toUpperCase(); - if (mapFields.containsKey(fieldName)) { - - // check for overloads - Object field = mapFields.get(fieldName); - if (field == null) { - mapFields.put(fieldName, m); - } else { - throw new ControlException("Unable to choose between overloaded methods " + m.getName() - + " on the " + _returnTypeClass.getName() + " class. Mapping is done using " - + "a case insensitive comparision of SQL ResultSet columns to field " - + "names and public setter methods on the return class."); - } - } - } - } - - // fix for 8813: include inherited and non-public fields - for (Class clazz = _returnTypeClass; clazz != null && clazz != Object.class; clazz = clazz.getSuperclass()) { - Field[] classFields = clazz.getDeclaredFields(); - for (Field f : classFields) { - if (Modifier.isStatic(f.getModifiers())) continue; - if (!Modifier.isPublic(f.getModifiers())) continue; - String fieldName = f.getName().toUpperCase(); - if (!mapFields.containsKey(fieldName)) continue; - - Object field = mapFields.get(fieldName); - if (field == null) { - mapFields.put(fieldName, f); - } - } - } - - // finally actually init the fields array - _fields = new AccessibleObject[_columnCount + 1]; - _fieldTypes = new int[_columnCount + 1]; - - for (int i = 1; i < _fields.length; i++) { - AccessibleObject f = mapFields.get(keys[i]); - if (f == null) { - throw new ControlException("Unable to map the SQL column " + keys[i] - + " to a field on the " + _returnTypeClass.getName() + - " class. Mapping is done using a case insensitive comparision of SQL ResultSet " - + "columns to field names and public setter methods on the return class."); - } - - _fields[i] = f; - if (f instanceof Field) { - _fieldTypes[i] = _tmf.getTypeId(((Field) f).getType()); - } else { - _fieldTypes[i] = _tmf.getTypeId(((Method) f).getParameterTypes()[0]); - } - } - } -} diff --git a/beehive-jdbc-control/src/main/java/org/apache/beehive/controls/system/jdbc/RowToXmlObjectMapper.java b/beehive-jdbc-control/src/main/java/org/apache/beehive/controls/system/jdbc/RowToXmlObjectMapper.java deleted file mode 100644 index fa7a312..0000000 --- a/beehive-jdbc-control/src/main/java/org/apache/beehive/controls/system/jdbc/RowToXmlObjectMapper.java +++ /dev/null @@ -1,326 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ - -package org.apache.beehive.controls.system.jdbc; - -import org.apache.beehive.controls.api.ControlException; -import org.apache.xmlbeans.SchemaProperty; -import org.apache.xmlbeans.SchemaType; -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.XmlOptions; - -import java.lang.reflect.Field; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.lang.reflect.Modifier; -import java.sql.ResultSet; -import java.sql.ResultSetMetaData; -import java.sql.SQLException; -import java.util.Calendar; -import java.util.HashMap; - -/** - * Maps a ResultSet row to an XmlObject. - */ -public class RowToXmlObjectMapper extends RowMapper { - - private final int _columnCount; - private final SchemaType _schemaType; - - private SetterMethod[] _setterMethods; - private final Object[] _args = new Object[1]; - - /** - * Create a new RowToXmlObjectMapper. - * - * @param resultSet ResultSet to map - * @param returnTypeClass Class to map to. - * @param cal Calendar instance for date/time mappings. - * @throws SQLException on error. - */ - RowToXmlObjectMapper(ResultSet resultSet, Class returnTypeClass, Calendar cal) - throws SQLException { - super(resultSet, returnTypeClass, cal); - - _columnCount = resultSet.getMetaData().getColumnCount(); - _schemaType = getSchemaType(_returnTypeClass); - _setterMethods = null; - } - - /** - * map a row from the ResultSet to an XmlObject instance - * - * @return An XmlObject instance. - */ - public Object mapRowToReturnType() { - - Object resultObject = null; - if (_columnCount == 1) { - - final int typeId = _tmf.getTypeId(_returnTypeClass); - - try { - if (typeId != TypeMappingsFactory.TYPE_UNKNOWN) { - return extractColumnValue(1, typeId); - } else { - // we still might want a single value (i.e. java.util.Date) - Object val = extractColumnValue(1, typeId); - if (_returnTypeClass.isAssignableFrom(val.getClass())) { - return val; - } - } - } catch (SQLException e) { - throw new ControlException(e.getMessage(), e); - } - } - - if (_setterMethods == null) { - try { - getResultSetMappings(); - } catch (SQLException e) { - throw new ControlException(e.getMessage(), e); - } - } - - resultObject = XmlObject.Factory.newInstance(new XmlOptions().setDocumentType(_schemaType)); - - for (int i = 1; i < _setterMethods.length; i++) { - Method setterMethod = _setterMethods[i].getSetter(); - Object resultValue = null; - - try { - resultValue = extractColumnValue(i, _setterMethods[i].getParameterType()); - - // if the setter is for an xmlbean enum type, convert the extracted resultset column - // value to the proper xmlbean enum type. All xmlbean enums are derived from the class - // StringEnumAbstractBase - if (_setterMethods[i].getParameterType() == TypeMappingsFactory.TYPE_XMLBEAN_ENUM) { - Class parameterClass = _setterMethods[i].getParameterClass(); - Method m = parameterClass.getMethod("forString", new Class[]{String.class}); - resultValue = m.invoke(null, new Object[]{resultValue}); - } - - _args[0] = resultValue; - setterMethod.invoke(resultObject, _args); - - if (_setterMethods[i].getNilable() != null) { - if (_resultSet.wasNull()) { - _setterMethods[i].getNilable().invoke(resultObject, (Object[]) null); - } - } - } catch (SQLException se) { - throw new ControlException(se.getMessage(), se); - } catch (IllegalArgumentException iae) { - try { - ResultSetMetaData md = _resultSet.getMetaData(); - throw new ControlException("The declared Java type for method " + setterMethod.getName() - + setterMethod.getParameterTypes()[0].toString() - + " is incompatible with the SQL format of column " + md.getColumnName(i).toString() - + md.getColumnTypeName(i).toString() - + " which returns objects of type " + resultValue.getClass().getName()); - } catch (SQLException e) { - throw new ControlException(e.getMessage(), e); - } - } catch (IllegalAccessException e) { - throw new ControlException("IllegalAccessException when trying to access method " + setterMethod.getName(), e); - } catch (NoSuchMethodException e) { - throw new ControlException("NoSuchMethodException when trying to map schema enum value using Enum.forString().", e); - } catch (InvocationTargetException e) { - throw new ControlException("IllegalInvocationException when trying to access method " + setterMethod.getName(), e); - } - } - return resultObject; - } - - -// ///////////////////////////////////////////////// private methods ///////////////////////////////////////////////// - - /** - * Build the necessary structures to do the mapping - * - * @throws SQLException - */ - private void getResultSetMappings() throws SQLException { - - // - // special case for XmlObject, find factory class - // - if (_schemaType.isDocumentType()) { - return; - } - - final String[] keys = getKeysFromResultSet(); - - // - // find setters for return class - // - HashMap mapFields = new HashMap(_columnCount * 2); - for (int i = 1; i <= _columnCount; i++) { - mapFields.put(keys[i], null); - } - - // public methods - Method[] classMethods = _returnTypeClass.getMethods(); - for (Method method : classMethods) { - - if (isSetterMethod(method)) { - final String fieldName = method.getName().substring(3).toUpperCase(); - if (mapFields.containsKey(fieldName)) { - mapFields.put(fieldName, method); - } - } - } - - // finally actually init the fields array - _setterMethods = new SetterMethod[_columnCount + 1]; - - for (int i = 1; i < _setterMethods.length; i++) { - Method setterMethod = mapFields.get(keys[i]); - if (setterMethod == null) { - throw new ControlException("Unable to map the SQL column " + keys[i] - + " to a field on the " + _returnTypeClass.getName() + - " class. Mapping is done using a case insensitive comparision of SQL ResultSet " - + "columns to public setter methods on the return class."); - } - - _setterMethods[i] = new SetterMethod(setterMethod); - } - } - - /** - * Build a String array of column names from the ResultSet. - * - * @return A String array containing the column names contained within the ResultSet. - * @throws SQLException on error - */ - protected String[] getKeysFromResultSet() - throws SQLException { - - String[] keys = super.getKeysFromResultSet(); - - // check schemaProperty mapping names for more accurate column->field mapping - SchemaProperty[] props = _schemaType.getElementProperties(); - for (int i = 0; i < props.length; i++) { - - int col = -1; - try { - col = _resultSet.findColumn(props[i].getName().getLocalPart()); - } catch (SQLException x) { - } - - if (col > 0) { - keys[col] = props[i].getJavaPropertyName().toUpperCase(); - } - } - return keys; - } - - /** - * Get the SchemaType for the specified class. - * - * @param returnType Class to get the SchemaType for. - * @return SchemaType - */ - private SchemaType getSchemaType(Class returnType) { - SchemaType schemaType = null; - if (XmlObject.class.isAssignableFrom(returnType)) { - try { - Field f = returnType.getField("type"); - if (SchemaType.class.isAssignableFrom(f.getType()) && Modifier.isStatic(f.getModifiers())) { - schemaType = (SchemaType) f.get(null); - } - } catch (NoSuchFieldException x) { - } catch (IllegalAccessException x) { - } - } - return schemaType; - } - - // /////////////////////////////////////////////INNER CLASSES///////////////////////////////////////////////// - - /** - * Helper class which contains setter method information. - */ - private final class SetterMethod { - private final Method _setter; - private final int _parameterType; - private final Class _parameterClass; - private final Method _nilable; - - /** - * Create a new setter method. - * - * @param setter Method instance. - */ - SetterMethod(Method setter) { - _setter = setter; - _parameterClass = _setter.getParameterTypes()[0]; - _parameterType = _tmf.getTypeId(_parameterClass); - _nilable = isNilable(); - } - - /** - * Return the setter method. - * - * @return Method - */ - Method getSetter() { return _setter; } - - /** - * Return the class of the setter method's paramater. - * - * @return Class of the setter method's param. - */ - Class getParameterClass() { return _parameterClass; } - - /** - * Get the type of the methods paramter. - * Type is defined by the TypeMappingsFactory, prefixed by TYPE_. - * - * @return int type. - */ - int getParameterType() { return _parameterType; } - - /** - * Get the nilable method for this setter. - * - * @return Method. - */ - Method getNilable() { return _nilable; } - - /** - * This takes care of the special case for xml beans return types. - * since they return primitive types even if they are nillable, we - * must explicitly call setNil after getting the column out of the resultSet. - * for that, we need to keep track of each field's setNil method. - * if the field is not nillable, it will not have a setNil method, and - * that array index will be null. - * - * @return Method - */ - private Method isNilable() { - try { - return _returnTypeClass.getMethod("setNil" + _setter.getName().substring(3), new Class[]{}); - } catch (NoSuchMethodException e) { - // NOOP - just means there is no setNil - } - return null; - } - } -} diff --git a/beehive-jdbc-control/src/main/java/org/apache/beehive/controls/system/jdbc/TypeMappingsFactory.java b/beehive-jdbc-control/src/main/java/org/apache/beehive/controls/system/jdbc/TypeMappingsFactory.java deleted file mode 100644 index b9ef24e..0000000 --- a/beehive-jdbc-control/src/main/java/org/apache/beehive/controls/system/jdbc/TypeMappingsFactory.java +++ /dev/null @@ -1,405 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.system.jdbc; - -import java.lang.reflect.Method; -import java.lang.reflect.InvocationTargetException; -import java.sql.Types; -import java.sql.Blob; -import java.sql.Clob; -import java.util.HashMap; -import java.util.Map; - -import org.apache.beehive.controls.api.ControlException; - -/** - * Currently contains all types of type mappings. Implemented using singleton pattern. - */ -public final class TypeMappingsFactory { - - /* @todo: refactor! */ - - private static TypeMappingsFactory _instance; - private static Class XMLBEANS_STRING_ENUM_ABSTRACT_BASE = null; - - static { - try { - XMLBEANS_STRING_ENUM_ABSTRACT_BASE = Class.forName("org.apache.xmlbeans.StringEnumAbstractBase"); - } catch (ClassNotFoundException e) { - // not an error, just means XmlBeans is not available - } - } - - /** - * Get an instance of this class. - * @return TypeMappingsFactory instance. - */ - public static TypeMappingsFactory getInstance() { - if (_instance == null) { - _instance = new TypeMappingsFactory(); - } - return _instance; - } - - public static final int TYPE_UNKNOWN = 0; - static final int TYPE_BYTE = 1; - static final int TYPE_SHORT = 2; - static final int TYPE_INT = 3; - static final int TYPE_LONG = 4; - static final int TYPE_FLOAT = 5; - static final int TYPE_DOUBLE = 6; - static final int TYPE_BOOLEAN = 7; - static final int TYPE_BYTE_OBJ = 8; - static final int TYPE_SHORT_OBJ = 9; - static final int TYPE_INT_OBJ = 10; - static final int TYPE_LONG_OBJ = 11; - static final int TYPE_FLOAT_OBJ = 12; - static final int TYPE_DOUBLE_OBJ = 13; - static final int TYPE_BOOLEAN_OBJ = 14; - static final int TYPE_BIG_DECIMAL = 15; - static final int TYPE_STRING = 16; - static final int TYPE_BYTES = 17; - static final int TYPE_SQLDATE = 18; - static final int TYPE_TIME = 19; - static final int TYPE_TIMESTAMP = 20; - static final int TYPE_STREAM = 21; - static final int TYPE_READER = 22; - static final int TYPE_CLOB = 23; - static final int TYPE_BLOB = 24; - static final int TYPE_ARRAY = 25; - static final int TYPE_REF = 26; - static final int TYPE_DATE = 27; - static final int TYPE_CALENDAR = 28; - static final int TYPE_STRUCT = 29; - static final int TYPE_XMLBEAN_ENUM = 30; - static final int TYPE_MAX = 31; - - private Map _primitiveDefaults; - - // - // keys in this map are the class of the method's return type, - // values are the set of constants defined above all prefixed with - // TYPE_ - // - private Map _typeMap; - private Map _typeSqlMap; - - /** - * Map a string version of sql type to sql type (java.sql.Types). - * example: "INTEGER" maps to java.sql.Types.INTEGER - */ - private Map _typeSqlNameMap; - - private static Method _methodMapGet; - - /** - * Constructor - */ - TypeMappingsFactory() { - - _primitiveDefaults = new HashMap(); - _primitiveDefaults.put(Boolean.TYPE, Boolean.FALSE); - _primitiveDefaults.put(Integer.TYPE, new Integer(0)); - _primitiveDefaults.put(Long.TYPE, new Long(0)); - _primitiveDefaults.put(Byte.TYPE, new Byte((byte) 0)); - _primitiveDefaults.put(Short.TYPE, new Short((short) 0)); - _primitiveDefaults.put(Character.TYPE, new Character('\u0000')); - _primitiveDefaults.put(Float.TYPE, new Float(0.0f)); - _primitiveDefaults.put(Double.TYPE, new Double(0.0d)); - - // Class to internal enum - _typeMap = new HashMap(TYPE_MAX * 2); - _typeMap.put(Boolean.TYPE, new Integer(TYPE_BOOLEAN)); - _typeMap.put(Integer.TYPE, new Integer(TYPE_INT)); - _typeMap.put(Long.TYPE, new Integer(TYPE_LONG)); - _typeMap.put(Byte.TYPE, new Integer(TYPE_BYTE)); - _typeMap.put(Short.TYPE, new Integer(TYPE_SHORT)); - _typeMap.put(Float.TYPE, new Integer(TYPE_FLOAT)); - _typeMap.put(Double.TYPE, new Integer(TYPE_DOUBLE)); - _typeMap.put(Boolean.class, new Integer(TYPE_BOOLEAN_OBJ)); - _typeMap.put(Integer.class, new Integer(TYPE_INT_OBJ)); - _typeMap.put(Long.class, new Integer(TYPE_LONG_OBJ)); - _typeMap.put(Byte.class, new Integer(TYPE_BYTE_OBJ)); - _typeMap.put(Short.class, new Integer(TYPE_SHORT_OBJ)); - _typeMap.put(Float.class, new Integer(TYPE_FLOAT_OBJ)); - _typeMap.put(Double.class, new Integer(TYPE_DOUBLE_OBJ)); - _typeMap.put(String.class, new Integer(TYPE_STRING)); - _typeMap.put(java.math.BigDecimal.class, new Integer(TYPE_BIG_DECIMAL)); - _typeMap.put(byte[].class, new Integer(TYPE_BYTES)); - _typeMap.put(java.sql.Timestamp.class, new Integer(TYPE_TIMESTAMP)); - _typeMap.put(java.sql.Time.class, new Integer(TYPE_TIME)); - _typeMap.put(java.sql.Date.class, new Integer(TYPE_SQLDATE)); - _typeMap.put(java.sql.Ref.class, new Integer(TYPE_REF)); - _typeMap.put(java.sql.Blob.class, new Integer(TYPE_BLOB)); - _typeMap.put(java.sql.Clob.class, new Integer(TYPE_CLOB)); - _typeMap.put(java.sql.Array.class, new Integer(TYPE_ARRAY)); - _typeMap.put(java.sql.Struct.class, new Integer(TYPE_STRUCT)); - _typeMap.put(java.io.Reader.class, new Integer(TYPE_READER)); - _typeMap.put(java.io.InputStream.class, new Integer(TYPE_STREAM)); - _typeMap.put(java.util.Date.class, new Integer(TYPE_DATE)); - _typeMap.put(java.util.Calendar.class, new Integer(TYPE_CALENDAR)); - _typeMap.put(java.util.GregorianCalendar.class, new Integer(TYPE_CALENDAR)); - if (XMLBEANS_STRING_ENUM_ABSTRACT_BASE != null) { - _typeMap.put(XMLBEANS_STRING_ENUM_ABSTRACT_BASE, new Integer(TYPE_XMLBEAN_ENUM)); - } - - // Class to java.sql.Types - _typeSqlMap = new HashMap(TYPE_MAX * 2); - _typeSqlMap.put(Boolean.TYPE, new Integer(Types.BOOLEAN)); - _typeSqlMap.put(Integer.TYPE, new Integer(Types.INTEGER)); - _typeSqlMap.put(Long.TYPE, new Integer(Types.BIGINT)); - _typeSqlMap.put(Byte.TYPE, new Integer(Types.TINYINT)); - _typeSqlMap.put(Short.TYPE, new Integer(Types.SMALLINT)); - _typeSqlMap.put(Float.TYPE, new Integer(Types.REAL)); - _typeSqlMap.put(Double.TYPE, new Integer(Types.DOUBLE)); - _typeSqlMap.put(Boolean.class, new Integer(Types.BOOLEAN)); - _typeSqlMap.put(Integer.class, new Integer(Types.INTEGER)); - _typeSqlMap.put(Long.class, new Integer(Types.BIGINT)); - _typeSqlMap.put(Byte.class, new Integer(Types.TINYINT)); - _typeSqlMap.put(Short.class, new Integer(Types.SMALLINT)); - _typeSqlMap.put(Float.class, new Integer(Types.REAL)); - _typeSqlMap.put(Double.class, new Integer(Types.DOUBLE)); - _typeSqlMap.put(String.class, new Integer(Types.VARCHAR)); - _typeSqlMap.put(java.math.BigDecimal.class, new Integer(Types.DECIMAL)); - _typeSqlMap.put(byte[].class, new Integer(Types.VARBINARY)); - _typeSqlMap.put(java.sql.Timestamp.class, new Integer(Types.TIMESTAMP)); - _typeSqlMap.put(java.sql.Time.class, new Integer(Types.TIME)); - _typeSqlMap.put(java.sql.Date.class, new Integer(Types.DATE)); - _typeSqlMap.put(java.sql.Ref.class, new Integer(Types.REF)); - _typeSqlMap.put(java.sql.Blob.class, new Integer(Types.BLOB)); - _typeSqlMap.put(java.sql.Clob.class, new Integer(Types.CLOB)); - _typeSqlMap.put(java.sql.Array.class, new Integer(Types.ARRAY)); - _typeSqlMap.put(java.sql.Struct.class, new Integer(Types.STRUCT)); - _typeSqlMap.put(java.util.Date.class, new Integer(Types.TIMESTAMP)); - _typeSqlMap.put(java.util.Calendar.class, new Integer(Types.TIMESTAMP)); - _typeSqlMap.put(java.util.GregorianCalendar.class, new Integer(Types.TIMESTAMP)); - if (XMLBEANS_STRING_ENUM_ABSTRACT_BASE != null) { - _typeSqlMap.put(XMLBEANS_STRING_ENUM_ABSTRACT_BASE, new Integer(Types.VARCHAR)); - } - - // String to java.sql.Types - _typeSqlNameMap = new HashMap(TYPE_MAX * 2); - _typeSqlNameMap.put("BIT", new Integer(Types.BIT)); - _typeSqlNameMap.put("TINYINT", new Integer(Types.TINYINT)); - _typeSqlNameMap.put("SMALLINT", new Integer(Types.SMALLINT)); - _typeSqlNameMap.put("INTEGER", new Integer(Types.INTEGER)); - _typeSqlNameMap.put("BIGINT", new Integer(Types.BIGINT)); - _typeSqlNameMap.put("FLOAT", new Integer(Types.REAL)); - _typeSqlNameMap.put("REAL", new Integer(Types.REAL)); - _typeSqlNameMap.put("DOUBLE", new Integer(Types.DOUBLE)); - _typeSqlNameMap.put("NUMERIC", new Integer(Types.NUMERIC)); - _typeSqlNameMap.put("DECIMAL", new Integer(Types.DECIMAL)); - _typeSqlNameMap.put("CHAR", new Integer(Types.CHAR)); - _typeSqlNameMap.put("VARCHAR", new Integer(Types.VARCHAR)); - _typeSqlNameMap.put("LONGVARCHAR", new Integer(Types.LONGVARCHAR)); - _typeSqlNameMap.put("DATE", new Integer(Types.DATE)); - _typeSqlNameMap.put("TIME", new Integer(Types.TIME)); - _typeSqlNameMap.put("TIMESTAMP", new Integer(Types.TIMESTAMP)); - _typeSqlNameMap.put("BINARY", new Integer(Types.BINARY)); - _typeSqlNameMap.put("VARBINARY", new Integer(Types.VARBINARY)); - _typeSqlNameMap.put("LONGVARBINARY", new Integer(Types.LONGVARBINARY)); - _typeSqlNameMap.put("NULL", new Integer(Types.NULL)); - _typeSqlNameMap.put("OTHER", new Integer(Types.OTHER)); - _typeSqlNameMap.put("JAVA_OBJECT", new Integer(Types.JAVA_OBJECT)); - _typeSqlNameMap.put("DISTINCT", new Integer(Types.DISTINCT)); - _typeSqlNameMap.put("STRUCT", new Integer(Types.STRUCT)); - _typeSqlNameMap.put("ARRAY", new Integer(Types.ARRAY)); - _typeSqlNameMap.put("BLOB", new Integer(Types.BLOB)); - _typeSqlNameMap.put("CLOB", new Integer(Types.CLOB)); - _typeSqlNameMap.put("REF", new Integer(Types.REF)); - _typeSqlNameMap.put("DATALINK", new Integer(Types.DATALINK)); - _typeSqlNameMap.put("BOOLEAN", new Integer(Types.BOOLEAN)); - - // some JAVA synonyms - _typeSqlNameMap.put("BYTE", new Integer(Types.TINYINT)); - _typeSqlNameMap.put("SHORT", new Integer(Types.SMALLINT)); - _typeSqlNameMap.put("INT", new Integer(Types.INTEGER)); - _typeSqlNameMap.put("LONG", new Integer(Types.BIGINT)); - - // cache the Map.get method for efficiency - try { - _methodMapGet = java.util.Map.class.getMethod("get", new Class[]{Object.class}); - } catch (NoSuchMethodException e) { - throw new ControlException("Can not find java.util.Map.get(Object) method"); - } - } - - /** - * Convert a type string to its SQL Type int value. - * @param type A String containing the SQL type name. - * @return The SQL type, TYPE_UNKNOWN if cannot convert. - */ - public int convertStringToSQLType(String type) { - if (_typeSqlNameMap.containsKey(type.toUpperCase())) { - return _typeSqlNameMap.get(type.toUpperCase()); - } - return TYPE_UNKNOWN; - } - - /** - * Get the SQL type of a class, start at top level class an check all super classes until match is found. - * @param classType Class to get SQL type of. - * @return Types.OTHER if cannot find SQL type. - */ - public int getSqlType(Class classType) { - - final Class origType = classType; - while (classType != null) { - Integer type = _typeSqlMap.get(classType); - if (type != null) { - return type.intValue(); - } - classType = classType.getSuperclass(); - } - - // - // special check for blobs/clobs they are interfaces not derived from - // - if (Blob.class.isAssignableFrom(origType)) { - return _typeSqlMap.get(Blob.class).intValue(); - } else if (Clob.class.isAssignableFrom(origType)) { - return _typeSqlMap.get(Clob.class).intValue(); - } - - return Types.OTHER; - } - - /** - * Get the SQL type for an object. - * @param o Object to get SQL type of. - * @return SQL type of the object, Types.OTHER if cannot classify. - */ - public int getSqlType(Object o) { - if (null == o) { - return Types.NULL; - } - return getSqlType(o.getClass()); - } - - /** - * - * @param val - * @param args - * @return the type - * @throws IllegalAccessException - * @throws InvocationTargetException - */ - public Object lookupType(Object val, Object[] args) - throws IllegalAccessException, InvocationTargetException - { - return _methodMapGet.invoke(val, args); - } - - /** - * Get the type id (defined by this class) for the given class. - * @param classType Class to get type of. - * @return Type id of class. - */ - public int getTypeId(Class classType) { - - final Class origType = classType; - while (null != classType) { - Integer typeObj = (Integer) _typeMap.get(classType); - if (null != typeObj) { - return typeObj.intValue(); - } - classType = classType.getSuperclass(); - } - - // - // special check for blobs/clobs they are interfaces not derived from - // - if (Blob.class.isAssignableFrom(origType)) { - return _typeMap.get(Blob.class).intValue(); - } else if (Clob.class.isAssignableFrom(origType)) { - return _typeMap.get(Clob.class).intValue(); - } - - return TYPE_UNKNOWN; - } - - /** - * Returns a primitive legal value as opposed to null if type is primitive. - * @param type type to get null value for. - * @return null value for specifed type. - */ - public Object fixNull(Class type) { - return type.isPrimitive() ? _primitiveDefaults.get(type) : null; - } - - /** - * Create an Object array for the given array. - * - * @param o An array. - * @return A new object array. - */ - public static Object[] toObjectArray(Object o) { - - Class clas = o.getClass().getComponentType(); - - if (null == clas) return null; - - Object[] arr; - - if (clas == Boolean.TYPE) { - boolean[] src = (boolean[]) o; - arr = new Object[src.length]; - for (int i = 0; i < src.length; i++) - arr[i] = new Boolean(src[i]); - } else if (clas == Character.TYPE) { - char[] src = (char[]) o; - arr = new Object[src.length]; - for (int i = 0; i < src.length; i++) - arr[i] = new Character(src[i]); - } else if (clas == Byte.TYPE) { - byte[] src = (byte[]) o; - arr = new Object[src.length]; - for (int i = 0; i < src.length; i++) - arr[i] = new Byte(src[i]); - } else if (clas == Short.TYPE) { - short[] src = (short[]) o; - arr = new Object[src.length]; - for (int i = 0; i < src.length; i++) - arr[i] = new Short(src[i]); - } else if (clas == Integer.TYPE) { - int[] src = (int[]) o; - arr = new Object[src.length]; - for (int i = 0; i < src.length; i++) - arr[i] = new Integer(src[i]); - } else if (clas == Long.TYPE) { - long[] src = (long[]) o; - arr = new Object[src.length]; - for (int i = 0; i < src.length; i++) - arr[i] = new Long(src[i]); - } else if (clas == Float.TYPE) { - float[] src = (float[]) o; - arr = new Object[src.length]; - for (int i = 0; i < src.length; i++) - arr[i] = new Float(src[i]); - } else if (clas == Double.TYPE) { - double[] src = (double[]) o; - arr = new Object[src.length]; - for (int i = 0; i < src.length; i++) - arr[i] = new Double(src[i]); - } else { - arr = (Object[]) o; - } - return arr; - } -} diff --git a/beehive-jdbc-control/src/main/java/org/apache/beehive/controls/system/jdbc/parser/JdbcFragment.java b/beehive-jdbc-control/src/main/java/org/apache/beehive/controls/system/jdbc/parser/JdbcFragment.java deleted file mode 100644 index 39212ea..0000000 --- a/beehive-jdbc-control/src/main/java/org/apache/beehive/controls/system/jdbc/parser/JdbcFragment.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ - -package org.apache.beehive.controls.system.jdbc.parser; - -import org.apache.beehive.controls.api.context.ControlBeanContext; - -import java.lang.reflect.Method; -import java.util.ArrayList; - -/** - * Represents an SQL escape sequence found in the SQL annotation's statement member. A JdbcFragment may - * contain child SqlFragments, typically these fragments consist of LiteralFragments and ReflectionFragments. - * Parameter substitutions may occur within the SQL escape delimiters {}. - * - * Syntactically an SQL escape sequence must match one of the following forms, where _space_ is a whitespace character: - * - *

    • {call_space_.....}
    • - *
    • {?=_space_.....}
    • - *
    • {d_space_.....}
    • - *
    • {t_space_.....}
    • - *
    • {ts_space_.....}
    • - *
    • {fn_space_.....}
    • - *
    • {escape_space_.....}
    • - *
    • {oj_space_.....}
    • - */ -public final class JdbcFragment extends SqlFragmentContainer { - - /** - * Create a new JdbcFragment - */ - JdbcFragment() { - super(); - } - - /** - * Get the prepared statement parameter value(s) contained within this fragment. - * - * @param context A ControlBeanContext instance. - * @param method The annotated method. - * @param args The method's arguments. - * - * @return null if this fragment doesn't contain a parameter value. - */ - Object[] getParameterValues(ControlBeanContext context, Method method, Object[] args) { - - ArrayList values = new ArrayList(); - for (SqlFragment sf : _children) { - if (sf.hasParamValue()) { - Object[] moreValues = sf.getParameterValues(context, method, args); - for (Object o : moreValues) { - values.add(o); - } - } - } - return values.toArray(); - } -} diff --git a/beehive-jdbc-control/src/main/java/org/apache/beehive/controls/system/jdbc/parser/LiteralFragment.java b/beehive-jdbc-control/src/main/java/org/apache/beehive/controls/system/jdbc/parser/LiteralFragment.java deleted file mode 100644 index 91493e8..0000000 --- a/beehive-jdbc-control/src/main/java/org/apache/beehive/controls/system/jdbc/parser/LiteralFragment.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ - -package org.apache.beehive.controls.system.jdbc.parser; - -import org.apache.beehive.controls.api.context.ControlBeanContext; - -import java.lang.reflect.Method; - -/** - * Represents a portion of the SQL annotation's statement member which is not within substitution delimiters. - * The parser creates LiteralFragements for portions of the SQL statement which do not require any special processing. - */ -public final class LiteralFragment extends SqlFragment { - - private final String _value; - - /** - * Create an new LiteralFragment with the specified value. - * @param value Value of this fragment. - */ - LiteralFragment(String value) { - _value = value; - } - - /** - * Get the text for a PreparedStatement - * @param context A ControlBeanContext instance - * @param m The annotated method. - * @param args The method's parameters. - * @return A String containing the literal value for this fragment. - */ - String getPreparedStatementText(ControlBeanContext context, Method m, Object[] args) { - return _value; - } - - /** - * Required for JUnit testing. - * @return The String value of this fragment. - */ - public String toString() { - return _value; - } -} diff --git a/beehive-jdbc-control/src/main/java/org/apache/beehive/controls/system/jdbc/parser/ParameterChecker.java b/beehive-jdbc-control/src/main/java/org/apache/beehive/controls/system/jdbc/parser/ParameterChecker.java deleted file mode 100644 index a5f6c30..0000000 --- a/beehive-jdbc-control/src/main/java/org/apache/beehive/controls/system/jdbc/parser/ParameterChecker.java +++ /dev/null @@ -1,196 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.system.jdbc.parser; - -import com.sun.mirror.declaration.ClassDeclaration; -import com.sun.mirror.declaration.FieldDeclaration; -import com.sun.mirror.declaration.MethodDeclaration; -import com.sun.mirror.declaration.ParameterDeclaration; -import com.sun.mirror.declaration.TypeDeclaration; -import com.sun.mirror.type.DeclaredType; -import com.sun.mirror.type.TypeMirror; -import com.sun.mirror.util.DeclarationFilter; -import org.apache.beehive.controls.api.ControlException; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.ResourceBundle; -import java.util.Locale; -import java.text.MessageFormat; - -/** - * Does compile-time checking of reflection parameteres in the SQL annotations's statement - * element vs. method parameters. Invoked by the JdbcControlChecker. - */ -public class ParameterChecker { - - /** - * Verify that all reflection parameters in the statement element can be mapped to method parameters. - * - * @param statement The parsed statement element. - * @param methodDecl The method declaration which was annotated. - */ - public static void checkReflectionParameters(SqlFragmentContainer statement, MethodDeclaration methodDecl) { - - ArrayList params = - new ArrayList(methodDecl.getParameters()); - HashMap paramMap = new HashMap(); - - // don't run these checks if this is a compiled class file (method names replaced with arg0, arg1, etc) - if (params.size() > 0 && params.get(0).getSimpleName().equals("arg0")) { - return; - } - - for (int i = 0; i < params.size(); i++) { - paramMap.put(params.get(i).getSimpleName(), params.get(i)); - } - - doCheck(statement, paramMap, methodDecl); - } - - /** - * Walk the tree of children of the statement, process all children of type ReflectionFragment. - * - * @param statement The parsed statement element. - * @param paramMap The method parameters, keyed by name. - * @param method The method declaration which was annotated. - */ - private static void doCheck(SqlFragmentContainer statement, HashMap paramMap, - final MethodDeclaration method) - { - - SqlFragment[] fragments = statement.getChildren(); - for (SqlFragment fragment : fragments) { - - // if the fragment is a container check all of its children. - if (fragment instanceof SqlFragmentContainer) { - doCheck((SqlFragmentContainer) fragment, paramMap, method); - - // reflection fragment - make sure it can be mapped using the method's param values. - } else if (fragment instanceof ReflectionFragment) { - checkReflectionFragment((ReflectionFragment) fragment, paramMap, method); - } - } - } - - /** - * Check the fragment. Must be able to resolve references like 'foo.bar' -> 'foo' where 'foo' is a method param - * of a type which contains a public getter or field named 'getBar()' or 'bar' respectively. - * - * @param fragment The reflection fragment to check. - * @param paramMap The method parameters, keyed by name. - * @param method The method declaration which was annotated. - */ - private static void checkReflectionFragment(ReflectionFragment fragment, - HashMap paramMap, MethodDeclaration method) - { - - final String[] paramNameQualifiers = ((ReflectionFragment) fragment).getParameterNameQualifiers(); - final String parameterName = ((ReflectionFragment) fragment).getParameterName(); - - if (paramMap.containsKey(paramNameQualifiers[0]) == false) { - throw new ControlException(buildMessage(parameterName, method.getSimpleName())); - } - - ParameterDeclaration tpd = paramMap.get(paramNameQualifiers[0]); - TypeMirror type = tpd.getType(); - - MethodDeclaration getterMethod = null; - FieldDeclaration field = null; - - for (int i = 1; i < paramNameQualifiers.length; i++) { - - getterMethod = null; - field = null; - - // loop through superclasses until we find a match or run out of superclasses - while (type != null) { - - if (type instanceof DeclaredType == false) { - throw new ControlException(buildMessage(parameterName, method.getSimpleName())); - } - - TypeDeclaration td = ((DeclaredType) type).getDeclaration(); - // - // abort if Map!!! No further checking can be done. - // - if (td.getQualifiedName().equals("java.util.Map")) { - return; - } - - Collection methods = - DeclarationFilter.FILTER_PUBLIC.filter(td.getMethods()); - for (MethodDeclaration m : methods) { - String upperFirst = paramNameQualifiers[i].substring(0,1).toUpperCase(); - if (paramNameQualifiers[i].length() > 1) { - upperFirst = upperFirst + paramNameQualifiers[i].substring(1); - } - if (m.getSimpleName().equals("get" + upperFirst) - || m.getSimpleName().equals("is" + upperFirst)) { - getterMethod = m; - } - } - - if (getterMethod == null) { - Collection fields = - DeclarationFilter.FILTER_PUBLIC.filter(td.getFields()); - for (FieldDeclaration fd : fields) { - if (fd.getSimpleName().equals(paramNameQualifiers[i])) { - field = fd; - } - } - } - - // try the super-class - if (getterMethod == null && field == null) { - if (td instanceof ClassDeclaration) { - type = ((ClassDeclaration) td).getSuperclass(); - continue; - } - } - - break; - } // while - - // found a match, get its type and continue within the for loop - if (getterMethod != null) { - type = getterMethod.getReturnType(); - } else if (field != null) { - type = field.getType(); - } else { - throw new ControlException(buildMessage(parameterName, method.getSimpleName())); - } - } - } - - /** - * Build the error message for this module. - * - * @param parameterName - * @param methodName - * @return The generated messge. - */ - private static String buildMessage(String parameterName, String methodName) { - - ResourceBundle rb = ResourceBundle.getBundle("org.apache.beehive.controls.system.jdbc.parser.strings", Locale.getDefault() ); - String pattern = rb.getString("jdbccontrol.invalid.param"); - return MessageFormat.format(pattern, parameterName, methodName); - } -} diff --git a/beehive-jdbc-control/src/main/java/org/apache/beehive/controls/system/jdbc/parser/ParseException.java b/beehive-jdbc-control/src/main/java/org/apache/beehive/controls/system/jdbc/parser/ParseException.java deleted file mode 100644 index 29fde9e..0000000 --- a/beehive-jdbc-control/src/main/java/org/apache/beehive/controls/system/jdbc/parser/ParseException.java +++ /dev/null @@ -1,192 +0,0 @@ -/* Generated By:JavaCC: Do not edit this line. ParseException.java Version 3.0 */ -package org.apache.beehive.controls.system.jdbc.parser; - -/** - * This exception is thrown when parse errors are encountered. - * You can explicitly create objects of this exception type by - * calling the method generateParseException in the generated - * parser. - * - * You can modify this class to customize your error reporting - * mechanisms so long as you retain the public fields. - */ -public class ParseException extends Exception { - - /** - * This constructor is used by the method "generateParseException" - * in the generated parser. Calling this constructor generates - * a new object of this type with the fields "currentToken", - * "expectedTokenSequences", and "tokenImage" set. The boolean - * flag "specialConstructor" is also set to true to indicate that - * this constructor was used to create this object. - * This constructor calls its super class with the empty string - * to force the "toString" method of parent class "Throwable" to - * print the error message in the form: - * ParseException: - */ - public ParseException(Token currentTokenVal, - int[][] expectedTokenSequencesVal, - String[] tokenImageVal - ) - { - super(""); - specialConstructor = true; - currentToken = currentTokenVal; - expectedTokenSequences = expectedTokenSequencesVal; - tokenImage = tokenImageVal; - } - - /** - * The following constructors are for use by you for whatever - * purpose you can think of. Constructing the exception in this - * manner makes the exception behave in the normal way - i.e., as - * documented in the class "Throwable". The fields "errorToken", - * "expectedTokenSequences", and "tokenImage" do not contain - * relevant information. The JavaCC generated code does not use - * these constructors. - */ - - public ParseException() { - super(); - specialConstructor = false; - } - - public ParseException(String message) { - super(message); - specialConstructor = false; - } - - /** - * This variable determines which constructor was used to create - * this object and thereby affects the semantics of the - * "getMessage" method (see below). - */ - protected boolean specialConstructor; - - /** - * This is the last token that has been consumed successfully. If - * this object has been created due to a parse error, the token - * followng this token will (therefore) be the first error token. - */ - public Token currentToken; - - /** - * Each entry in this array is an array of integers. Each array - * of integers represents a sequence of tokens (by their ordinal - * values) that is expected at this point of the parse. - */ - public int[][] expectedTokenSequences; - - /** - * This is a reference to the "tokenImage" array of the generated - * parser within which the parse error occurred. This array is - * defined in the generated ...Constants interface. - */ - public String[] tokenImage; - - /** - * This method has the standard behavior when this object has been - * created using the standard constructors. Otherwise, it uses - * "currentToken" and "expectedTokenSequences" to generate a parse - * error message and returns it. If this object has been created - * due to a parse error, and you do not catch it (it gets thrown - * from the parser), then this method is called during the printing - * of the final stack trace, and hence the correct error message - * gets displayed. - */ - public String getMessage() { - if (!specialConstructor) { - return super.getMessage(); - } - String expected = ""; - int maxSize = 0; - for (int i = 0; i < expectedTokenSequences.length; i++) { - if (maxSize < expectedTokenSequences[i].length) { - maxSize = expectedTokenSequences[i].length; - } - for (int j = 0; j < expectedTokenSequences[i].length; j++) { - expected += tokenImage[expectedTokenSequences[i][j]] + " "; - } - if (expectedTokenSequences[i][expectedTokenSequences[i].length - 1] != 0) { - expected += "..."; - } - expected += eol + " "; - } - String retval = "Encountered \""; - Token tok = currentToken.next; - for (int i = 0; i < maxSize; i++) { - if (i != 0) retval += " "; - if (tok.kind == 0) { - retval += tokenImage[0]; - break; - } - retval += add_escapes(tok.image); - tok = tok.next; - } - retval += "\" at line " + currentToken.next.beginLine + ", column " + currentToken.next.beginColumn; - retval += "." + eol; - if (expectedTokenSequences.length == 1) { - retval += "Was expecting:" + eol + " "; - } else { - retval += "Was expecting one of:" + eol + " "; - } - retval += expected; - return retval; - } - - /** - * The end of line string for this machine. - */ - protected String eol = System.getProperty("line.separator", "\n"); - - /** - * Used to convert raw characters to their escaped version - * when these raw version cannot be used as part of an ASCII - * string literal. - */ - protected String add_escapes(String str) { - StringBuffer retval = new StringBuffer(); - char ch; - for (int i = 0; i < str.length(); i++) { - switch (str.charAt(i)) - { - case 0 : - continue; - case '\b': - retval.append("\\b"); - continue; - case '\t': - retval.append("\\t"); - continue; - case '\n': - retval.append("\\n"); - continue; - case '\f': - retval.append("\\f"); - continue; - case '\r': - retval.append("\\r"); - continue; - case '\"': - retval.append("\\\""); - continue; - case '\'': - retval.append("\\\'"); - continue; - case '\\': - retval.append("\\\\"); - continue; - default: - if ((ch = str.charAt(i)) < 0x20 || ch > 0x7e) { - String s = "0000" + Integer.toString(ch, 16); - retval.append("\\u" + s.substring(s.length() - 4, s.length())); - } else { - retval.append(ch); - } - continue; - } - } - return retval.toString(); - } - -} diff --git a/beehive-jdbc-control/src/main/java/org/apache/beehive/controls/system/jdbc/parser/ReflectionFragment.java b/beehive-jdbc-control/src/main/java/org/apache/beehive/controls/system/jdbc/parser/ReflectionFragment.java deleted file mode 100644 index c227f2e..0000000 --- a/beehive-jdbc-control/src/main/java/org/apache/beehive/controls/system/jdbc/parser/ReflectionFragment.java +++ /dev/null @@ -1,300 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ - -package org.apache.beehive.controls.system.jdbc.parser; - -import org.apache.beehive.controls.api.ControlException; -import org.apache.beehive.controls.api.context.ControlBeanContext; -import org.apache.beehive.controls.system.jdbc.TypeMappingsFactory; -import org.apache.beehive.controls.system.jdbc.JdbcControl; - -import java.lang.reflect.Method; -import java.util.Map; -import java.util.regex.Pattern; - -/** - * Represents a method parameter substitution into the SQL annotation's statement member. Delimited by '{' and '}'. - * Method parameter names must exactly match the name used in the SQL statement in order for the substitution to occur. - *

      - *

      - * SQL(statement="SELECT * FROM {tableName}")
      - * public void getAll(String tableName) throws SQLException;
      - * 
      - */ -public final class ReflectionFragment extends SqlFragment { - - private static final String PREPARED_STATEMENT_SUB_MARK = "?"; - private static final Pattern s_parameterNamePattern = Pattern.compile("\\."); - - private final String _parameterName; - private final String[] _nameQualifiers; - private int _sqlDataType; - - /** - * Create a new ReflectionFragment with the specifed method parameter name. - * - * @param parameterName The name of the parameter whose value should be substituted at this location. - */ - protected ReflectionFragment(String parameterName) { - _parameterName = parameterName; - _sqlDataType = TypeMappingsFactory.TYPE_UNKNOWN; - _nameQualifiers = s_parameterNamePattern.split(_parameterName); - } - - /** - * Create a new ReflectionFragment with the specified method parameter name and SQL type. - * - * @param parameterName The name of the parameter whose value should be substituted at this location. - * @param sqlDataType A String specifing the SQL data type for this parameter. - */ - protected ReflectionFragment(String parameterName, String sqlDataType) { - this(parameterName); - if (sqlDataType != null) { - _sqlDataType = TypeMappingsFactory.getInstance().convertStringToSQLType(sqlDataType); - } - } - - /** - * Return text generated by this fragment for a PreparedStatement - * - * @param context A ControlBeanContext instance. - * @param m The annotated method. - * @param args The method's parameters - * @return Always returns a PREPARED_STATEMENT_SUB_MARK - */ - protected String getPreparedStatementText(ControlBeanContext context, Method m, Object[] args) { - // this reflection fragment may resolve to a JdbcControl.ComplexSqlFragment - // if so it changes the behavior a bit. - Object val = getParameterValue(context, m, args); - if (val instanceof JdbcControl.ComplexSqlFragment) { - return ((JdbcControl.ComplexSqlFragment)val).getSQL(); - } else { - return PREPARED_STATEMENT_SUB_MARK; - } - } - - /** - * A reflection fragment may evaluate to an JdbcControl.ComplexSqlFragment type, - * which requires additional steps to evaluate after reflection. - * - * @param context Control bean context. - * @param m Method. - * @param args Method args. - * @return true or false. - */ - protected boolean hasComplexValue(ControlBeanContext context, Method m, Object[] args) { - Object val = getParameterValue(context, m, args); - return val instanceof JdbcControl.ComplexSqlFragment; - } - - /** - * Always true for ReflectionFragment. - * - * @return true - */ - protected boolean hasParamValue() { return true; } - - /** - * Get the parameter name (as specified in the SQL statement). - * - * @return The parameter name. - */ - protected String getParameterName() { return _parameterName; } - - /** - * Get a copy of the array of parameter name qualifiers. - * - * @return An array of parameter name qualifiers. - */ - protected String[] getParameterNameQualifiers() { - String[] nameQualifiersCopy = new String[_nameQualifiers.length]; - System.arraycopy(_nameQualifiers, 0, nameQualifiersCopy, 0, _nameQualifiers.length); - return nameQualifiersCopy; - } - - /** - * Get the SQL data type of this param. - * - * @return The SQL data type for this param. - */ - protected int getParamSqlDataType() { return _sqlDataType; } - - /** - * For JUnit testing. - * - * @return The String value of this fragment. - */ - public String toString() { return PREPARED_STATEMENT_SUB_MARK; } - - /** - * Get the value of this parameter. - * - * @param context ControlBeanContext instance to evaluate the parameter's value against. - * @param method Method instance to evaluate against. - * @param args Method argument values - * @return All parameter object values contained within this fragment - */ - protected Object[] getParameterValues(ControlBeanContext context, Method method, Object[] args) { - - Object value = getParameterValue(context, method, args); - if (value instanceof JdbcControl.ComplexSqlFragment) { - JdbcControl.SQLParameter[] params = ((JdbcControl.ComplexSqlFragment)value).getParameters(); - Object[] values = new Object[params.length]; - for (int i = 0; i < params.length; i++) { - values[i] = params[i].value; - } - return values; - } - return new Object[]{value}; - } - - // - // /////////////////////////////////////////////// PRIVATE METHODS ///////////////////////////////////////////// - // - - /** - * Get the value from the method param. - * @param method - * @param args - * @return Value of reflected method param. - */ - private Object getParameterValue(ControlBeanContext context, Method method, Object[] args) { - Object value; - try { - value = context.getParameterValue(method, _nameQualifiers[0], args); - } catch (IllegalArgumentException iae) { - throw new ControlException("Invalid argument name in SQL statement: " + _nameQualifiers[0], iae); - } - - for (int i = 1; i < _nameQualifiers.length; i++) { - // handle maps, properties, and fields... - value = extractValue(value, _nameQualifiers[i - 1], _nameQualifiers[i]); - } - return value; - } - - /** - * Get the value from the referenced method parameter using java reflection - * - * @param aValue - * @param aName - * @param bName - * @return The value - */ - private Object extractValue(Object aValue, String aName, String bName) { - - Class aClass = aValue.getClass(); - Object value; - - // - // a.isB() or a.getB() - // - String bNameCapped = Character.toUpperCase(bName.charAt(0)) + bName.substring(1); - Method getMethod = null; - Class retType; - - // - // try a.isB() first, if found verify that a.isB() returns a boolean value, - // and that there is not also a a.getB() method - if there is except - // - try { - - getMethod = aClass.getMethod("is" + bNameCapped, (Class[]) null); - retType = getMethod.getReturnType(); - if (!(retType.equals(Boolean.class) || - retType.equals(Boolean.TYPE))) { - // only boolean returns can be isB() - getMethod = null; - } else { - /** - * make sure ("get" + bNameCapped) does not exist as well - * see CR216159 - */ - boolean getMethodFound = true; - try { - aClass.getMethod("get" + bNameCapped, (Class[])null); - } catch (NoSuchMethodException e) { - getMethodFound = false; - } - - if (getMethodFound) { - throw new ControlException("Colliding field accsessors in user defined class '" - + aClass.getName() + "' for field '" + bName - + "'. Please use is for boolean fields and get name for other datatypes."); - } - } - } catch (NoSuchMethodException e) { - // ignore - } - - // - // try a.getB() if a.isB() was not found. - // - if (getMethod == null) { - try { - getMethod = aClass.getMethod("get" + bNameCapped, (Class[])null); - } catch (NoSuchMethodException e) { - // ignore - } - } - - if (getMethod != null) { - // OK- a.getB() - try { - value = getMethod.invoke(aValue, (Object[]) null); - } catch (IllegalAccessException e) { - throw new ControlException("Unable to access public method: " + e.toString()); - } catch (java.lang.reflect.InvocationTargetException e) { - throw new ControlException("Exception thrown when executing : " + getMethod.getName() + "() to use as parameter"); - } - return value; - } - - // - // try a.b - // - - try { - value = aClass.getField(bName).get(aValue); - return value; - } catch (NoSuchFieldException e) { - // ignore - } catch (IllegalAccessException e) { - // ignore - } - - // - // try a.get(b) - // - - if (aValue instanceof Map) { - try { - value = TypeMappingsFactory.getInstance().lookupType(aValue, new Object[]{bName}); - return value; - } catch (Exception mapex) { - throw new ControlException("Exception thrown when executing Map.get() to resolve parameter" + mapex.toString()); - } - } - - // no other options... - throw new ControlException("Illegal argument in SQL statement: " + _parameterName - + "; unable to find suitable method of retrieving property " + bName - + " out of object " + aName + "."); - } -} diff --git a/beehive-jdbc-control/src/main/java/org/apache/beehive/controls/system/jdbc/parser/SimpleCharStream.java b/beehive-jdbc-control/src/main/java/org/apache/beehive/controls/system/jdbc/parser/SimpleCharStream.java deleted file mode 100644 index fb99fc7..0000000 --- a/beehive-jdbc-control/src/main/java/org/apache/beehive/controls/system/jdbc/parser/SimpleCharStream.java +++ /dev/null @@ -1,401 +0,0 @@ -/* Generated By:JavaCC: Do not edit this line. SimpleCharStream.java Version 3.0 */ -package org.apache.beehive.controls.system.jdbc.parser; - -/** - * An implementation of interface CharStream, where the stream is assumed to - * contain only ASCII characters (without unicode processing). - */ - -public class SimpleCharStream -{ - public static final boolean staticFlag = false; - int bufsize; - int available; - int tokenBegin; - public int bufpos = -1; - protected int bufline[]; - protected int bufcolumn[]; - - protected int column = 0; - protected int line = 1; - - protected boolean prevCharIsCR = false; - protected boolean prevCharIsLF = false; - - protected java.io.Reader inputStream; - - protected char[] buffer; - protected int maxNextCharInd = 0; - protected int inBuf = 0; - - protected void ExpandBuff(boolean wrapAround) - { - char[] newbuffer = new char[bufsize + 2048]; - int newbufline[] = new int[bufsize + 2048]; - int newbufcolumn[] = new int[bufsize + 2048]; - - try - { - if (wrapAround) - { - System.arraycopy(buffer, tokenBegin, newbuffer, 0, bufsize - tokenBegin); - System.arraycopy(buffer, 0, newbuffer, - bufsize - tokenBegin, bufpos); - buffer = newbuffer; - - System.arraycopy(bufline, tokenBegin, newbufline, 0, bufsize - tokenBegin); - System.arraycopy(bufline, 0, newbufline, bufsize - tokenBegin, bufpos); - bufline = newbufline; - - System.arraycopy(bufcolumn, tokenBegin, newbufcolumn, 0, bufsize - tokenBegin); - System.arraycopy(bufcolumn, 0, newbufcolumn, bufsize - tokenBegin, bufpos); - bufcolumn = newbufcolumn; - - maxNextCharInd = (bufpos += (bufsize - tokenBegin)); - } - else - { - System.arraycopy(buffer, tokenBegin, newbuffer, 0, bufsize - tokenBegin); - buffer = newbuffer; - - System.arraycopy(bufline, tokenBegin, newbufline, 0, bufsize - tokenBegin); - bufline = newbufline; - - System.arraycopy(bufcolumn, tokenBegin, newbufcolumn, 0, bufsize - tokenBegin); - bufcolumn = newbufcolumn; - - maxNextCharInd = (bufpos -= tokenBegin); - } - } - catch (Throwable t) - { - throw new Error(t.getMessage()); - } - - - bufsize += 2048; - available = bufsize; - tokenBegin = 0; - } - - protected void FillBuff() throws java.io.IOException - { - if (maxNextCharInd == available) - { - if (available == bufsize) - { - if (tokenBegin > 2048) - { - bufpos = maxNextCharInd = 0; - available = tokenBegin; - } - else if (tokenBegin < 0) - bufpos = maxNextCharInd = 0; - else - ExpandBuff(false); - } - else if (available > tokenBegin) - available = bufsize; - else if ((tokenBegin - available) < 2048) - ExpandBuff(true); - else - available = tokenBegin; - } - - int i; - try { - if ((i = inputStream.read(buffer, maxNextCharInd, - available - maxNextCharInd)) == -1) - { - inputStream.close(); - throw new java.io.IOException(); - } - else - maxNextCharInd += i; - return; - } - catch(java.io.IOException e) { - --bufpos; - backup(0); - if (tokenBegin == -1) - tokenBegin = bufpos; - throw e; - } - } - - public char BeginToken() throws java.io.IOException - { - tokenBegin = -1; - char c = readChar(); - tokenBegin = bufpos; - - return c; - } - - protected void UpdateLineColumn(char c) - { - column++; - - if (prevCharIsLF) - { - prevCharIsLF = false; - line += (column = 1); - } - else if (prevCharIsCR) - { - prevCharIsCR = false; - if (c == '\n') - { - prevCharIsLF = true; - } - else - line += (column = 1); - } - - switch (c) - { - case '\r' : - prevCharIsCR = true; - break; - case '\n' : - prevCharIsLF = true; - break; - case '\t' : - column--; - column += (8 - (column & 07)); - break; - default : - break; - } - - bufline[bufpos] = line; - bufcolumn[bufpos] = column; - } - - public char readChar() throws java.io.IOException - { - if (inBuf > 0) - { - --inBuf; - - if (++bufpos == bufsize) - bufpos = 0; - - return buffer[bufpos]; - } - - if (++bufpos >= maxNextCharInd) - FillBuff(); - - char c = buffer[bufpos]; - - UpdateLineColumn(c); - return (c); - } - - /** - * @deprecated - * @see #getEndColumn - */ - - public int getColumn() { - return bufcolumn[bufpos]; - } - - /** - * @deprecated - * @see #getEndLine - */ - - public int getLine() { - return bufline[bufpos]; - } - - public int getEndColumn() { - return bufcolumn[bufpos]; - } - - public int getEndLine() { - return bufline[bufpos]; - } - - public int getBeginColumn() { - return bufcolumn[tokenBegin]; - } - - public int getBeginLine() { - return bufline[tokenBegin]; - } - - public void backup(int amount) { - - inBuf += amount; - if ((bufpos -= amount) < 0) - bufpos += bufsize; - } - - public SimpleCharStream(java.io.Reader dstream, int startline, - int startcolumn, int buffersize) - { - inputStream = dstream; - line = startline; - column = startcolumn - 1; - - available = bufsize = buffersize; - buffer = new char[buffersize]; - bufline = new int[buffersize]; - bufcolumn = new int[buffersize]; - } - - public SimpleCharStream(java.io.Reader dstream, int startline, - int startcolumn) - { - this(dstream, startline, startcolumn, 4096); - } - - public SimpleCharStream(java.io.Reader dstream) - { - this(dstream, 1, 1, 4096); - } - public void ReInit(java.io.Reader dstream, int startline, - int startcolumn, int buffersize) - { - inputStream = dstream; - line = startline; - column = startcolumn - 1; - - if (buffer == null || buffersize != buffer.length) - { - available = bufsize = buffersize; - buffer = new char[buffersize]; - bufline = new int[buffersize]; - bufcolumn = new int[buffersize]; - } - prevCharIsLF = prevCharIsCR = false; - tokenBegin = inBuf = maxNextCharInd = 0; - bufpos = -1; - } - - public void ReInit(java.io.Reader dstream, int startline, - int startcolumn) - { - ReInit(dstream, startline, startcolumn, 4096); - } - - public void ReInit(java.io.Reader dstream) - { - ReInit(dstream, 1, 1, 4096); - } - public SimpleCharStream(java.io.InputStream dstream, int startline, - int startcolumn, int buffersize) - { - this(new java.io.InputStreamReader(dstream), startline, startcolumn, 4096); - } - - public SimpleCharStream(java.io.InputStream dstream, int startline, - int startcolumn) - { - this(dstream, startline, startcolumn, 4096); - } - - public SimpleCharStream(java.io.InputStream dstream) - { - this(dstream, 1, 1, 4096); - } - - public void ReInit(java.io.InputStream dstream, int startline, - int startcolumn, int buffersize) - { - ReInit(new java.io.InputStreamReader(dstream), startline, startcolumn, 4096); - } - - public void ReInit(java.io.InputStream dstream) - { - ReInit(dstream, 1, 1, 4096); - } - public void ReInit(java.io.InputStream dstream, int startline, - int startcolumn) - { - ReInit(dstream, startline, startcolumn, 4096); - } - public String GetImage() - { - if (bufpos >= tokenBegin) - return new String(buffer, tokenBegin, bufpos - tokenBegin + 1); - else - return new String(buffer, tokenBegin, bufsize - tokenBegin) + - new String(buffer, 0, bufpos + 1); - } - - public char[] GetSuffix(int len) - { - char[] ret = new char[len]; - - if ((bufpos + 1) >= len) - System.arraycopy(buffer, bufpos - len + 1, ret, 0, len); - else - { - System.arraycopy(buffer, bufsize - (len - bufpos - 1), ret, 0, - len - bufpos - 1); - System.arraycopy(buffer, 0, ret, len - bufpos - 1, bufpos + 1); - } - - return ret; - } - - public void Done() - { - buffer = null; - bufline = null; - bufcolumn = null; - } - - /** - * Method to adjust line and column numbers for the start of a token. - */ - public void adjustBeginLineColumn(int newLine, int newCol) - { - int start = tokenBegin; - int len; - - if (bufpos >= tokenBegin) - { - len = bufpos - tokenBegin + inBuf + 1; - } - else - { - len = bufsize - tokenBegin + bufpos + 1 + inBuf; - } - - int i = 0, j = 0, k = 0; - int nextColDiff = 0, columnDiff = 0; - - while (i < len && - bufline[j = start % bufsize] == bufline[k = ++start % bufsize]) - { - bufline[j] = newLine; - nextColDiff = columnDiff + bufcolumn[k] - bufcolumn[j]; - bufcolumn[j] = newCol + columnDiff; - columnDiff = nextColDiff; - i++; - } - - if (i < len) - { - bufline[j] = newLine++; - bufcolumn[j] = newCol + columnDiff; - - while (i++ < len) - { - if (bufline[j = start % bufsize] != bufline[++start % bufsize]) - bufline[j] = newLine++; - else - bufline[j] = newLine; - } - } - - line = bufline[j]; - column = bufcolumn[j]; - } - -} diff --git a/beehive-jdbc-control/src/main/java/org/apache/beehive/controls/system/jdbc/parser/SqlFragment.java b/beehive-jdbc-control/src/main/java/org/apache/beehive/controls/system/jdbc/parser/SqlFragment.java deleted file mode 100644 index a3ea89f..0000000 --- a/beehive-jdbc-control/src/main/java/org/apache/beehive/controls/system/jdbc/parser/SqlFragment.java +++ /dev/null @@ -1,98 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ - -package org.apache.beehive.controls.system.jdbc.parser; - -import org.apache.beehive.controls.api.context.ControlBeanContext; -import org.apache.beehive.controls.system.jdbc.TypeMappingsFactory; - -import java.lang.reflect.Method; - -/** - * The abstract base class for fragments generated during parsing. - */ -public abstract class SqlFragment { - - /** - * True if this fragment shouldn't be cached since the prepared statement may change on each invocation. - * @return true if this fragment shouldn't be cached by the parser - */ - boolean isDynamicFragment() { - return false; - } - - /** - * Does this fragment contain a parameter value for a prepared statement - * @return true if this fragement doesn't contain a prepared statement value. - */ - boolean hasParamValue() { - return false; - } - - /** - * True if this fragment evaluates to a JdbcControl.ComplexSqlFragment, i.e. - * a value type which needs additional evaluation after reflection. - * - * @param context Control bean context. - * @param method Method. - * @param args Method args. - * @return true if evaluates to a complex sql fragment. - */ - protected boolean hasComplexValue(ControlBeanContext context, Method method, Object[] args) { - return false; - } - - /** - * Get the SQL data type for the parameter value contained within this fragment. - * @return The SQL data type for this fragment. - */ - int getParamSqlDataType() { - return TypeMappingsFactory.TYPE_UNKNOWN; - } - - /** - * Get the prepared statement parameter value contained within this fragment. - * - * @param context A ControlBeanContext instance - * @param method The annotated method - * @param args The method's parameters - * @return null if this fragment doesn't contain a parameter value. - */ - Object[] getParameterValues(ControlBeanContext context, Method method, Object[] args) { - return null; - } - - /** - * Get the text for a prepared statement generated by this fragment. - * @param context A ControlBeanContext instance - * @param method The annotated method - * @param args The method's parameters - * @return A String containing the prepared statement text generated by this fragment - */ - abstract String getPreparedStatementText(ControlBeanContext context, Method method, Object[] args); - - /** - * Must be implemented for JUnit testing. - * @return The String value of this fragment. - */ - public String toString() { - assert false : "Classes which extend SqlFragment must implement toString()"; - return null; - } -} diff --git a/beehive-jdbc-control/src/main/java/org/apache/beehive/controls/system/jdbc/parser/SqlFragmentContainer.java b/beehive-jdbc-control/src/main/java/org/apache/beehive/controls/system/jdbc/parser/SqlFragmentContainer.java deleted file mode 100644 index 3ccbf5d..0000000 --- a/beehive-jdbc-control/src/main/java/org/apache/beehive/controls/system/jdbc/parser/SqlFragmentContainer.java +++ /dev/null @@ -1,99 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ - -package org.apache.beehive.controls.system.jdbc.parser; - -import org.apache.beehive.controls.api.context.ControlBeanContext; - -import java.lang.reflect.Method; -import java.util.ArrayList; - -/** - * The abstract base class for fragment's which may contain child fragments. - */ -public abstract class SqlFragmentContainer extends SqlFragment { - - /** Child fragments of this container. */ - protected ArrayList _children; - - /** - * Construct a new SqlFragmentContainer instance. - */ - SqlFragmentContainer() { - _children = new ArrayList(); - } - - /** - * Does this fragment contain a parameter value for a prepared statement? - * @return true If this fragment contains a parameter value for a PreparedStatement. - */ - boolean hasParamValue() { - for (SqlFragment f : _children) { - if (f.hasParamValue()) { - return true; - } - } - return false; - } - - /** - * Add a child. - * @param child Child to add. - */ - void addChild(SqlFragment child) { - _children.add(child); - } - - /** - * Return the array of children. - * @return An array of SqlFragments. - */ - SqlFragment[] getChildren() { - SqlFragment[] fragments = new SqlFragment[_children.size()]; - return _children.toArray(fragments); - } - - /** - * Must be implemented for JUnit testing. - * @return The String value of this fragment and all of its child fragments. - */ - public String toString() { - StringBuilder s = new StringBuilder(); - for (SqlFragment f : _children) { - s.append(f.toString()); - } - return s.toString(); - } - - /** - * builds the text of the prepared statement - * - * @param context A ControlBeanContext instance. - * @param m The annotated method. - * @param args The method's parameters. - * @return The PreparedStatement text generated by this fragment and its children. - */ - String getPreparedStatementText(ControlBeanContext context, Method m, Object[] args) { - StringBuilder sb = new StringBuilder(); - for (SqlFragment sf : _children) { - sb.append(sf.getPreparedStatementText(context, m, args)); - } - return sb.toString(); - } -} diff --git a/beehive-jdbc-control/src/main/java/org/apache/beehive/controls/system/jdbc/parser/SqlGrammar.java b/beehive-jdbc-control/src/main/java/org/apache/beehive/controls/system/jdbc/parser/SqlGrammar.java deleted file mode 100644 index b35cd18..0000000 --- a/beehive-jdbc-control/src/main/java/org/apache/beehive/controls/system/jdbc/parser/SqlGrammar.java +++ /dev/null @@ -1,538 +0,0 @@ -/* Generated By:JavaCC: Do not edit this line. SqlGrammar.java */ -package org.apache.beehive.controls.system.jdbc.parser; -import java.io.StringReader; - -public class SqlGrammar implements SqlGrammarConstants { - private StringBuilder buffer = new StringBuilder(); - public static void main(String[] args) throws Exception - { - SqlGrammar parser = new SqlGrammar(new StringReader(args[0])); - SqlStatement statement = parser.parse(); - System.out.println(statement.toString()); - } - -// -// Parse methods -// - - -// -// Main parse method -// - final public SqlStatement parse() throws ParseException { - SqlStatement statement = new SqlStatement(); - SqlFragment frag; - Token t, sq; - label_1: - while (true) { - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case NON_EXPRESSION_TEXT: - case START_EXPRESSION: - case SQUOTE: - ; - break; - default: - jj_la1[0] = jj_gen; - break label_1; - } - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case NON_EXPRESSION_TEXT: - t = jj_consume_token(NON_EXPRESSION_TEXT); - statement.addChild(new LiteralFragment(t.image)); - break; - case SQUOTE: - sq = jj_consume_token(SQUOTE); - t = jj_consume_token(STRING_LITERAL); - statement.addChild(new LiteralFragment(sq.image + t.image)); - break; - case START_EXPRESSION: - frag = parseExpression(); - statement.addChild(frag); - break; - default: - jj_la1[1] = jj_gen; - jj_consume_token(-1); - throw new ParseException(); - } - } - jj_consume_token(0); - {if (true) return statement;} - throw new Error("Missing return statement in function"); - } - -// -// Parse an expression delimited by '{}' -// - final public SqlFragment parseExpression() throws ParseException { - Token t, tt = null; - SqlFragment frag = null; - jj_consume_token(START_EXPRESSION); - label_2: - while (true) { - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case WHITESPACE: - ; - break; - default: - jj_la1[2] = jj_gen; - break label_2; - } - jj_consume_token(WHITESPACE); - } - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case SQL_ESCAPE: - case SQL_SUBST: - case SQL_FN: - frag = parseSqlEscape(); - break; - case JDBC_CALL: - case JDBC_RET: - case JDBC_DATE: - case JDBC_TIME: - case JDBC_TIMESTAMP: - case JDBC_FUNCTION: - case JDBC_ESCAPE: - case JDBC_OUTERJOIN: - frag = parseJdbcEscape(); - break; - case IDENTIFIER: - t = jj_consume_token(IDENTIFIER); - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case REFLECT_SEP: - jj_consume_token(REFLECT_SEP); - tt = jj_consume_token(IDENTIFIER); - break; - default: - jj_la1[3] = jj_gen; - ; - } - jj_consume_token(END_EXPRESSION); - frag = new ReflectionFragment(t.image,(tt == null) ? null : tt.image); - break; - default: - jj_la1[4] = jj_gen; - jj_consume_token(-1); - throw new ParseException(); - } - label_3: - while (true) { - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case WHITESPACE: - ; - break; - default: - jj_la1[5] = jj_gen; - break label_3; - } - jj_consume_token(WHITESPACE); - } - {if (true) return frag;} - throw new Error("Missing return statement in function"); - } - -// -// parse an sql: escape sequence -// - final public SqlSubstitutionFragment parseSqlEscape() throws ParseException { - Token id1, id2; - Token t = null; - SqlSubstitutionFragment frag; - String func = null; - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case SQL_ESCAPE: - case SQL_SUBST: - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case SQL_ESCAPE: - jj_consume_token(SQL_ESCAPE); - break; - case SQL_SUBST: - jj_consume_token(SQL_SUBST); - break; - default: - jj_la1[6] = jj_gen; - jj_consume_token(-1); - throw new ParseException(); - } - t = jj_consume_token(IDENTIFIER); - if (t != null) { - frag = new SqlSubstitutionFragment(new ReflectionFragment(t.image)); - } else { - frag = new SqlSubstitutionFragment(new LiteralFragment(func)); - } - break; - case SQL_FN: - jj_consume_token(SQL_FN); - label_4: - while (true) { - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case SQL_FN_WHITESPACE: - ; - break; - default: - jj_la1[7] = jj_gen; - break label_4; - } - jj_consume_token(SQL_FN_WHITESPACE); - } - jj_consume_token(SQL_FN_NM); - label_5: - while (true) { - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case SQL_FN_WHITESPACE: - ; - break; - default: - jj_la1[8] = jj_gen; - break label_5; - } - jj_consume_token(SQL_FN_WHITESPACE); - } - jj_consume_token(SQL_FN_PAREN); - label_6: - while (true) { - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case SQL_FN_WHITESPACE: - ; - break; - default: - jj_la1[9] = jj_gen; - break label_6; - } - jj_consume_token(SQL_FN_WHITESPACE); - } - id1 = jj_consume_token(SQL_FN_IDENTIFIER); - label_7: - while (true) { - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case SQL_FN_WHITESPACE: - ; - break; - default: - jj_la1[10] = jj_gen; - break label_7; - } - jj_consume_token(SQL_FN_WHITESPACE); - } - jj_consume_token(SQL_FN_COMMA); - label_8: - while (true) { - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case SQL_FN_WHITESPACE: - ; - break; - default: - jj_la1[11] = jj_gen; - break label_8; - } - jj_consume_token(SQL_FN_WHITESPACE); - } - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case SQL_FN_PSTART: - t = jj_consume_token(SQL_FN_PSTART); - break; - default: - jj_la1[12] = jj_gen; - ; - } - id2 = jj_consume_token(SQL_FN_IDENTIFIER); - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case SQL_FN_PEND: - jj_consume_token(SQL_FN_PEND); - break; - default: - jj_la1[13] = jj_gen; - ; - } - label_9: - while (true) { - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case SQL_FN_WHITESPACE: - ; - break; - default: - jj_la1[14] = jj_gen; - break label_9; - } - jj_consume_token(SQL_FN_WHITESPACE); - } - jj_consume_token(SQL_FN_END); - if (t == null) { - frag = new SqlSubstitutionFragment(new LiteralFragment("(" + id1.image + " IN (" + id2.image + ")")); - } else { - frag = new SqlSubstitutionFragment(new LiteralFragment("(" + id1.image + " IN ("), - new ReflectionFragment(id2.image), - new LiteralFragment("))")); - } - break; - default: - jj_la1[15] = jj_gen; - jj_consume_token(-1); - throw new ParseException(); - } - jj_consume_token(END_EXPRESSION); - {if (true) return frag;} - throw new Error("Missing return statement in function"); - } - -// -// parse a param sub inside of a jdbc escape -// - final public SqlFragment parseReflect() throws ParseException { - Token t, tt = null; - SqlFragment frag; - jj_consume_token(JDBC_PARAM); - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case PARAM_IDENTIFIER: - t = jj_consume_token(PARAM_IDENTIFIER); - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case PARAM_REFLECT_SEP: - jj_consume_token(PARAM_REFLECT_SEP); - tt = jj_consume_token(IDENTIFIER); - break; - default: - jj_la1[16] = jj_gen; - ; - } - frag = new ReflectionFragment(t.image, (tt == null) ? null : tt.image); - break; - case PARAM_LITERAL: - t = jj_consume_token(PARAM_LITERAL); - frag = new LiteralFragment(t.image); - break; - default: - jj_la1[17] = jj_gen; - jj_consume_token(-1); - throw new ParseException(); - } - jj_consume_token(PARAM_END); - {if (true) return frag;} - throw new Error("Missing return statement in function"); - } - -// -// parse a jdbc escape sequence -// - final public JdbcFragment parseJdbcEscape() throws ParseException { - Token lit, c; - JdbcFragment jfrag = new JdbcFragment(); - jfrag.addChild(new LiteralFragment("{")); - SqlFragment frag = null; - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case JDBC_CALL: - c = jj_consume_token(JDBC_CALL); - break; - case JDBC_RET: - c = jj_consume_token(JDBC_RET); - break; - case JDBC_DATE: - c = jj_consume_token(JDBC_DATE); - break; - case JDBC_ESCAPE: - c = jj_consume_token(JDBC_ESCAPE); - break; - case JDBC_FUNCTION: - c = jj_consume_token(JDBC_FUNCTION); - break; - case JDBC_TIME: - c = jj_consume_token(JDBC_TIME); - break; - case JDBC_TIMESTAMP: - c = jj_consume_token(JDBC_TIMESTAMP); - break; - case JDBC_OUTERJOIN: - c = jj_consume_token(JDBC_OUTERJOIN); - break; - default: - jj_la1[18] = jj_gen; - jj_consume_token(-1); - throw new ParseException(); - } - jfrag.addChild(new LiteralFragment(c.image)); - label_10: - while (true) { - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case JDBC_LIT: - lit = jj_consume_token(JDBC_LIT); - jfrag.addChild(new LiteralFragment(lit.image)); - break; - case JDBC_PARAM: - frag = parseReflect(); - jfrag.addChild(frag); - break; - default: - jj_la1[19] = jj_gen; - jj_consume_token(-1); - throw new ParseException(); - } - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case JDBC_LIT: - case JDBC_PARAM: - ; - break; - default: - jj_la1[20] = jj_gen; - break label_10; - } - } - jj_consume_token(JDBC_END); - jfrag.addChild(new LiteralFragment("}")); - {if (true) return jfrag;} - throw new Error("Missing return statement in function"); - } - - public SqlGrammarTokenManager token_source; - SimpleCharStream jj_input_stream; - public Token token, jj_nt; - private int jj_ntk; - private int jj_gen; - final private int[] jj_la1 = new int[21]; - static private int[] jj_la1_0; - static private int[] jj_la1_1; - static { - jj_la1_0(); - jj_la1_1(); - } - private static void jj_la1_0() { - jj_la1_0 = new int[] {0xe,0xe,0x100000,0x100,0x2ffe00,0x100000,0x600,0x40000000,0x40000000,0x40000000,0x40000000,0x40000000,0x10000000,0x20000000,0x40000000,0xe00,0x0,0x0,0xff000,0x0,0x0,}; - } - private static void jj_la1_1() { - jj_la1_1 = new int[] {0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x10,0x28,0x0,0x6,0x6,}; - } - - public SqlGrammar(java.io.InputStream stream) { - jj_input_stream = new SimpleCharStream(stream, 1, 1); - token_source = new SqlGrammarTokenManager(jj_input_stream); - token = new Token(); - jj_ntk = -1; - jj_gen = 0; - for (int i = 0; i < 21; i++) jj_la1[i] = -1; - } - - public void ReInit(java.io.InputStream stream) { - jj_input_stream.ReInit(stream, 1, 1); - token_source.ReInit(jj_input_stream); - token = new Token(); - jj_ntk = -1; - jj_gen = 0; - for (int i = 0; i < 21; i++) jj_la1[i] = -1; - } - - public SqlGrammar(java.io.Reader stream) { - jj_input_stream = new SimpleCharStream(stream, 1, 1); - token_source = new SqlGrammarTokenManager(jj_input_stream); - token = new Token(); - jj_ntk = -1; - jj_gen = 0; - for (int i = 0; i < 21; i++) jj_la1[i] = -1; - } - - public void ReInit(java.io.Reader stream) { - jj_input_stream.ReInit(stream, 1, 1); - token_source.ReInit(jj_input_stream); - token = new Token(); - jj_ntk = -1; - jj_gen = 0; - for (int i = 0; i < 21; i++) jj_la1[i] = -1; - } - - public SqlGrammar(SqlGrammarTokenManager tm) { - token_source = tm; - token = new Token(); - jj_ntk = -1; - jj_gen = 0; - for (int i = 0; i < 21; i++) jj_la1[i] = -1; - } - - public void ReInit(SqlGrammarTokenManager tm) { - token_source = tm; - token = new Token(); - jj_ntk = -1; - jj_gen = 0; - for (int i = 0; i < 21; i++) jj_la1[i] = -1; - } - - final private Token jj_consume_token(int kind) throws ParseException { - Token oldToken; - if ((oldToken = token).next != null) token = token.next; - else token = token.next = token_source.getNextToken(); - jj_ntk = -1; - if (token.kind == kind) { - jj_gen++; - return token; - } - token = oldToken; - jj_kind = kind; - throw generateParseException(); - } - - final public Token getNextToken() { - if (token.next != null) token = token.next; - else token = token.next = token_source.getNextToken(); - jj_ntk = -1; - jj_gen++; - return token; - } - - final public Token getToken(int index) { - Token t = token; - for (int i = 0; i < index; i++) { - if (t.next != null) t = t.next; - else t = t.next = token_source.getNextToken(); - } - return t; - } - - final private int jj_ntk() { - if ((jj_nt=token.next) == null) - return (jj_ntk = (token.next=token_source.getNextToken()).kind); - else - return (jj_ntk = jj_nt.kind); - } - - private java.util.Vector jj_expentries = new java.util.Vector(); - private int[] jj_expentry; - private int jj_kind = -1; - - public ParseException generateParseException() { - jj_expentries.removeAllElements(); - boolean[] la1tokens = new boolean[39]; - for (int i = 0; i < 39; i++) { - la1tokens[i] = false; - } - if (jj_kind >= 0) { - la1tokens[jj_kind] = true; - jj_kind = -1; - } - for (int i = 0; i < 21; i++) { - if (jj_la1[i] == jj_gen) { - for (int j = 0; j < 32; j++) { - if ((jj_la1_0[i] & (1<", - "", - "\"{\"", - "\"\\\'\"", - "", - "", - "", - "\"}\"", - "\"|\"", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "\")\"", - "\"in\"", - "\"(\"", - "\",\"", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - }; - -} diff --git a/beehive-jdbc-control/src/main/java/org/apache/beehive/controls/system/jdbc/parser/SqlGrammarTokenManager.java b/beehive-jdbc-control/src/main/java/org/apache/beehive/controls/system/jdbc/parser/SqlGrammarTokenManager.java deleted file mode 100644 index 1360de4..0000000 --- a/beehive-jdbc-control/src/main/java/org/apache/beehive/controls/system/jdbc/parser/SqlGrammarTokenManager.java +++ /dev/null @@ -1,1494 +0,0 @@ -/* Generated By:JavaCC: Do not edit this line. SqlGrammarTokenManager.java */ -package org.apache.beehive.controls.system.jdbc.parser; -import java.io.StringReader; - -public class SqlGrammarTokenManager implements SqlGrammarConstants -{ - public java.io.PrintStream debugStream = System.out; - public void setDebugStream(java.io.PrintStream ds) { debugStream = ds; } -private final int jjStopStringLiteralDfa_0(int pos, long active0) -{ - switch (pos) - { - default : - return -1; - } -} -private final int jjStartNfa_0(int pos, long active0) -{ - return jjMoveNfa_0(jjStopStringLiteralDfa_0(pos, active0), pos + 1); -} -private final int jjStopAtPos(int pos, int kind) -{ - jjmatchedKind = kind; - jjmatchedPos = pos; - return pos + 1; -} -private final int jjStartNfaWithStates_0(int pos, int kind, int state) -{ - jjmatchedKind = kind; - jjmatchedPos = pos; - try { curChar = input_stream.readChar(); } - catch(java.io.IOException e) { return pos + 1; } - return jjMoveNfa_0(state, pos + 1); -} -private final int jjMoveStringLiteralDfa0_0() -{ - switch(curChar) - { - case 39: - return jjStopAtPos(0, 3); - case 123: - return jjStopAtPos(0, 2); - default : - return jjMoveNfa_0(0, 0); - } -} -private final void jjCheckNAdd(int state) -{ - if (jjrounds[state] != jjround) - { - jjstateSet[jjnewStateCnt++] = state; - jjrounds[state] = jjround; - } -} -private final void jjAddStates(int start, int end) -{ - do { - jjstateSet[jjnewStateCnt++] = jjnextStates[start]; - } while (start++ != end); -} -private final void jjCheckNAddTwoStates(int state1, int state2) -{ - jjCheckNAdd(state1); - jjCheckNAdd(state2); -} -private final void jjCheckNAddStates(int start, int end) -{ - do { - jjCheckNAdd(jjnextStates[start]); - } while (start++ != end); -} -private final void jjCheckNAddStates(int start) -{ - jjCheckNAdd(jjnextStates[start]); - jjCheckNAdd(jjnextStates[start + 1]); -} -static final long[] jjbitVec0 = { - 0xfffffffffffffffeL, 0xffffffffffffffffL, 0xffffffffffffffffL, 0xffffffffffffffffL -}; -static final long[] jjbitVec2 = { - 0x0L, 0x0L, 0xffffffffffffffffL, 0xffffffffffffffffL -}; -private final int jjMoveNfa_0(int startState, int curPos) -{ - int[] nextStates; - int startsAt = 0; - jjnewStateCnt = 1; - int i = 1; - jjstateSet[0] = startState; - int j, kind = 0x7fffffff; - for (;;) - { - if (++jjround == 0x7fffffff) - ReInitRounds(); - if (curChar < 64) - { - long l = 1L << curChar; - MatchLoop: do - { - switch(jjstateSet[--i]) - { - case 0: - if ((0xffffff7fffffffffL & l) == 0L) - break; - kind = 1; - jjstateSet[jjnewStateCnt++] = 0; - break; - default : break; - } - } while(i != startsAt); - } - else if (curChar < 128) - { - long l = 1L << (curChar & 077); - MatchLoop: do - { - switch(jjstateSet[--i]) - { - case 0: - if ((0xd7ffffffffffffffL & l) == 0L) - break; - kind = 1; - jjstateSet[jjnewStateCnt++] = 0; - break; - default : break; - } - } while(i != startsAt); - } - else - { - int hiByte = (int)(curChar >> 8); - int i1 = hiByte >> 6; - long l1 = 1L << (hiByte & 077); - int i2 = (curChar & 0xff) >> 6; - long l2 = 1L << (curChar & 077); - MatchLoop: do - { - switch(jjstateSet[--i]) - { - case 0: - if (!jjCanMove_0(hiByte, i1, i2, l1, l2)) - break; - if (kind > 1) - kind = 1; - jjstateSet[jjnewStateCnt++] = 0; - break; - default : break; - } - } while(i != startsAt); - } - if (kind != 0x7fffffff) - { - jjmatchedKind = kind; - jjmatchedPos = curPos; - kind = 0x7fffffff; - } - ++curPos; - if ((i = jjnewStateCnt) == (startsAt = 1 - (jjnewStateCnt = startsAt))) - return curPos; - try { curChar = input_stream.readChar(); } - catch(java.io.IOException e) { return curPos; } - } -} -private final int jjStopStringLiteralDfa_3(int pos, long active0) -{ - switch (pos) - { - case 0: - if ((active0 & 0x2000000L) != 0L) - { - jjmatchedKind = 31; - return 4; - } - return -1; - default : - return -1; - } -} -private final int jjStartNfa_3(int pos, long active0) -{ - return jjMoveNfa_3(jjStopStringLiteralDfa_3(pos, active0), pos + 1); -} -private final int jjStartNfaWithStates_3(int pos, int kind, int state) -{ - jjmatchedKind = kind; - jjmatchedPos = pos; - try { curChar = input_stream.readChar(); } - catch(java.io.IOException e) { return pos + 1; } - return jjMoveNfa_3(state, pos + 1); -} -private final int jjMoveStringLiteralDfa0_3() -{ - switch(curChar) - { - case 40: - return jjStopAtPos(0, 26); - case 41: - return jjStopAtPos(0, 24); - case 44: - return jjStopAtPos(0, 27); - case 73: - return jjMoveStringLiteralDfa1_3(0x2000000L); - case 105: - return jjMoveStringLiteralDfa1_3(0x2000000L); - default : - return jjMoveNfa_3(0, 0); - } -} -private final int jjMoveStringLiteralDfa1_3(long active0) -{ - try { curChar = input_stream.readChar(); } - catch(java.io.IOException e) { - jjStopStringLiteralDfa_3(0, active0); - return 1; - } - switch(curChar) - { - case 78: - if ((active0 & 0x2000000L) != 0L) - return jjStartNfaWithStates_3(1, 25, 4); - break; - case 110: - if ((active0 & 0x2000000L) != 0L) - return jjStartNfaWithStates_3(1, 25, 4); - break; - default : - break; - } - return jjStartNfa_3(0, active0); -} -static final long[] jjbitVec3 = { - 0x1ff00000fffffffeL, 0xffffffffffffc000L, 0xffffffffL, 0x600000000000000L -}; -static final long[] jjbitVec4 = { - 0x0L, 0x0L, 0x0L, 0xff7fffffff7fffffL -}; -static final long[] jjbitVec5 = { - 0x0L, 0xffffffffffffffffL, 0xffffffffffffffffL, 0xffffffffffffffffL -}; -static final long[] jjbitVec6 = { - 0xffffffffffffffffL, 0xffffffffffffffffL, 0xffffL, 0x0L -}; -static final long[] jjbitVec7 = { - 0xffffffffffffffffL, 0xffffffffffffffffL, 0x0L, 0x0L -}; -static final long[] jjbitVec8 = { - 0x3fffffffffffL, 0x0L, 0x0L, 0x0L -}; -private final int jjMoveNfa_3(int startState, int curPos) -{ - int[] nextStates; - int startsAt = 0; - jjnewStateCnt = 5; - int i = 1; - jjstateSet[0] = startState; - int j, kind = 0x7fffffff; - for (;;) - { - if (++jjround == 0x7fffffff) - ReInitRounds(); - if (curChar < 64) - { - long l = 1L << curChar; - MatchLoop: do - { - switch(jjstateSet[--i]) - { - case 0: - if ((0x100002600L & l) != 0L) - { - if (kind > 30) - kind = 30; - } - else if (curChar == 36) - { - if (kind > 31) - kind = 31; - jjCheckNAdd(4); - } - break; - case 2: - if ((0x100002600L & l) != 0L) - kind = 30; - break; - case 3: - if (curChar != 36) - break; - if (kind > 31) - kind = 31; - jjCheckNAdd(4); - break; - case 4: - if ((0x3ff401000000000L & l) == 0L) - break; - if (kind > 31) - kind = 31; - jjCheckNAdd(4); - break; - default : break; - } - } while(i != startsAt); - } - else if (curChar < 128) - { - long l = 1L << (curChar & 077); - MatchLoop: do - { - switch(jjstateSet[--i]) - { - case 0: - if ((0x7fffffe87fffffeL & l) != 0L) - { - if (kind > 31) - kind = 31; - jjCheckNAdd(4); - } - else if (curChar == 125) - { - if (kind > 29) - kind = 29; - } - else if (curChar == 123) - { - if (kind > 28) - kind = 28; - } - break; - case 1: - if (curChar == 125) - kind = 29; - break; - case 3: - case 4: - if ((0x7fffffe87fffffeL & l) == 0L) - break; - if (kind > 31) - kind = 31; - jjCheckNAdd(4); - break; - default : break; - } - } while(i != startsAt); - } - else - { - int hiByte = (int)(curChar >> 8); - int i1 = hiByte >> 6; - long l1 = 1L << (hiByte & 077); - int i2 = (curChar & 0xff) >> 6; - long l2 = 1L << (curChar & 077); - MatchLoop: do - { - switch(jjstateSet[--i]) - { - case 0: - case 4: - if (!jjCanMove_1(hiByte, i1, i2, l1, l2)) - break; - if (kind > 31) - kind = 31; - jjCheckNAdd(4); - break; - default : break; - } - } while(i != startsAt); - } - if (kind != 0x7fffffff) - { - jjmatchedKind = kind; - jjmatchedPos = curPos; - kind = 0x7fffffff; - } - ++curPos; - if ((i = jjnewStateCnt) == (startsAt = 5 - (jjnewStateCnt = startsAt))) - return curPos; - try { curChar = input_stream.readChar(); } - catch(java.io.IOException e) { return curPos; } - } -} -private final int jjMoveStringLiteralDfa0_1() -{ - return jjMoveNfa_1(14, 0); -} -private final int jjMoveNfa_1(int startState, int curPos) -{ - int[] nextStates; - int startsAt = 0; - jjnewStateCnt = 14; - int i = 1; - jjstateSet[0] = startState; - int j, kind = 0x7fffffff; - for (;;) - { - if (++jjround == 0x7fffffff) - ReInitRounds(); - if (curChar < 64) - { - long l = 1L << curChar; - MatchLoop: do - { - switch(jjstateSet[--i]) - { - case 14: - if ((0xffffff7fffffdbffL & l) != 0L) - jjCheckNAddStates(0, 5); - else if (curChar == 39) - { - if (kind > 4) - kind = 4; - } - if ((0xff000000000000L & l) != 0L) - jjCheckNAddStates(6, 11); - if ((0xf000000000000L & l) != 0L) - jjstateSet[jjnewStateCnt++] = 9; - break; - case 0: - if ((0xffffff7fffffdbffL & l) != 0L) - jjCheckNAddStates(0, 5); - break; - case 2: - if ((0x3ff000000000000L & l) != 0L) - jjstateSet[jjnewStateCnt++] = 3; - break; - case 3: - if ((0x3ff000000000000L & l) != 0L) - jjstateSet[jjnewStateCnt++] = 4; - break; - case 4: - case 7: - if ((0x3ff000000000000L & l) != 0L) - jjCheckNAdd(5); - break; - case 5: - if ((0x3ff000000000000L & l) != 0L) - jjCheckNAddStates(0, 5); - break; - case 8: - if ((0xf000000000000L & l) != 0L) - jjstateSet[jjnewStateCnt++] = 9; - break; - case 9: - if ((0xff000000000000L & l) != 0L) - jjstateSet[jjnewStateCnt++] = 10; - break; - case 10: - if ((0xff000000000000L & l) != 0L) - jjCheckNAddStates(0, 5); - break; - case 11: - if ((0xff000000000000L & l) != 0L) - jjCheckNAddStates(6, 11); - break; - case 12: - if (curChar == 39) - kind = 4; - break; - case 13: - if ((0xff000000000000L & l) != 0L) - jjCheckNAddStates(12, 18); - break; - default : break; - } - } while(i != startsAt); - } - else if (curChar < 128) - { - long l = 1L << (curChar & 077); - MatchLoop: do - { - switch(jjstateSet[--i]) - { - case 14: - jjCheckNAddStates(0, 5); - if ((0x100000001000000L & l) != 0L) - jjstateSet[jjnewStateCnt++] = 7; - else if ((0x20000000200000L & l) != 0L) - jjstateSet[jjnewStateCnt++] = 2; - break; - case 0: - jjCheckNAddStates(0, 5); - break; - case 1: - if ((0x20000000200000L & l) != 0L) - jjstateSet[jjnewStateCnt++] = 2; - break; - case 2: - if ((0x7e0000007eL & l) != 0L) - jjstateSet[jjnewStateCnt++] = 3; - break; - case 3: - if ((0x7e0000007eL & l) != 0L) - jjstateSet[jjnewStateCnt++] = 4; - break; - case 4: - case 7: - if ((0x7e0000007eL & l) != 0L) - jjCheckNAdd(5); - break; - case 5: - if ((0x7e0000007eL & l) != 0L) - jjCheckNAddStates(0, 5); - break; - case 6: - if ((0x100000001000000L & l) != 0L) - jjstateSet[jjnewStateCnt++] = 7; - break; - default : break; - } - } while(i != startsAt); - } - else - { - int hiByte = (int)(curChar >> 8); - int i1 = hiByte >> 6; - long l1 = 1L << (hiByte & 077); - int i2 = (curChar & 0xff) >> 6; - long l2 = 1L << (curChar & 077); - MatchLoop: do - { - switch(jjstateSet[--i]) - { - case 14: - case 0: - if (jjCanMove_0(hiByte, i1, i2, l1, l2)) - jjCheckNAddStates(0, 5); - break; - default : break; - } - } while(i != startsAt); - } - if (kind != 0x7fffffff) - { - jjmatchedKind = kind; - jjmatchedPos = curPos; - kind = 0x7fffffff; - } - ++curPos; - if ((i = jjnewStateCnt) == (startsAt = 14 - (jjnewStateCnt = startsAt))) - return curPos; - try { curChar = input_stream.readChar(); } - catch(java.io.IOException e) { return curPos; } - } -} -private final int jjMoveStringLiteralDfa0_4() -{ - return jjMoveNfa_4(0, 0); -} -private final int jjMoveNfa_4(int startState, int curPos) -{ - int[] nextStates; - int startsAt = 0; - jjnewStateCnt = 3; - int i = 1; - jjstateSet[0] = startState; - int j, kind = 0x7fffffff; - for (;;) - { - if (++jjround == 0x7fffffff) - ReInitRounds(); - if (curChar < 64) - { - long l = 1L << curChar; - MatchLoop: do - { - switch(jjstateSet[--i]) - { - case 0: - case 1: - kind = 33; - jjCheckNAdd(1); - break; - default : break; - } - } while(i != startsAt); - } - else if (curChar < 128) - { - long l = 1L << (curChar & 077); - MatchLoop: do - { - switch(jjstateSet[--i]) - { - case 0: - if ((0xd7ffffffffffffffL & l) != 0L) - { - if (kind > 33) - kind = 33; - jjCheckNAdd(1); - } - else if (curChar == 123) - { - if (kind > 34) - kind = 34; - } - else if (curChar == 125) - { - if (kind > 32) - kind = 32; - } - break; - case 1: - if ((0xd7ffffffffffffffL & l) == 0L) - break; - kind = 33; - jjCheckNAdd(1); - break; - case 2: - if (curChar == 123) - kind = 34; - break; - default : break; - } - } while(i != startsAt); - } - else - { - int hiByte = (int)(curChar >> 8); - int i1 = hiByte >> 6; - long l1 = 1L << (hiByte & 077); - int i2 = (curChar & 0xff) >> 6; - long l2 = 1L << (curChar & 077); - MatchLoop: do - { - switch(jjstateSet[--i]) - { - case 0: - case 1: - if (!jjCanMove_0(hiByte, i1, i2, l1, l2)) - break; - if (kind > 33) - kind = 33; - jjCheckNAdd(1); - break; - default : break; - } - } while(i != startsAt); - } - if (kind != 0x7fffffff) - { - jjmatchedKind = kind; - jjmatchedPos = curPos; - kind = 0x7fffffff; - } - ++curPos; - if ((i = jjnewStateCnt) == (startsAt = 3 - (jjnewStateCnt = startsAt))) - return curPos; - try { curChar = input_stream.readChar(); } - catch(java.io.IOException e) { return curPos; } - } -} -private final int jjStopStringLiteralDfa_2(int pos, long active0) -{ - switch (pos) - { - default : - return -1; - } -} -private final int jjStartNfa_2(int pos, long active0) -{ - return jjMoveNfa_2(jjStopStringLiteralDfa_2(pos, active0), pos + 1); -} -private final int jjStartNfaWithStates_2(int pos, int kind, int state) -{ - jjmatchedKind = kind; - jjmatchedPos = pos; - try { curChar = input_stream.readChar(); } - catch(java.io.IOException e) { return pos + 1; } - return jjMoveNfa_2(state, pos + 1); -} -private final int jjMoveStringLiteralDfa0_2() -{ - switch(curChar) - { - case 124: - return jjStopAtPos(0, 8); - case 125: - return jjStopAtPos(0, 7); - default : - return jjMoveNfa_2(4, 0); - } -} -private final int jjMoveNfa_2(int startState, int curPos) -{ - int[] nextStates; - int startsAt = 0; - jjnewStateCnt = 54; - int i = 1; - jjstateSet[0] = startState; - int j, kind = 0x7fffffff; - for (;;) - { - if (++jjround == 0x7fffffff) - ReInitRounds(); - if (curChar < 64) - { - long l = 1L << curChar; - MatchLoop: do - { - switch(jjstateSet[--i]) - { - case 4: - if ((0x100002600L & l) != 0L) - { - if (kind > 20) - kind = 20; - } - else if (curChar == 36) - { - if (kind > 21) - kind = 21; - jjCheckNAdd(31); - } - else if (curChar == 63) - jjCheckNAddTwoStates(6, 7); - break; - case 1: - if ((0x100002600L & l) == 0L) - break; - if (kind > 12) - kind = 12; - jjstateSet[jjnewStateCnt++] = 1; - break; - case 5: - if (curChar == 63) - jjCheckNAddTwoStates(6, 7); - break; - case 6: - if ((0x100002600L & l) != 0L) - jjCheckNAddTwoStates(6, 7); - break; - case 7: - if (curChar != 61) - break; - kind = 13; - jjCheckNAdd(8); - break; - case 8: - if ((0x100002600L & l) == 0L) - break; - if (kind > 13) - kind = 13; - jjCheckNAdd(8); - break; - case 10: - if ((0x100002600L & l) == 0L) - break; - if (kind > 14) - kind = 14; - jjstateSet[jjnewStateCnt++] = 10; - break; - case 12: - if ((0x100002600L & l) == 0L) - break; - if (kind > 15) - kind = 15; - jjstateSet[jjnewStateCnt++] = 12; - break; - case 14: - if ((0x100002600L & l) == 0L) - break; - if (kind > 16) - kind = 16; - jjstateSet[jjnewStateCnt++] = 14; - break; - case 17: - if ((0x100002600L & l) == 0L) - break; - if (kind > 17) - kind = 17; - jjstateSet[jjnewStateCnt++] = 17; - break; - case 20: - if ((0x100002600L & l) == 0L) - break; - if (kind > 18) - kind = 18; - jjstateSet[jjnewStateCnt++] = 20; - break; - case 27: - if ((0x100002600L & l) == 0L) - break; - if (kind > 19) - kind = 19; - jjstateSet[jjnewStateCnt++] = 27; - break; - case 29: - if ((0x100002600L & l) != 0L && kind > 20) - kind = 20; - break; - case 30: - if (curChar != 36) - break; - if (kind > 21) - kind = 21; - jjCheckNAdd(31); - break; - case 31: - if ((0x3ff401000000000L & l) == 0L) - break; - if (kind > 21) - kind = 21; - jjCheckNAdd(31); - break; - case 33: - if (curChar == 58) - jjCheckNAdd(34); - break; - case 34: - if ((0x100002600L & l) == 0L) - break; - if (kind > 9) - kind = 9; - jjCheckNAdd(34); - break; - case 37: - if (curChar == 58) - jjCheckNAddTwoStates(38, 44); - break; - case 38: - if ((0x100002600L & l) != 0L) - jjCheckNAddTwoStates(38, 44); - break; - case 40: - if ((0x100002600L & l) == 0L) - break; - if (kind > 10) - kind = 10; - jjstateSet[jjnewStateCnt++] = 40; - break; - case 47: - if (curChar == 58) - jjCheckNAddTwoStates(48, 51); - break; - case 48: - if ((0x100002600L & l) != 0L) - jjCheckNAddTwoStates(48, 51); - break; - case 50: - if ((0x100002600L & l) == 0L) - break; - if (kind > 11) - kind = 11; - jjstateSet[jjnewStateCnt++] = 50; - break; - default : break; - } - } while(i != startsAt); - } - else if (curChar < 128) - { - long l = 1L << (curChar & 077); - MatchLoop: do - { - switch(jjstateSet[--i]) - { - case 4: - if ((0x7fffffe87fffffeL & l) != 0L) - { - if (kind > 21) - kind = 21; - jjCheckNAdd(31); - } - if ((0x8000000080000L & l) != 0L) - jjAddStates(19, 21); - else if ((0x800000008000L & l) != 0L) - jjstateSet[jjnewStateCnt++] = 26; - else if ((0x2000000020L & l) != 0L) - jjstateSet[jjnewStateCnt++] = 24; - else if ((0x4000000040L & l) != 0L) - jjstateSet[jjnewStateCnt++] = 16; - else if ((0x10000000100000L & l) != 0L) - jjstateSet[jjnewStateCnt++] = 13; - else if ((0x1000000010L & l) != 0L) - jjstateSet[jjnewStateCnt++] = 10; - else if ((0x800000008L & l) != 0L) - jjstateSet[jjnewStateCnt++] = 3; - if ((0x10000000100000L & l) != 0L) - jjstateSet[jjnewStateCnt++] = 12; - break; - case 0: - if ((0x100000001000L & l) != 0L) - jjstateSet[jjnewStateCnt++] = 1; - break; - case 2: - if ((0x100000001000L & l) != 0L) - jjstateSet[jjnewStateCnt++] = 0; - break; - case 3: - if ((0x200000002L & l) != 0L) - jjstateSet[jjnewStateCnt++] = 2; - break; - case 9: - if ((0x1000000010L & l) != 0L) - jjstateSet[jjnewStateCnt++] = 10; - break; - case 11: - if ((0x10000000100000L & l) != 0L) - jjstateSet[jjnewStateCnt++] = 12; - break; - case 13: - if ((0x8000000080000L & l) != 0L) - jjstateSet[jjnewStateCnt++] = 14; - break; - case 15: - if ((0x10000000100000L & l) != 0L) - jjstateSet[jjnewStateCnt++] = 13; - break; - case 16: - if ((0x400000004000L & l) != 0L) - jjstateSet[jjnewStateCnt++] = 17; - break; - case 18: - if ((0x4000000040L & l) != 0L) - jjstateSet[jjnewStateCnt++] = 16; - break; - case 19: - if ((0x2000000020L & l) != 0L) - jjstateSet[jjnewStateCnt++] = 20; - break; - case 21: - if ((0x1000000010000L & l) != 0L) - jjstateSet[jjnewStateCnt++] = 19; - break; - case 22: - if ((0x200000002L & l) != 0L) - jjstateSet[jjnewStateCnt++] = 21; - break; - case 23: - if ((0x800000008L & l) != 0L) - jjstateSet[jjnewStateCnt++] = 22; - break; - case 24: - if ((0x8000000080000L & l) != 0L) - jjstateSet[jjnewStateCnt++] = 23; - break; - case 25: - if ((0x2000000020L & l) != 0L) - jjstateSet[jjnewStateCnt++] = 24; - break; - case 26: - if ((0x40000000400L & l) != 0L) - jjstateSet[jjnewStateCnt++] = 27; - break; - case 28: - if ((0x800000008000L & l) != 0L) - jjstateSet[jjnewStateCnt++] = 26; - break; - case 30: - case 31: - if ((0x7fffffe87fffffeL & l) == 0L) - break; - if (kind > 21) - kind = 21; - jjCheckNAdd(31); - break; - case 32: - if ((0x8000000080000L & l) != 0L) - jjAddStates(19, 21); - break; - case 35: - if ((0x100000001000L & l) != 0L) - jjstateSet[jjnewStateCnt++] = 33; - break; - case 36: - if ((0x2000000020000L & l) != 0L) - jjstateSet[jjnewStateCnt++] = 35; - break; - case 39: - if ((0x10000000100000L & l) != 0L) - jjstateSet[jjnewStateCnt++] = 40; - break; - case 41: - if ((0x8000000080000L & l) != 0L) - jjstateSet[jjnewStateCnt++] = 39; - break; - case 42: - if ((0x400000004L & l) != 0L) - jjstateSet[jjnewStateCnt++] = 41; - break; - case 43: - if ((0x20000000200000L & l) != 0L) - jjstateSet[jjnewStateCnt++] = 42; - break; - case 44: - if ((0x8000000080000L & l) != 0L) - jjstateSet[jjnewStateCnt++] = 43; - break; - case 45: - if ((0x100000001000L & l) != 0L) - jjstateSet[jjnewStateCnt++] = 37; - break; - case 46: - if ((0x2000000020000L & l) != 0L) - jjstateSet[jjnewStateCnt++] = 45; - break; - case 49: - if ((0x400000004000L & l) != 0L) - jjstateSet[jjnewStateCnt++] = 50; - break; - case 51: - if ((0x4000000040L & l) != 0L) - jjstateSet[jjnewStateCnt++] = 49; - break; - case 52: - if ((0x100000001000L & l) != 0L) - jjstateSet[jjnewStateCnt++] = 47; - break; - case 53: - if ((0x2000000020000L & l) != 0L) - jjstateSet[jjnewStateCnt++] = 52; - break; - default : break; - } - } while(i != startsAt); - } - else - { - int hiByte = (int)(curChar >> 8); - int i1 = hiByte >> 6; - long l1 = 1L << (hiByte & 077); - int i2 = (curChar & 0xff) >> 6; - long l2 = 1L << (curChar & 077); - MatchLoop: do - { - switch(jjstateSet[--i]) - { - case 4: - case 31: - if (!jjCanMove_1(hiByte, i1, i2, l1, l2)) - break; - if (kind > 21) - kind = 21; - jjCheckNAdd(31); - break; - default : break; - } - } while(i != startsAt); - } - if (kind != 0x7fffffff) - { - jjmatchedKind = kind; - jjmatchedPos = curPos; - kind = 0x7fffffff; - } - ++curPos; - if ((i = jjnewStateCnt) == (startsAt = 54 - (jjnewStateCnt = startsAt))) - return curPos; - try { curChar = input_stream.readChar(); } - catch(java.io.IOException e) { return curPos; } - } -} -private final int jjMoveStringLiteralDfa0_5() -{ - return jjMoveNfa_5(0, 0); -} -private final int jjMoveNfa_5(int startState, int curPos) -{ - int[] nextStates; - int startsAt = 0; - jjnewStateCnt = 19; - int i = 1; - jjstateSet[0] = startState; - int j, kind = 0x7fffffff; - for (;;) - { - if (++jjround == 0x7fffffff) - ReInitRounds(); - if (curChar < 64) - { - long l = 1L << curChar; - MatchLoop: do - { - switch(jjstateSet[--i]) - { - case 0: - if (curChar == 39) - jjCheckNAddStates(22, 27); - else if (curChar == 36) - { - if (kind > 35) - kind = 35; - jjCheckNAdd(1); - } - break; - case 1: - if ((0x3ff401000000000L & l) == 0L) - break; - if (kind > 35) - kind = 35; - jjCheckNAdd(1); - break; - case 3: - if (curChar == 39) - jjCheckNAddStates(22, 27); - break; - case 4: - if ((0xffffff7fffffdbffL & l) != 0L) - jjCheckNAddStates(22, 27); - break; - case 6: - if ((0x3ff000000000000L & l) != 0L) - jjstateSet[jjnewStateCnt++] = 7; - break; - case 7: - if ((0x3ff000000000000L & l) != 0L) - jjstateSet[jjnewStateCnt++] = 8; - break; - case 8: - case 11: - if ((0x3ff000000000000L & l) != 0L) - jjCheckNAdd(9); - break; - case 9: - if ((0x3ff000000000000L & l) != 0L) - jjCheckNAddStates(22, 27); - break; - case 12: - if ((0xf000000000000L & l) != 0L) - jjstateSet[jjnewStateCnt++] = 13; - break; - case 13: - if ((0xff000000000000L & l) != 0L) - jjstateSet[jjnewStateCnt++] = 14; - break; - case 14: - if ((0xff000000000000L & l) != 0L) - jjCheckNAddStates(22, 27); - break; - case 15: - if ((0xff000000000000L & l) != 0L) - jjCheckNAddStates(28, 33); - break; - case 16: - if (curChar == 39 && kind > 37) - kind = 37; - break; - case 17: - if ((0xff000000000000L & l) != 0L) - jjCheckNAddStates(34, 40); - break; - default : break; - } - } while(i != startsAt); - } - else if (curChar < 128) - { - long l = 1L << (curChar & 077); - MatchLoop: do - { - switch(jjstateSet[--i]) - { - case 0: - if ((0x7fffffe87fffffeL & l) != 0L) - { - if (kind > 35) - kind = 35; - jjCheckNAdd(1); - } - else if (curChar == 125) - { - if (kind > 38) - kind = 38; - } - else if (curChar == 124) - { - if (kind > 36) - kind = 36; - } - break; - case 1: - if ((0x7fffffe87fffffeL & l) == 0L) - break; - if (kind > 35) - kind = 35; - jjCheckNAdd(1); - break; - case 2: - if (curChar == 124 && kind > 36) - kind = 36; - break; - case 4: - jjCheckNAddStates(22, 27); - break; - case 5: - if ((0x20000000200000L & l) != 0L) - jjstateSet[jjnewStateCnt++] = 6; - break; - case 6: - if ((0x7e0000007eL & l) != 0L) - jjstateSet[jjnewStateCnt++] = 7; - break; - case 7: - if ((0x7e0000007eL & l) != 0L) - jjstateSet[jjnewStateCnt++] = 8; - break; - case 8: - case 11: - if ((0x7e0000007eL & l) != 0L) - jjCheckNAdd(9); - break; - case 9: - if ((0x7e0000007eL & l) != 0L) - jjCheckNAddStates(22, 27); - break; - case 10: - if ((0x100000001000000L & l) != 0L) - jjstateSet[jjnewStateCnt++] = 11; - break; - case 18: - if (curChar == 125 && kind > 38) - kind = 38; - break; - default : break; - } - } while(i != startsAt); - } - else - { - int hiByte = (int)(curChar >> 8); - int i1 = hiByte >> 6; - long l1 = 1L << (hiByte & 077); - int i2 = (curChar & 0xff) >> 6; - long l2 = 1L << (curChar & 077); - MatchLoop: do - { - switch(jjstateSet[--i]) - { - case 0: - case 1: - if (!jjCanMove_1(hiByte, i1, i2, l1, l2)) - break; - if (kind > 35) - kind = 35; - jjCheckNAdd(1); - break; - case 4: - if (jjCanMove_0(hiByte, i1, i2, l1, l2)) - jjAddStates(22, 27); - break; - default : break; - } - } while(i != startsAt); - } - if (kind != 0x7fffffff) - { - jjmatchedKind = kind; - jjmatchedPos = curPos; - kind = 0x7fffffff; - } - ++curPos; - if ((i = jjnewStateCnt) == (startsAt = 19 - (jjnewStateCnt = startsAt))) - return curPos; - try { curChar = input_stream.readChar(); } - catch(java.io.IOException e) { return curPos; } - } -} -static final int[] jjnextStates = { - 0, 1, 6, 8, 11, 12, 0, 1, 6, 8, 12, 13, 0, 1, 6, 8, - 11, 12, 13, 36, 46, 53, 4, 5, 10, 12, 15, 16, 4, 5, 10, 12, - 16, 17, 4, 5, 10, 12, 15, 16, 17, -}; -private static final boolean jjCanMove_0(int hiByte, int i1, int i2, long l1, long l2) -{ - switch(hiByte) - { - case 0: - return ((jjbitVec2[i2] & l2) != 0L); - default : - if ((jjbitVec0[i1] & l1) != 0L) - return true; - return false; - } -} -private static final boolean jjCanMove_1(int hiByte, int i1, int i2, long l1, long l2) -{ - switch(hiByte) - { - case 0: - return ((jjbitVec4[i2] & l2) != 0L); - case 48: - return ((jjbitVec5[i2] & l2) != 0L); - case 49: - return ((jjbitVec6[i2] & l2) != 0L); - case 51: - return ((jjbitVec7[i2] & l2) != 0L); - case 61: - return ((jjbitVec8[i2] & l2) != 0L); - default : - if ((jjbitVec3[i1] & l1) != 0L) - return true; - return false; - } -} -public static final String[] jjstrLiteralImages = { -"", null, "\173", "\47", null, null, null, "\175", "\174", null, null, null, -null, null, null, null, null, null, null, null, null, null, null, null, "\51", null, -"\50", "\54", null, null, null, null, null, null, null, null, null, null, null, }; -public static final String[] lexStateNames = { - "DEFAULT", - "IN_LITERAL", - "IN_EXPRESSION", - "IN_SQLFN", - "IN_JDBC", - "IN_PARAM", -}; -public static final int[] jjnewLexState = { - -1, -1, 2, 1, 0, -1, -1, -1, -1, -1, -1, 3, 4, 4, 4, 4, 4, 4, 4, 4, -1, -1, -1, -1, 2, - -1, -1, -1, -1, -1, -1, -1, -1, -1, 5, -1, -1, -1, -1, -}; -protected SimpleCharStream input_stream; -private final int[] jjrounds = new int[54]; -private final int[] jjstateSet = new int[108]; -StringBuffer image; -int jjimageLen; -int lengthOfMatch; -protected char curChar; -public SqlGrammarTokenManager(SimpleCharStream stream) -{ - if (SimpleCharStream.staticFlag) - throw new Error("ERROR: Cannot use a static CharStream class with a non-static lexical analyzer."); - input_stream = stream; -} -public SqlGrammarTokenManager(SimpleCharStream stream, int lexState) -{ - this(stream); - SwitchTo(lexState); -} -public void ReInit(SimpleCharStream stream) -{ - jjmatchedPos = jjnewStateCnt = 0; - curLexState = defaultLexState; - input_stream = stream; - ReInitRounds(); -} -private final void ReInitRounds() -{ - int i; - jjround = 0x80000001; - for (i = 54; i-- > 0;) - jjrounds[i] = 0x80000000; -} -public void ReInit(SimpleCharStream stream, int lexState) -{ - ReInit(stream); - SwitchTo(lexState); -} -public void SwitchTo(int lexState) -{ - if (lexState >= 6 || lexState < 0) - throw new TokenMgrError("Error: Ignoring invalid lexical state : " + lexState + ". State unchanged.", TokenMgrError.INVALID_LEXICAL_STATE); - else - curLexState = lexState; -} - -protected Token jjFillToken() -{ - Token t = Token.newToken(jjmatchedKind); - t.kind = jjmatchedKind; - String im = jjstrLiteralImages[jjmatchedKind]; - t.image = (im == null) ? input_stream.GetImage() : im; - t.beginLine = input_stream.getBeginLine(); - t.beginColumn = input_stream.getBeginColumn(); - t.endLine = input_stream.getEndLine(); - t.endColumn = input_stream.getEndColumn(); - return t; -} - -int curLexState = 0; -int defaultLexState = 0; -int jjnewStateCnt; -int jjround; -int jjmatchedPos; -int jjmatchedKind; - -public Token getNextToken() -{ - int kind; - Token specialToken = null; - Token matchedToken; - int curPos = 0; - - EOFLoop : - for (;;) - { - try - { - curChar = input_stream.BeginToken(); - } - catch(java.io.IOException e) - { - jjmatchedKind = 0; - matchedToken = jjFillToken(); - return matchedToken; - } - image = null; - jjimageLen = 0; - - switch(curLexState) - { - case 0: - jjmatchedKind = 0x7fffffff; - jjmatchedPos = 0; - curPos = jjMoveStringLiteralDfa0_0(); - break; - case 1: - jjmatchedKind = 0x7fffffff; - jjmatchedPos = 0; - curPos = jjMoveStringLiteralDfa0_1(); - break; - case 2: - jjmatchedKind = 0x7fffffff; - jjmatchedPos = 0; - curPos = jjMoveStringLiteralDfa0_2(); - break; - case 3: - jjmatchedKind = 0x7fffffff; - jjmatchedPos = 0; - curPos = jjMoveStringLiteralDfa0_3(); - break; - case 4: - jjmatchedKind = 0x7fffffff; - jjmatchedPos = 0; - curPos = jjMoveStringLiteralDfa0_4(); - break; - case 5: - jjmatchedKind = 0x7fffffff; - jjmatchedPos = 0; - curPos = jjMoveStringLiteralDfa0_5(); - break; - } - if (jjmatchedKind != 0x7fffffff) - { - if (jjmatchedPos + 1 < curPos) - input_stream.backup(curPos - jjmatchedPos - 1); - matchedToken = jjFillToken(); - TokenLexicalActions(matchedToken); - if (jjnewLexState[jjmatchedKind] != -1) - curLexState = jjnewLexState[jjmatchedKind]; - return matchedToken; - } - int error_line = input_stream.getEndLine(); - int error_column = input_stream.getEndColumn(); - String error_after = null; - boolean EOFSeen = false; - try { input_stream.readChar(); input_stream.backup(1); } - catch (java.io.IOException e1) { - EOFSeen = true; - error_after = curPos <= 1 ? "" : input_stream.GetImage(); - if (curChar == '\n' || curChar == '\r') { - error_line++; - error_column = 0; - } - else - error_column++; - } - if (!EOFSeen) { - input_stream.backup(1); - error_after = curPos <= 1 ? "" : input_stream.GetImage(); - } - throw new TokenMgrError(EOFSeen, curLexState, error_line, error_column, error_after, curChar, TokenMgrError.LEXICAL_ERROR); - } -} - -void TokenLexicalActions(Token matchedToken) -{ - switch(jjmatchedKind) - { - case 7 : - if (image == null) - image = new StringBuffer(jjstrLiteralImages[7]); - else - image.append(jjstrLiteralImages[7]); - SwitchTo(DEFAULT); - break; - case 32 : - if (image == null) - image = new StringBuffer(new String(input_stream.GetSuffix(jjimageLen + (lengthOfMatch = jjmatchedPos + 1)))); - else - image.append(new String(input_stream.GetSuffix(jjimageLen + (lengthOfMatch = jjmatchedPos + 1)))); - SwitchTo(DEFAULT); - break; - case 38 : - if (image == null) - image = new StringBuffer(new String(input_stream.GetSuffix(jjimageLen + (lengthOfMatch = jjmatchedPos + 1)))); - else - image.append(new String(input_stream.GetSuffix(jjimageLen + (lengthOfMatch = jjmatchedPos + 1)))); - SwitchTo(IN_JDBC); - break; - default : - break; - } -} -} diff --git a/beehive-jdbc-control/src/main/java/org/apache/beehive/controls/system/jdbc/parser/SqlParser.java b/beehive-jdbc-control/src/main/java/org/apache/beehive/controls/system/jdbc/parser/SqlParser.java deleted file mode 100644 index d3de63d..0000000 --- a/beehive-jdbc-control/src/main/java/org/apache/beehive/controls/system/jdbc/parser/SqlParser.java +++ /dev/null @@ -1,85 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ - -package org.apache.beehive.controls.system.jdbc.parser; - -import org.apache.beehive.controls.api.ControlException; - -import java.util.HashMap; -import java.io.StringReader; - -/** - * The SqlParser class is a thread-safe class which parses a string containing a SQL statement - * with JdbcControl substitituion delimiters. It is important to note that the SQL is not parsed/validated - only - * the sections within the SQL string which are delimited by '{' and '}' are parsed. - *

      - * Parsing is accomplished using the JavaCC grammar file SqlGrammer.jj. As the string is parsed it is broken - * into fragments by the parser. Any portion of the string which is not between '{' and '}' delimiters becomes a - * LiteralFragment. The portions of the SQL string which fall between the start and end delimiters are categorized as - * either JdbcFragment, ReflectionFragment, or SqlSubstitutionFragment. - *

      - * Fragments which subclass SqlFragmentContainer may contain other fragments as children. Fragements subclassed - * from SqlFragment my not contain child fragments. Upon completion of parsing a SqlStatement is - * returned to the caller. The SqlStatement contains the heirarchary of fragments which have been derived - * from the orignal SQL string. - *

      - * The parser will also cache all SqlStatements which contain non-volitale SQL. Only SqlEscapeFragments - * contain volitile SQL at this point. - */ -public final class SqlParser { - - // maintain a cache of SQLStatements which have already been parsed - private HashMap _cachedSqlStatements; - - /** - * Create a new instance of the SqlParser. - */ - public SqlParser() { - _cachedSqlStatements = new HashMap(); - } - - /** - * Parse the sql and return an SqlStatement. - * - * @param sql A String contianing the sql to parse. - * @return A SqlStatement instance. - */ - public SqlStatement parse(String sql) { - - // does a cached parse result exist for this statement? - if (_cachedSqlStatements.containsKey(sql)) { - return _cachedSqlStatements.get(sql); - } - - SqlGrammar _parser = new SqlGrammar(new StringReader(sql)); - SqlStatement parsed = null; - try { - parsed = _parser.parse(); - } catch (ParseException e) { - throw new ControlException("Error parsing SQL statment." + e.getMessage(), e); - } catch (TokenMgrError tme) { - throw new ControlException("Error parsing SQL statment. " + tme.getMessage(), tme); - } - - if (parsed.isCacheable()) { - _cachedSqlStatements.put(sql, parsed); - } - return parsed; - } -} diff --git a/beehive-jdbc-control/src/main/java/org/apache/beehive/controls/system/jdbc/parser/SqlStatement.java b/beehive-jdbc-control/src/main/java/org/apache/beehive/controls/system/jdbc/parser/SqlStatement.java deleted file mode 100644 index cc52379..0000000 --- a/beehive-jdbc-control/src/main/java/org/apache/beehive/controls/system/jdbc/parser/SqlStatement.java +++ /dev/null @@ -1,523 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ - -package org.apache.beehive.controls.system.jdbc.parser; - -import org.apache.beehive.controls.api.ControlException; -import org.apache.beehive.controls.api.context.ControlBeanContext; -import org.apache.beehive.controls.system.jdbc.JdbcControl; -import org.apache.beehive.controls.system.jdbc.TypeMappingsFactory; - -import javax.sql.RowSet; -import java.io.Serializable; -import java.lang.reflect.Method; -import java.sql.CallableStatement; -import java.sql.Connection; -import java.sql.DatabaseMetaData; -import java.sql.PreparedStatement; -import java.sql.SQLException; -import java.sql.Statement; -import java.sql.Types; -import java.util.Calendar; - -/** - * Represents a fully parsed SQL statement. SqlStatements can be used to generated a java.sql.PreparedStatement. - */ -public final class SqlStatement extends SqlFragmentContainer implements Serializable { - - private static final TypeMappingsFactory _tmf = TypeMappingsFactory.getInstance(); - private boolean _callableStatement = false; - private boolean _cacheableStatement = true; - - // - // set from SQL annotation element values - // - private boolean _batchUpdate; - private boolean _getGeneratedKeys; - private String[] _genKeyColumnNames; - private int _fetchSize; - private int _maxArray; - private int _maxRows; - private int[] _genKeyColumnIndexes; - private JdbcControl.ScrollType _scrollType; - private JdbcControl.FetchDirection _fetchDirection; - private JdbcControl.HoldabilityType _holdability; - - /** - * Create a new SqlStatement. - */ - SqlStatement() { - super(); - } - - /** - * Append a SqlFragment to the end of this statement. - * - * @param frag SqlFragment to append. - */ - void addChild(SqlFragment frag) { - super.addChild(frag); - - if (frag.isDynamicFragment()) { - _cacheableStatement = false; - } - } - - - /** - * Can the PreparedStatement generated by this class be cached? - * - * @return true if this statement can be cached by the SqlParser. - */ - boolean isCacheable() { return _cacheableStatement; } - - - /** - * Does this statement generate a callable or prepared statement? - * - * @return true if this statement generates callable statement. - */ - public boolean isCallableStatement() { return _callableStatement; } - - /** - * Does this statement do a batch update? - * - * @return true if this statement should be executed as a batch update. - */ - public boolean isBatchUpdate() { return _batchUpdate; } - - /** - * Does this statement return generatedKeys? - * - * @return true if getGeneratedKeys set to true. - */ - public boolean getsGeneratedKeys() { return _getGeneratedKeys; } - - /** - * Generates the PreparedStatement the SQL statement. - * - * @param context ControlBeanContext instance. - * @param connection Connection to database. - * @param calendar Calendar instance which can be used to resolve date/time values. - * @param method Method the SQL is associated with. - * @param arguments Method parameters. - * @return The PreparedStatement generated by this statement. - * @throws SQLException If PreparedStatement cannot be created. - */ - public PreparedStatement createPreparedStatement(ControlBeanContext context, Connection connection, - Calendar calendar, Method method, Object[] arguments) - throws SQLException { - - PreparedStatement preparedStatement = null; - loadSQLAnnotationStatmentOptions(context, method); - checkJdbcSupport(connection.getMetaData()); - - _callableStatement = setCallableStatement(arguments); - - try { - final String sql = getPreparedStatementText(context, method, arguments); - - // - // is this a request for generatedKeys ? - // - if (_getGeneratedKeys) { - - if (_callableStatement) { - throw new ControlException("getGeneratedKeys not supported for CallableStatements"); - } - - if (_genKeyColumnNames.length > 0) { - preparedStatement = connection.prepareStatement(sql, _genKeyColumnNames); - } else if (_genKeyColumnIndexes.length > 0) { - preparedStatement = connection.prepareStatement(sql, _genKeyColumnIndexes); - } else { - preparedStatement = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); - } - - } else { - - if (_holdability == JdbcControl.HoldabilityType.DRIVER_DEFAULT) { - if (_scrollType == JdbcControl.ScrollType.DRIVER_DEFAULT) { - preparedStatement = (_callableStatement) ? connection.prepareCall(sql) : connection.prepareStatement(sql); - } else { - preparedStatement = (_callableStatement) - ? connection.prepareCall(sql, _scrollType.getType(), _scrollType.getConcurrencyType()) - : connection.prepareStatement(sql, _scrollType.getType(), _scrollType.getConcurrencyType()); - } - } else { - preparedStatement = (_callableStatement) - ? connection.prepareCall(sql, _scrollType.getType(), _scrollType.getConcurrencyType(), _holdability.getHoldability()) - : connection.prepareStatement(sql, _scrollType.getType(), _scrollType.getConcurrencyType(), _holdability.getHoldability()); - } - } - - // - // If the method argument is of type SQLParameter, treat this statement as a CallableStatement, - // - if (_callableStatement) { - for (SqlFragment sf : _children) { - if (sf.hasParamValue()) { - throw new ControlException("Cannot use parameter substution and SQLParameter array in the same method."); - } - } - JdbcControl.SQLParameter[] params = (JdbcControl.SQLParameter[]) arguments[0]; - if (params == null) { - return preparedStatement; - } - for (int i = 0; i < params.length; i++) { - JdbcControl.SQLParameter p = params[i]; - if (p.dir != JdbcControl.SQLParameter.OUT) { - Object value = params[i].value; - setPreparedStatementParameter(preparedStatement, i + 1, value, params[i].type, calendar); - } - - if (p.dir != JdbcControl.SQLParameter.IN) { - ((CallableStatement) preparedStatement).registerOutParameter(i + 1, params[i].type); - } - } - - - // - // special handling for batch updates - // - } else if (_batchUpdate) { - doBatchUpdate(preparedStatement, arguments, calendar); - - - // - // standard case, not a batch or callable - // - } else { - int pIndex = 1; - for (SqlFragment sf : _children) { - if (sf.hasParamValue()) { - Object values[] = sf.getParameterValues(context, method, arguments); - for (Object value : values) { - setPreparedStatementParameter(preparedStatement, pIndex++, value, sf.getParamSqlDataType(), calendar); - } - } - } - } - } catch (SQLException e) { - if (preparedStatement != null) preparedStatement.close(); - throw e; - } - - preparedStatement.setFetchDirection(_fetchDirection.getDirection()); - preparedStatement.setFetchSize(_fetchSize); - preparedStatement.setMaxRows(computeMaxRows(method)); - - return preparedStatement; - } - - /** - * Generates the PreparedStatement the SQL statement. - * - * @param context ControlBeanContext instance. - * @param connection Connection to database. - * @param method Method the SQL is associated with. - * @param arguments Method parameters. - * @return The PreparedStatement generated by this statement. - */ - public String createPreparedStatementString(ControlBeanContext context, Connection connection, - Method method, Object[] arguments) { - - final boolean callableStatement = setCallableStatement(arguments); - StringBuilder sqlString = new StringBuilder(getPreparedStatementText(context, method, arguments)); - - if (callableStatement) { - JdbcControl.SQLParameter[] params = (JdbcControl.SQLParameter[]) arguments[0]; - if (params == null) { - return sqlString.toString(); - } - - sqlString.append(" Params: {"); - for (int i = 0; i < params.length; i++) { - if (i > 0) { sqlString.append(params[i].value.toString()); } - } - sqlString.append("}"); - - } else if (_batchUpdate) { - sqlString.append(" Params: batch update."); - - } else { - sqlString.append(" Params: {"); - boolean first = true; - for (SqlFragment sf : _children) { - if (sf.hasParamValue()) { - Object values[] = sf.getParameterValues(context, method, arguments); - for (Object value : values) { - - if (!first) sqlString.append(", "); else first = false; - sqlString.append(value); - } - } - } - sqlString.append("}"); - } - return sqlString.toString(); - } - - - // /////////////////////////////////////////////////// PRIVATE METHODS /////////////////////////////////////////// - - /** - * Sets the specified parameter in the prepared statement. - * - * @param ps A PreparedStatement. - * @param i index of parameter to set. - * @param value value of the parameter. - * @param sqlType SQL type of value. - * @param cal A calendar instance used to resolve date/time values. - * @throws SQLException If the parameter cannot be set. - */ - private void setPreparedStatementParameter(PreparedStatement ps, int i, Object value, int sqlType, Calendar cal) - throws SQLException { - - if (sqlType == Types.NULL) { - sqlType = _tmf.getSqlType(value); - } - - if (value == null) { - ps.setNull(i, Types.NULL == sqlType ? Types.VARCHAR : sqlType); - return; - } - - switch (sqlType) { - - case Types.VARCHAR: - if (!(value instanceof String)) value = value.toString(); - break; - - case Types.BOOLEAN: - if (value instanceof Boolean) { - ps.setBoolean(i, ((Boolean) value).booleanValue()); - return; - } - break; - - case Types.TIMESTAMP: - if (value instanceof java.util.Calendar) { - Calendar calValue = (Calendar) value; - -// @todo: validate it is correct to comment out call to deprectated method -// if (cal == null) { -// /* NOTE: drivers are inconsistent in their handling of setTimestamp(i,date,cal) -// * so we won't use that, unless the user calls setCalendar(). -// * I'm going with the theory that it makes sense to store -// * the time relative to the Calendar's timezone rather than -// * the system timezone otherwise, using a Calendar would be a no-op. -// */ -// value = new java._sql.Timestamp(calValue.get(Calendar.YEAR) - 1900, -// calValue.get(Calendar.MONTH), -// calValue.get(Calendar.DATE), -// calValue.get(Calendar.HOUR_OF_DAY), -// calValue.get(Calendar.MINUTE), -// calValue.get(Calendar.SECOND), -// calValue.get(Calendar.MILLISECOND)); -// } else { - value = new java.sql.Timestamp(calValue.getTimeInMillis()); -// } - } else if (java.util.Date.class.equals(value.getClass())) { - // some drivers don't like java.util.Date - value = new java.sql.Timestamp(((java.util.Date) value).getTime()); - } - - if (value instanceof java.sql.Timestamp) { - if (cal == null) - ps.setTimestamp(i, (java.sql.Timestamp) value); - else - ps.setTimestamp(i, (java.sql.Timestamp) value, cal); - return; - } - break; - - case Types.DATE: - if (value instanceof java.util.Calendar) { - /* NOTE: see note above - Calendar cal = (Calendar)value; - value = new java._sql.Date(cal.getTimeInMillis()); - ps.setDate(i, (java._sql.Date)value, cal); - return; - */ - Calendar calValue = (Calendar) value; - - // @todo: validate that commenting out deprected method is correct behavior -// if (cal == null) { -// value = new java._sql.Date(calValue.get(Calendar.YEAR - 1900), -// calValue.get(Calendar.MONTH), -// calValue.get(Calendar.DATE)); -// } else { - value = new java.sql.Date(calValue.getTimeInMillis()); -// } - } else if (value.getClass() == java.util.Date.class) { - // some drivers don't like java.util.Date - value = new java.sql.Date(((java.util.Date) value).getTime()); - } - - if (value instanceof java.sql.Date) { - if (cal == null) { - ps.setDate(i, (java.sql.Date) value); - } else { - ps.setDate(i, (java.sql.Date) value, cal); - } - return; - } - break; - - case Types.TIME: - if (value instanceof java.sql.Time) { - if (cal == null) { - ps.setTime(i, (java.sql.Time) value); - } else { - ps.setTime(i, (java.sql.Time) value, cal); - } - return; - } - break; - } - - if (sqlType == Types.NULL) { - ps.setObject(i, value); - } else { - ps.setObject(i, value, sqlType); - } - } - - /** - * Determine if this SQL will generate a callable or prepared statement. - * - * @param args The method's argument list which this SQL annotation was assocatied with. - * @return true if this statement will generated a CallableStatement - */ - private boolean setCallableStatement(Object[] args) { - - // CallableStatement vs. PreparedStatement - if (args != null && args.length == 1 && args[0] != null) { - Class argClass = args[0].getClass(); - if (argClass.isArray() && JdbcControl.SQLParameter.class.isAssignableFrom(argClass.getComponentType())) { - return true; - } - } - return false; - } - - /** - * Build a prepared statement for a batch update. - * - * @param ps The PreparedStatement object. - * @param args The parameter list of the jdbccontrol method. - * @param cal A Calendar instance used to resolve date/time values. - * @throws SQLException If a batch update cannot be performed. - */ - private void doBatchUpdate(PreparedStatement ps, Object[] args, Calendar cal) throws SQLException { - - final int[] sqlTypes = new int[args.length]; - final Object[] objArrays = new Object[args.length]; - - // build an array of type values and object arrays - for (int i = 0; i < args.length; i++) { - sqlTypes[i] = _tmf.getSqlType(args[i].getClass().getComponentType()); - objArrays[i] = TypeMappingsFactory.toObjectArray(args[i]); - } - - final int rowCount = ((Object[]) objArrays[0]).length; - for (int i = 0; i < rowCount; i++) { - for (int j = 0; j < args.length; j++) { - setPreparedStatementParameter(ps, j + 1, ((Object[]) objArrays[j])[i], sqlTypes[j], cal); - } - ps.addBatch(); - } - } - - /** - * Load element values from the SQL annotation which apply to Statements. - * - * @param context ControlBeanContext instance. - * @param method Annotated method. - */ - private void loadSQLAnnotationStatmentOptions(ControlBeanContext context, Method method) { - - final JdbcControl.SQL methodSQL = (JdbcControl.SQL) context.getMethodPropertySet(method, JdbcControl.SQL.class); - - _batchUpdate = methodSQL.batchUpdate(); - _getGeneratedKeys = methodSQL.getGeneratedKeys(); - _genKeyColumnNames = methodSQL.generatedKeyColumnNames(); - _genKeyColumnIndexes = methodSQL.generatedKeyColumnIndexes(); - _scrollType = methodSQL.scrollableResultSet(); - _fetchDirection = methodSQL.fetchDirection(); - _fetchSize = methodSQL.fetchSize(); - _maxRows = methodSQL.maxRows(); - _maxArray = methodSQL.arrayMaxLength(); - - _holdability = methodSQL.resultSetHoldabilityOverride(); - } - - /** - * Checks that all statement options specified in annotation are supported by the database. - * - * @param metaData - * @throws SQLException - */ - private void checkJdbcSupport(DatabaseMetaData metaData) throws SQLException { - - if (_getGeneratedKeys && !metaData.supportsGetGeneratedKeys()) { - throw new ControlException("The database does not support getGeneratedKeys."); - } - - if (_batchUpdate && !metaData.supportsBatchUpdates()) { - throw new ControlException("The database does not support batchUpdates."); - } - - if (_scrollType != JdbcControl.ScrollType.DRIVER_DEFAULT - && !metaData.supportsResultSetConcurrency(_scrollType.getType(), _scrollType.getConcurrencyType())) { - throw new ControlException("The database does not support the ResultSet concurrecy type: " + _scrollType.toString()); - } - - if (_holdability != JdbcControl.HoldabilityType.DRIVER_DEFAULT - && !metaData.supportsResultSetHoldability(_holdability.getHoldability())) { - throw new ControlException("The database does not support the ResultSet holdability type: " + _holdability.toString()); - } - } - - /** - * The much maligned method for computing the maximum number of ResultSet rows this statement should return. - * The values of maxRows and arrayMaxLength are enforced at compile-time by the JdbcControlChecker to be the - * following: MAXROWS_ALL <= maxRows, 0 < arrayMaxLength - * - * @param method The annotated method. - * @return max number of resultSet rows to return from the query. - */ - private int computeMaxRows(Method method) { - - Class returnType = method.getReturnType(); - - final boolean isArray = returnType.isArray(); - final boolean isRowSet = returnType.equals(RowSet.class); - - int maxSet = _maxRows; - if (isArray && _maxArray != JdbcControl.MAXROWS_ALL) { - maxSet = _maxRows == JdbcControl.MAXROWS_ALL ? _maxArray + 1 : Math.min(_maxArray + 1, _maxRows); - } else if (isRowSet && _maxRows > 0) { - maxSet = _maxRows + 1; - } - - return maxSet; - } -} diff --git a/beehive-jdbc-control/src/main/java/org/apache/beehive/controls/system/jdbc/parser/SqlSubstitutionFragment.java b/beehive-jdbc-control/src/main/java/org/apache/beehive/controls/system/jdbc/parser/SqlSubstitutionFragment.java deleted file mode 100644 index 1468b6c..0000000 --- a/beehive-jdbc-control/src/main/java/org/apache/beehive/controls/system/jdbc/parser/SqlSubstitutionFragment.java +++ /dev/null @@ -1,173 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ - -package org.apache.beehive.controls.system.jdbc.parser; - -import org.apache.beehive.controls.api.context.ControlBeanContext; -import org.apache.beehive.controls.system.jdbc.TypeMappingsFactory; - -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.Arrays; - -/** - * Represents a fragement from the SQL annotation's statement member which begins with '{sql:'. - * Substitution fragements are unique in that they are fully evaluated BEFORE a PreparedStatement - * is generated. - *

      - * Supported 'sql:' escapes are subst and fn. subst is the default mode, and will be used if 'sql: ' - * is specified. - * - * The fn variant of this construct has a very ridgid syntax at this point. It must conform to: - * - *

      - *   {sql:fn in(x,{y})}
      - * 
      - * - * where the '{y}' could also be some literal term. - */ -public final class SqlSubstitutionFragment extends SqlFragmentContainer { - - private boolean _hasParamValue = false; - - /** - * Constructor for subst or function with no param substitution - * - * @param child An child which is contained in this fragment. - */ - protected SqlSubstitutionFragment(SqlFragment child) { - super(); - addChild(child); - } - - /** - * Constructor for a function which includes a ReflectionFragment - * - * @param lf A LiteralFragment which contains the text up to the parameter substitution. - * @param rf The ReflectionFragment containing the parameter substitution - * @param lff A LiteralFragment which contains any text which occures after the parameter substitution. - */ - protected SqlSubstitutionFragment(LiteralFragment lf, ReflectionFragment rf, LiteralFragment lff) { - super(); - addChild(lf); - addChild(rf); - addChild(lff); - } - - /** - * Always true for this fragment type - * @return true - */ - protected boolean isDynamicFragment() { return true; } - - /** - * Will be true for this fragment type only if one of its children contains - * a complex sql fragment. - * @return true if there are param values which need to be retrieved. - */ - protected boolean hasParamValue() { - return _hasParamValue; - } - - /** - * Get the parameter values from this fragment and its children. An SqlSubstitutionFragment - * only contains parameters if one of its children has a complex value type. - * - * @param context A ControlBeanContext instance - * @param m The annotated method - * @param args The method parameters - * @return Array of objects. - */ - protected Object[] getParameterValues(ControlBeanContext context, Method m, Object[] args) { - ArrayList paramValues = new ArrayList(); - for (SqlFragment frag : _children) { - if (frag.hasComplexValue(context, m, args)) { - paramValues.addAll(Arrays.asList(frag.getParameterValues(context, m, args))); - } - } - return paramValues.toArray(); - } - - /** - * Return the text for a PreparedStatement from this fragment. This type of fragment - * typically evaluates any reflection parameters at this point. The exception - * is if the reflected result is a ComplexSqlFragment, it that case the sql text - * is retrieved from the fragment in this method. The parameter values are - * retrieved in the getParameterValues method of this class. - * - * @param context A ControlBeanContext instance - * @param m The annotated method - * @param args The method parameters - * @return A String containing the value of this fragment and its children - */ - protected String getPreparedStatementText(ControlBeanContext context, Method m, Object[] args) { - - StringBuilder sb = new StringBuilder(); - for (SqlFragment frag : _children) { - - boolean complexFragment = frag.hasComplexValue(context, m, args); - if (frag.hasParamValue() && !complexFragment) { - Object[] pValues = frag.getParameterValues(context, m, args); - for (Object o : pValues) { - sb.append(processSqlParams(o)); - } - } else { - _hasParamValue |= complexFragment; - sb.append(frag.getPreparedStatementText(context, m, args)); - } - } - return sb.toString(); - } - - -// ////////////////////////////////////////////// Private Methods ////////////////////////////////////////////// - - - /** - * Check for the cases of a null or array type param value. If array type build a string of the array values - * seperated by commas. - * - * @param value - * @return String containing value. - */ - private String processSqlParams(Object value) { - - Object[] arr = null; - if (value != null) { - arr = TypeMappingsFactory.toObjectArray(value); - } - - if (value == null || (arr != null && arr.length == 0)) { - return ""; - } else if (arr != null) { - StringBuilder result = new StringBuilder(); - for (int i = 0; i < arr.length; i++) { - if (i > 0) { - result.append(','); - result.append(arr[i].toString()); - } else { - result.append(arr[i].toString()); - } - } - return result.toString(); - } else { - return value.toString(); - } - } -} diff --git a/beehive-jdbc-control/src/main/java/org/apache/beehive/controls/system/jdbc/parser/Token.java b/beehive-jdbc-control/src/main/java/org/apache/beehive/controls/system/jdbc/parser/Token.java deleted file mode 100644 index ee6a0e0..0000000 --- a/beehive-jdbc-control/src/main/java/org/apache/beehive/controls/system/jdbc/parser/Token.java +++ /dev/null @@ -1,81 +0,0 @@ -/* Generated By:JavaCC: Do not edit this line. Token.java Version 3.0 */ -package org.apache.beehive.controls.system.jdbc.parser; - -/** - * Describes the input token stream. - */ - -public class Token { - - /** - * An integer that describes the kind of this token. This numbering - * system is determined by JavaCCParser, and a table of these numbers is - * stored in the file ...Constants.java. - */ - public int kind; - - /** - * beginLine and beginColumn describe the position of the first character - * of this token; endLine and endColumn describe the position of the - * last character of this token. - */ - public int beginLine, beginColumn, endLine, endColumn; - - /** - * The string image of the token. - */ - public String image; - - /** - * A reference to the next regular (non-special) token from the input - * stream. If this is the last token from the input stream, or if the - * token manager has not read tokens beyond this one, this field is - * set to null. This is true only if this token is also a regular - * token. Otherwise, see below for a description of the contents of - * this field. - */ - public Token next; - - /** - * This field is used to access special tokens that occur prior to this - * token, but after the immediately preceding regular (non-special) token. - * If there are no such special tokens, this field is set to null. - * When there are more than one such special token, this field refers - * to the last of these special tokens, which in turn refers to the next - * previous special token through its specialToken field, and so on - * until the first special token (whose specialToken field is null). - * The next fields of special tokens refer to other special tokens that - * immediately follow it (without an intervening regular token). If there - * is no such token, this field is null. - */ - public Token specialToken; - - /** - * Returns the image. - */ - public String toString() - { - return image; - } - - /** - * Returns a new Token object, by default. However, if you want, you - * can create and return subclass objects based on the value of ofKind. - * Simply add the cases to the switch for all those special cases. - * For example, if you have a subclass of Token called IDToken that - * you want to create if ofKind is ID, simlpy add something like : - * - * case MyParserConstants.ID : return new IDToken(); - * - * to the following switch statement. Then you can cast matchedToken - * variable to the appropriate type and use it in your lexical actions. - */ - public static final Token newToken(int ofKind) - { - switch(ofKind) - { - default : return new Token(); - } - } - -} diff --git a/beehive-jdbc-control/src/main/java/org/apache/beehive/controls/system/jdbc/parser/TokenMgrError.java b/beehive-jdbc-control/src/main/java/org/apache/beehive/controls/system/jdbc/parser/TokenMgrError.java deleted file mode 100644 index aeee2a0..0000000 --- a/beehive-jdbc-control/src/main/java/org/apache/beehive/controls/system/jdbc/parser/TokenMgrError.java +++ /dev/null @@ -1,133 +0,0 @@ -/* Generated By:JavaCC: Do not edit this line. TokenMgrError.java Version 3.0 */ -package org.apache.beehive.controls.system.jdbc.parser; - -public class TokenMgrError extends Error -{ - /* - * Ordinals for various reasons why an Error of this type can be thrown. - */ - - /** - * Lexical error occured. - */ - static final int LEXICAL_ERROR = 0; - - /** - * An attempt wass made to create a second instance of a static token manager. - */ - static final int STATIC_LEXER_ERROR = 1; - - /** - * Tried to change to an invalid lexical state. - */ - static final int INVALID_LEXICAL_STATE = 2; - - /** - * Detected (and bailed out of) an infinite loop in the token manager. - */ - static final int LOOP_DETECTED = 3; - - /** - * Indicates the reason why the exception is thrown. It will have - * one of the above 4 values. - */ - int errorCode; - - /** - * Replaces unprintable characters by their espaced (or unicode escaped) - * equivalents in the given string - */ - protected static final String addEscapes(String str) { - StringBuffer retval = new StringBuffer(); - char ch; - for (int i = 0; i < str.length(); i++) { - switch (str.charAt(i)) - { - case 0 : - continue; - case '\b': - retval.append("\\b"); - continue; - case '\t': - retval.append("\\t"); - continue; - case '\n': - retval.append("\\n"); - continue; - case '\f': - retval.append("\\f"); - continue; - case '\r': - retval.append("\\r"); - continue; - case '\"': - retval.append("\\\""); - continue; - case '\'': - retval.append("\\\'"); - continue; - case '\\': - retval.append("\\\\"); - continue; - default: - if ((ch = str.charAt(i)) < 0x20 || ch > 0x7e) { - String s = "0000" + Integer.toString(ch, 16); - retval.append("\\u" + s.substring(s.length() - 4, s.length())); - } else { - retval.append(ch); - } - continue; - } - } - return retval.toString(); - } - - /** - * Returns a detailed message for the Error when it is thrown by the - * token manager to indicate a lexical error. - * Parameters : - * EOFSeen : indicates if EOF caused the lexicl error - * curLexState : lexical state in which this error occured - * errorLine : line number when the error occured - * errorColumn : column number when the error occured - * errorAfter : prefix that was seen before this error occured - * curchar : the offending character - * Note: You can customize the lexical error message by modifying this method. - */ - protected static String LexicalError(boolean EOFSeen, int lexState, int errorLine, int errorColumn, String errorAfter, char curChar) { - return("Lexical error at line " + - errorLine + ", column " + - errorColumn + ". Encountered: " + - (EOFSeen ? " " : ("\"" + addEscapes(String.valueOf(curChar)) + "\"") + " (" + (int)curChar + "), ") + - "after : \"" + addEscapes(errorAfter) + "\""); - } - - /** - * You can also modify the body of this method to customize your error messages. - * For example, cases like LOOP_DETECTED and INVALID_LEXICAL_STATE are not - * of end-users concern, so you can return something like : - * - * "Internal Error : Please file a bug report .... " - * - * from this method for such cases in the release version of your parser. - */ - public String getMessage() { - return super.getMessage(); - } - - /* - * Constructors of various flavors follow. - */ - - public TokenMgrError() { - } - - public TokenMgrError(String message, int reason) { - super(message); - errorCode = reason; - } - - public TokenMgrError(boolean EOFSeen, int lexState, int errorLine, int errorColumn, String errorAfter, char curChar, int reason) { - this(LexicalError(EOFSeen, lexState, errorLine, errorColumn, errorAfter, curChar), reason); - } -} diff --git a/beehive-jdbc-control/src/main/resources/org/apache/beehive/controls/system/jdbc/parser/SqlGrammar.jj b/beehive-jdbc-control/src/main/resources/org/apache/beehive/controls/system/jdbc/parser/SqlGrammar.jj deleted file mode 100644 index fab977b..0000000 --- a/beehive-jdbc-control/src/main/resources/org/apache/beehive/controls/system/jdbc/parser/SqlGrammar.jj +++ /dev/null @@ -1,315 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ - -options { - STATIC = false; - UNICODE_INPUT = true; - DEBUG_TOKEN_MANAGER = false; - DEBUG_PARSER = false; -} - -// -// parser declarations -// -PARSER_BEGIN(SqlGrammar) - -package org.apache.beehive.controls.system.jdbc.parser; -import java.io.StringReader; - -public class SqlGrammar -{ - private StringBuilder buffer = new StringBuilder(); - public static void main(String[] args) throws Exception - { - SqlGrammar parser = new SqlGrammar(new StringReader(args[0])); - SqlStatement statement = parser.parse(); - System.out.println(statement.toString()); - } -} - -PARSER_END(SqlGrammar) - -// -// token mgr decls -// -TOKEN_MGR_DECLS : { } - -// -// default token mgr state -- just collect anything until a { or ' is read -// - TOKEN: -{ - < NON_EXPRESSION_TEXT : (~["{","}","'"])+ > - | < START_EXPRESSION : "{"> : IN_EXPRESSION - | < SQUOTE : "'"> : IN_LITERAL -} - -// -// this token mgr state is used to skip over literal values which occur in non_expression_text, -// they need to be skipped in this state since they may contain a '{}' which needs to be ignored. -// - TOKEN: -{ - )* "'") > : DEFAULT - | <#ECMA_ESCAPE_SEQUENCE: "\\" | - ( - ["n", "t", "b", "r", "f", "\\", "\""] | - ["0"-"7"] (["0"-"7"])? | - ["0"-"3"] ["0"-"7"] ["0"-"7"] | - ["x","X"] | - ["u","U"] - ) - > - | <#HIT: ["0"-"9","a"-"f","A"-"F"] > -} - -// -// state for parse db control sql expressions, delimited by {} -// - TOKEN [IGNORE_CASE]: -{ - { SwitchTo(DEFAULT); } - | - | )+> - | )*"subst"()+> - | )*"fn"()+> : IN_SQLFN - | )+> : IN_JDBC - | )*"="()*> : IN_JDBC - | )+> : IN_JDBC - | )+> : IN_JDBC - | )+> : IN_JDBC - | )+> : IN_JDBC - | )+> : IN_JDBC - | )+> : IN_JDBC - | - | ) (||".")* > - | < #LETTER : - [ - "\u0024", - "\u0041"-"\u005a", - "\u005f", - "\u0061"-"\u007a", - "\u00c0"-"\u00d6", - "\u00d8"-"\u00f6", - "\u00f8"-"\u00ff", - "\u0100"-"\u1fff", - "\u3040"-"\u318f", - "\u3300"-"\u337f", - "\u3400"-"\u3d2d", - "\u4e00"-"\u9fff", - "\uf900"-"\ufaff" - ] - > - | < #DIGIT : - [ - "\u0030"-"\u0039", - "\u0660"-"\u0669", - "\u06f0"-"\u06f9", - "\u0966"-"\u096f", - "\u09e6"-"\u09ef", - "\u0a66"-"\u0a6f", - "\u0ae6"-"\u0aef", - "\u0b66"-"\u0b6f", - "\u0be7"-"\u0bef", - "\u0c66"-"\u0c6f", - "\u0ce6"-"\u0cef", - "\u0d66"-"\u0d6f", - "\u0e50"-"\u0e59", - "\u0ed0"-"\u0ed9", - "\u1040"-"\u1049" - ] - > -} - -// -// special state for the sql:fn constuct -// - TOKEN [IGNORE_CASE]: -{ - : IN_EXPRESSION - | - | - | - | > - | > - | > - | > -} - - TOKEN: -{ - > { SwitchTo(DEFAULT); } - | - | > : IN_PARAM -} - - TOKEN: -{ - > - | > - | )* "'") > - | > { SwitchTo(IN_JDBC); } -} - - -// -// Parse methods -// - - -// -// Main parse method -// -SqlStatement parse() : -{ - SqlStatement statement = new SqlStatement(); - SqlFragment frag; - Token t, sq; -} -{ - ( - ( - (t= {statement.addChild(new LiteralFragment(t.image));}) - | - (sq=t= {statement.addChild(new LiteralFragment(sq.image + t.image));}) - | - (frag=parseExpression() {statement.addChild(frag);}) - ) - )* - - { - return statement; - } -} - -// -// Parse an expression delimited by '{}' -// -SqlFragment parseExpression() : -{ - Token t, tt = null; - SqlFragment frag = null; -} -{ - ()* - ( - frag = parseSqlEscape() - | frag = parseJdbcEscape() - | (t= (tt=)? {frag = new ReflectionFragment(t.image,(tt == null) ? null : tt.image);}) - ) - ()* - // - - { - return frag; - } -} - -// -// parse an sql: escape sequence -// -SqlSubstitutionFragment parseSqlEscape() : -{ - Token id1, id2; - Token t = null; - SqlSubstitutionFragment frag; - String func = null; -} -{ -( - ( - ( - ( | ) t=) - { - if (t != null) { - frag = new SqlSubstitutionFragment(new ReflectionFragment(t.image)); - } else { - frag = new SqlSubstitutionFragment(new LiteralFragment(func)); - } - } - ) - | - ( - ( - ()* ()* ()* - id1= ()* ()* (t=)? - id2= ()? ()* - ) - { - if (t == null) { - frag = new SqlSubstitutionFragment(new LiteralFragment("(" + id1.image + " IN (" + id2.image + ")")); - } else { - frag = new SqlSubstitutionFragment(new LiteralFragment("(" + id1.image + " IN ("), - new ReflectionFragment(id2.image), - new LiteralFragment("))")); - } - } - ) -) - - { return frag; } -} - -// -// parse a param sub inside of a jdbc escape -// -SqlFragment parseReflect() : -{ - Token t, tt = null; - SqlFragment frag; -} -{ - - (((t=)(tt=)? - { frag = new ReflectionFragment(t.image, (tt == null) ? null : tt.image); }) - - | - ((t=) - { frag = new LiteralFragment(t.image); })) - - - {return frag;} -} - -// -// parse a jdbc escape sequence -// -JdbcFragment parseJdbcEscape() : -{ - Token lit, c; - JdbcFragment jfrag = new JdbcFragment(); - jfrag.addChild(new LiteralFragment("{")); - SqlFragment frag = null; -} - -{ - (c=|c=|c=|c=|c=|c=|c=|c=) - {jfrag.addChild(new LiteralFragment(c.image));} - ( - (lit= {jfrag.addChild(new LiteralFragment(lit.image));} - | (frag=parseReflect()) { jfrag.addChild(frag);}) - )+ - - - { - jfrag.addChild(new LiteralFragment("}")); - return jfrag; - } -} - diff --git a/beehive-jdbc-control/src/main/resources/org/apache/beehive/controls/system/jdbc/parser/strings.properties b/beehive-jdbc-control/src/main/resources/org/apache/beehive/controls/system/jdbc/parser/strings.properties deleted file mode 100644 index 24e70f1..0000000 --- a/beehive-jdbc-control/src/main/resources/org/apache/beehive/controls/system/jdbc/parser/strings.properties +++ /dev/null @@ -1,5 +0,0 @@ - -jdbccontrol.invalid.param=\ - Unable to map the parameter in SQL statement {0} to a parameter of the method \ - {1}. Mapping is accomplished by matching a method parameter name to \ - a value delimited by '{' and '}' in the statement element. diff --git a/beehive-jdbc-control/src/main/resources/org/apache/beehive/controls/system/jdbc/strings.properties b/beehive-jdbc-control/src/main/resources/org/apache/beehive/controls/system/jdbc/strings.properties deleted file mode 100644 index 5a59c76..0000000 --- a/beehive-jdbc-control/src/main/resources/org/apache/beehive/controls/system/jdbc/strings.properties +++ /dev/null @@ -1,26 +0,0 @@ - -jdbccontrol.empty.statement=\ - SQL annotation on method: {0} : Contains an empty statement member. - -jdbccontrol.bad.maxrows=\ - SQL annotation on method: {0} : maxRows set to invalid value: {1} - -jdbccontrol.bad.parse=\ - Error parsing SQL statment on method: {0} : {1} - -jdbccontrol.genkeys=\ - SQL annotation on method: {0} : getGeneratedKeys must be set to \ - true in order to specify generatedKeyColumnNames or generatedKeyColumnIndexes. - -jdbccontrol.genkeycolumns=\ - SQL annotation on method: {0} : Only one of generatedKeyColumnNames or \ - generatedKeyColumnIndexes may be set in the method annotation. - -jdbccontrol.batchupdate=\ - SQL annotation on method: {0} : If batchUpdate is set to true, method must return void or an array of integers. - -jdbccontrol.iterator.returntype=\ - SQL annotation on method: {0} : iteratorElementType must be specified if method returns an Iterator. - -jdbccontrol.scollresultset=\ - SQL annotation on method: {0} : Element scrollableResultSet specified but method does not return a ResultSet. diff --git a/beehive-jms-control/pom.xml b/beehive-jms-control/pom.xml deleted file mode 100644 index 8347ecd..0000000 --- a/beehive-jms-control/pom.xml +++ /dev/null @@ -1,98 +0,0 @@ - - - - - 4.0.0 - - com.moparisthebest.beehive - beehive - 1.0.5-SNAPSHOT - - beehive-jms-control - beehive-jms-control - - ${project.build.outputDirectory} - - - - com.moparisthebest.beehive - beehive-controls - ${project.version} - - - xmlbeans - xbean - - - org.apache.geronimo.specs - geronimo-j2ee_1.4_spec - - - - - - maven-antrun-plugin - - - gensrc - generate-sources - - run - - - - - - - - - - - - - - - - - - - - - - - org.codehaus.mojo - build-helper-maven-plugin - - - generate-sources - - add-source - - - - ${gensrc.dir} - - - - - - - - \ No newline at end of file diff --git a/beehive-jms-control/src/main/java/org/apache/beehive/controls/system/jms/JMSControl.java b/beehive-jms-control/src/main/java/org/apache/beehive/controls/system/jms/JMSControl.java deleted file mode 100644 index f1af3ee..0000000 --- a/beehive-jms-control/src/main/java/org/apache/beehive/controls/system/jms/JMSControl.java +++ /dev/null @@ -1,472 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.system.jms; - -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.ElementType; -import java.lang.annotation.Target; -import java.util.Map; -import javax.jms.Session; - -import org.apache.beehive.controls.api.ControlException; -import org.apache.beehive.controls.api.bean.AnnotationMemberTypes; -import org.apache.beehive.controls.api.bean.ControlInterface; -import org.apache.beehive.controls.api.bean.AnnotationConstraints; -import org.apache.beehive.controls.api.packaging.FeatureInfo; -import org.apache.beehive.controls.api.properties.PropertySet; - -/** - * The control interface for the jms control. - */ -@ControlInterface (defaultBinding="org.apache.beehive.controls.system.jms.impl.JMSControlImpl") -public interface JMSControl -{ - /** - * The destination type. - */ - enum DestinationType - { - /** The destination is set from the object obtained from JNDI. */ - Auto, - /** The destination must be a javax.jms.QueueSender. */ - Queue, - /** The destination must be a javax.jms.TopicPublisher. */ - Topic - }; - - /** - * The header type. Corresponds to the JMS* bean properties on a JMS message. - */ - enum HeaderType - { - /** @see javax.jms.Message#getJMSCorrelationID */ - JMSCorrelationID, - /** @see javax.jms.Message#getJMSDeliveryMode */ - JMSDeliveryMode, - /** @see javax.jms.Message#getJMSPriority */ - JMSPriority, - /** @see javax.jms.Message#getJMSExpiration */ - JMSExpiration, - /** @see javax.jms.Message#getJMSMessageID */ - JMSMessageID, - /** @see javax.jms.Message#getJMSType */ - JMSType, - /** @see javax.jms.Message#getJMSRedelivered */ - JMSRedelivered, - /** @see javax.jms.Message#getJMSTimestamp */ - JMSTimestamp - }; - - /** - * The message type. - */ - enum MessageType - { - /** Message is determined from the body instance class. If the method is not annotated with Body, then the message type is Map. */ - Auto, - /** Message is a {@link javax.jms.TextMessage} */ - Text, - /** Message is a {@link javax.jms.BytesMessage} */ - Bytes, - /** Message is a {@link javax.jms.ObjectMessage} */ - Object, - /** Message is a {@link javax.jms.MapMessage} */ - Map, - /** Message is a {@link javax.jms.Message} as given by the Body parameter */ - JMSMessage - }; - - /** - * The delivery mode. - */ - enum DeliveryMode - { - /** - * @see javax.jms.DeliveryMode#NON_PERSISTENT - */ - NonPersistent, - /** - * @see javax.jms.DeliveryMode#PERSISTENT - */ - Persistent, - /** The default for the provider */ - Auto - }; - - /** - * The acknowledge mode. - */ - enum AcknowledgeMode - { - /** - * @see javax.jms.Session#AUTO_ACKNOWLEDGE - */ - Auto, - /** - * @see javax.jms.Session#CLIENT_ACKNOWLEDGE - */ - Client, - /** - * @see javax.jms.Session#DUPS_OK_ACKNOWLEDGE - */ - DupsOk - }; - - /** - * Indicates the JMSCorrelationID message header. - * - * @deprecated - * @see HeaderType#JMSCorrelationID - */ - public static final String HEADER_CORRELATIONID = HeaderType.JMSCorrelationID.toString(); - - /** - * Indicates the JMSDeliveryMode message header. - * - * @deprecated - * @see HeaderType#JMSDeliveryMode - */ - public static final String HEADER_DELIVERYMODE = HeaderType.JMSDeliveryMode.toString(); - - /** - * Indicates the JMSExpiration message header. - * Use with the getHeaders and setHeaders methods. - * - * @deprecated - * @see HeaderType#JMSExpiration - */ - public static final String HEADER_EXPIRATION = HeaderType.JMSExpiration.toString(); - - /** - * Indicates the JMSMessageID message header. - * - * @deprecated - * @see HeaderType#JMSMessageID - */ - public static final String HEADER_MESSAGEID = HeaderType.JMSMessageID.toString(); - - /** - * Indicates the JMSPriority message header. - * - * @deprecated - * @see HeaderType#JMSPriority - */ - public static final String HEADER_PRIORITY = HeaderType.JMSPriority.toString(); - - /** - * Indicates the JMSRedelivered message header. - * - * @deprecated - * @see HeaderType#JMSRedelivered - */ - public static final String HEADER_REDELIVERED = HeaderType.JMSRedelivered.toString(); - - /** - * Indicates the JMSTimestamp message header. - * - * @deprecated - * @see HeaderType#JMSTimestamp - */ - public static final String HEADER_TIMESTAMP = HeaderType.JMSTimestamp.toString(); - - /** - * Indicates the JMSType message header. - * - * @deprecated - * @see HeaderType#JMSType - */ - public static final String HEADER_TYPE = HeaderType.JMSType.toString(); - - /** - * Get the {@link Session}. - * @return the session. - */ - public Session getSession() throws ControlException; - - /** - * Get the {@link javax.jms.Connection}. - * - * @return the connection. - */ - public javax.jms.Connection getConnection() throws ControlException; - - /** - * Get the {@link javax.jms.Destination}. - * - * @return an instance destination object. - */ - public javax.jms.Destination getDestination() throws ControlException; - - - /** - * Sets the JMS headers to be assigned to the next JMS message - * sent. Note that these headers are set only on the next message, - * subsequent messages will not get these headers. Also note that - * if the body is a message itself, - * then any header set through this map will override headers set - * in the message. - * - * @param headers A map of header names (Strings or HeaderType) to header values. - */ - public void setHeaders(Map headers); - - /** - * Sets a JMS header to be assigned to the next JMS message - * sent. Note that this headers is set only on the next message, - * subsequent messages will not get this header. Also note that - * if the body is a message itself, - * then the header set here will override the header set - * in the message. - * - * @param type the header type. - * @param value the value for the header. - */ - public void setHeader(JMSControl.HeaderType type,Object value); - - /** - * Sets the JMS properties to be assigned to the next JMS message - * sent. Note that these properties are set only on the next - * message, subsequent messages will not get these - * properties. Also note that if the next message is sent through - * a publish method, then any property set through this - * map will override properties set in the message itself. - * - * @param properties A map of property names (Strings) to property - * values. - */ - public void setProperties(Map properties); - - /** - * Set the given JMS property to be assigned to the next JMS message sent. Note that - * this property is set only on the next message, subsequent messages will not get this - * property. Also note that if the body is a message itself, then the property set here - * will override the property set in the message. - * - * @param name the property name. - * @param value the property value. - */ - public void setProperty(String name,Object value); - - /** - * The message type used by the method. The default is to use the type of the body parameter. - */ - @PropertySet(prefix="Message") - @Target({ElementType.METHOD}) - @Retention(RetentionPolicy.RUNTIME) - public @interface Message - { - @FeatureInfo(shortDescription="The message type") - public JMSControl.MessageType value() default JMSControl.MessageType.Auto; - } - - /** - * The method parameter representing a message property with the given name. - * For more information, see the property getter and setter methods on {@link Message}. - */ - @Target({ElementType.PARAMETER}) - @Retention(RetentionPolicy.RUNTIME) - public @interface Property - { - /** - * The property name. - */ - public String name(); - } - - /** - * The method parameter representing a message property with the given name and value. - * For more information, see the property getter and setter methods on {@link Message}. - */ - @PropertySet(prefix="Property") - @Target({ElementType.METHOD}) - @Retention(RetentionPolicy.RUNTIME) - public @interface PropertyValue - { - /** - * The property name. - */ - public String name(); - - /** - * The property value. - */ - public String value(); - - /** - * The property type. - */ - public Class type() default String.class; - - } - - /** - * The method/parameter annotation representing a message priority. If not given - * then the default for the JMS provider is used. - */ - @PropertySet(prefix="Priority") - @Target({ElementType.PARAMETER,ElementType.METHOD}) - @Retention(RetentionPolicy.RUNTIME) - @AnnotationConstraints.AllowExternalOverride - public @interface Priority - { - @AnnotationMemberTypes.Optional - public int value() default -1; - } - - /** - * The method/parameter representing the message JMS type. - */ - @PropertySet(prefix="Type") - @Target({ElementType.PARAMETER, ElementType.METHOD}) - @Retention(RetentionPolicy.RUNTIME) - public @interface Type - { - public String value() default ""; - } - - /** - * The method/parameter representing the message JMS CorrelationID. - */ - @PropertySet(prefix="CorrelationId") - @Target({ElementType.PARAMETER,ElementType.METHOD}) - @Retention(RetentionPolicy.RUNTIME) - public @interface CorrelationId - { - public String value() default ""; - } - - /** - * The method parameter representing a message expiration in milliseconds. - * If not given then the default for the JMS provider is used. - */ - @PropertySet(prefix="Expiration") - @Target({ElementType.PARAMETER,ElementType.METHOD}) - @Retention(RetentionPolicy.RUNTIME) - @AnnotationConstraints.AllowExternalOverride - public @interface Expiration - { - @AnnotationMemberTypes.Optional - public long value() default -1L; - } - - /** - * The method parameter representing a message delivery mode. - * If not given then the default for the JMS provider is used. - */ - @PropertySet(prefix="Delivery") - @Target({ElementType.PARAMETER,ElementType.METHOD}) - @Retention(RetentionPolicy.RUNTIME) - public @interface Delivery - { - public JMSControl.DeliveryMode value() default JMSControl.DeliveryMode.Auto; - } - - /** - * The method parameter representing one or more properties. - */ - @PropertySet(prefix="Properties") - @Target({ElementType.METHOD}) - @Retention(RetentionPolicy.RUNTIME) - public @interface Properties - { - public PropertyValue[] value(); - } - - /** - * The JMS destination annotation for a extended class method. - */ - @PropertySet - @Retention(RetentionPolicy.RUNTIME) - @Target({ElementType.TYPE,ElementType.FIELD}) - @AnnotationConstraints.AllowExternalOverride - public @interface Destination - { - /** - * The JNDI name of the queue or topic. - */ - // BUG: There should be a JMS_TOPIC_OR_QUEUE resource type. - @FeatureInfo(shortDescription="JNDI name of the queue or topic") - @AnnotationMemberTypes.JndiName( resourceType = AnnotationMemberTypes.JndiName.ResourceType.OTHER ) - public String sendJndiName(); - - /** - * The Correlation-Id for messages. - */ - @FeatureInfo(shortDescription="Correlation-Id for messages") - @AnnotationMemberTypes.Optional - public String sendCorrelationProperty() default ""; - - /** - * The JNDI name of queue connection factory. - */ - @FeatureInfo(shortDescription="JNDI name of queue connection factory") - public String jndiConnectionFactory(); - - /** - * The destination type (DestinationType). The default is to use the type of the destination object named by the JNDI name. - */ - @FeatureInfo(shortDescription="The destination type (DestinationType). The default is to use the type of the destination object named by the JNDI name") - @AnnotationMemberTypes.Optional - public JMSControl.DestinationType sendType() default JMSControl.DestinationType.Auto; - - /** - * True if send is transacted. The default is transacted. - */ - @FeatureInfo(shortDescription="True if send is transacted. The default is transacted") - @AnnotationMemberTypes.Optional - public boolean transacted() default true; - - /** - * The acknowledge mode. The default is to use auto-acknowledge. - */ - @FeatureInfo(shortDescription="The acknowledge mode. The default is to use auto-acknowledge") - @AnnotationMemberTypes.Optional - public JMSControl.AcknowledgeMode acknowledgeMode() default JMSControl.AcknowledgeMode.Auto; - - /** - * The JNDI context factory. - */ - @FeatureInfo(shortDescription="JNDI context factory") - @AnnotationMemberTypes.Optional - public String jndiContextFactory() default ""; - - /** - * The JNDI provider URL. - */ - @FeatureInfo(shortDescription="JNDI provider URL") - @AnnotationMemberTypes.Optional - @AnnotationMemberTypes.URI - public String jndiProviderURL() default ""; - - /** - * The JNDI security principal. - */ - @FeatureInfo(shortDescription="JNDI security principal") - @AnnotationMemberTypes.Optional - public String jndiUsername() default ""; - - /** - * The JNDI security credentials. - */ - @FeatureInfo(shortDescription="JNDI security credentials") - @AnnotationMemberTypes.Optional - public String jndiPassword() default ""; - } -} diff --git a/beehive-jms-control/src/main/java/org/apache/beehive/controls/system/jms/impl/JMSControlImpl.java b/beehive-jms-control/src/main/java/org/apache/beehive/controls/system/jms/impl/JMSControlImpl.java deleted file mode 100644 index def48e4..0000000 --- a/beehive-jms-control/src/main/java/org/apache/beehive/controls/system/jms/impl/JMSControlImpl.java +++ /dev/null @@ -1,925 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.system.jms.impl; - -import java.io.Serializable; -import java.lang.reflect.Method; -import java.lang.reflect.InvocationTargetException; -import java.util.Iterator; -import java.util.Map; -import java.util.HashMap; - -import javax.jms.JMSException; -import javax.jms.MapMessage; -import javax.jms.MessageProducer; -import javax.jms.Queue; -import javax.jms.QueueConnection; -import javax.jms.QueueConnectionFactory; -import javax.jms.ConnectionFactory; -import javax.jms.QueueSession; -import javax.jms.Session; -import javax.jms.BytesMessage; -import javax.jms.TopicConnection; -import javax.jms.TopicConnectionFactory; -import javax.jms.Topic; -import javax.jms.TopicPublisher; -import javax.jms.TopicSession; - -import org.apache.beehive.controls.api.ControlException; -import org.apache.beehive.controls.api.events.EventHandler; -import org.apache.beehive.controls.api.context.ControlBeanContext; -import org.apache.beehive.controls.api.context.Context; -import org.apache.beehive.controls.api.context.ResourceContext; -import org.apache.beehive.controls.api.bean.ControlImplementation; -import org.apache.beehive.controls.api.bean.Extensible; -import org.apache.beehive.controls.api.bean.Control; -import org.apache.beehive.controls.system.jms.JMSControl; -import org.apache.beehive.controls.system.jndi.JndiControlBean; - -/** - *

      - * Implementation of the {@link JMSControl}. - *

      - */ -@ControlImplementation -public class JMSControlImpl - implements JMSControl, Extensible, java.io.Serializable { - - private static Class XMLOBJ_CLASS = null; - - static { - try { - XMLOBJ_CLASS = Class.forName("org.apache.xmlbeans.XmlObject"); - } - catch (ClassNotFoundException e) { - // NOOP if apache xml beans not present - } - } - - /** - * Implementation of the {@link org.apache.beehive.controls.system.jms.JMSControl#getSession()} method. - * - * @return the {@link Session} - * @throws ControlException when an error occurs trying to create a JMS session - */ - public Session getSession() throws ControlException { - if (_session == null) { - try { - switch (getDestinationType()) { - case Auto: - determineDestination(); - return getSession(); - case Topic: - createTopicSession(); - break; - case Queue: - createQueueSession(); - break; - } - } - catch (JMSException e) { - throw new ControlException("Failure to get JMS connection or session", e); - } - } - return _session; - } - - /** - * Get the JMS {@link javax.jms.Destination}. Implementation of the - * {@link org.apache.beehive.controls.system.jms.JMSControl#getDestination()} method. - */ - public javax.jms.Destination getDestination() throws ControlException { - if (_destination == null) { - _destination = - (javax.jms.Destination) getJndiControl().getResource(getDestinationProperties().sendJndiName(), - javax.jms.Destination.class); - } - return _destination; - } - - /** - * Get the JMS {@link javax.jms.Connection}. Implementation of the - * {@link JMSControl#getConnection()}. - */ - public javax.jms.Connection getConnection() throws ControlException { - getSession(); - return _connection; - } - - /** - * @see JMSControl#setHeaders - */ - public void setHeaders(Map headers) { - if (headers == null) - return; - - HashMap map = new HashMap(); - for (Object name : headers.keySet()) { - - Object value = headers.get(name); - - HeaderType type = null; - /* - * Allow for string valued or HeaderType valued - * map entries. - */ - if (name instanceof HeaderType) - type = (HeaderType) name; - else { - if (name.equals(HeaderType.JMSCorrelationID.toString())) - type = HeaderType.JMSCorrelationID; - else if (name.equals(HeaderType.JMSDeliveryMode.toString())) - type = HeaderType.JMSDeliveryMode; - else if (name.equals(HeaderType.JMSExpiration.toString())) - type = HeaderType.JMSExpiration; - else if (name.equals(HeaderType.JMSMessageID.toString())) - type = HeaderType.JMSMessageID; - else if (name.equals(HeaderType.JMSPriority.toString())) - type = HeaderType.JMSPriority; - else if (name.equals(HeaderType.JMSRedelivered.toString())) - type = HeaderType.JMSRedelivered; - else if (name.equals(HeaderType.JMSTimestamp.toString())) - type = HeaderType.JMSTimestamp; - else if (name.equals(HeaderType.JMSType.toString())) - type = HeaderType.JMSType; - else throw new IllegalArgumentException("Invalid JMS header type '" + name + "'"); - } - map.put(type, value); - } - - for (HeaderType key : map.keySet()) - setHeader(key, map.get(key)); - } - - /** - * @see JMSControl#setHeader - */ - public void setHeader(JMSControl.HeaderType type, Object value) { - if (_headers == null) - _headers = new HashMap(); - - _headers.put(type, value); - } - - - /** - * @see JMSControl#setProperties - */ - public void setProperties(Map properties) { - if (properties == null) - return; - - /* todo: this is making an implicit assumption that the Map contains Strings */ - Iterator i = properties.keySet().iterator(); - while (i.hasNext()) { - String name = i.next(); - Object value = properties.get(name); - setProperty(name, value); - } - } - - /** - * @see JMSControl#setProperty - */ - public void setProperty(String name, Object value) { - if (_properties == null) - _properties = new HashMap(); - - _properties.put(name, value); - } - - - /** - * Implementation of the {@link Extensible#invoke(java.lang.reflect.Method, Object[])} method. This - * method allows extension by interface. - */ - public Object invoke(Method method, Object[] args) throws ControlException { - assert (method != null && args != null); - javax.jms.Message m = null; - boolean isBody = false; - try { - Destination props = getDestinationProperties(); - Session session = getSession(); - String jmsType = null; - String correlationId = null; - /* - * Set the deliveryMode, priority and expiration. - */ - int deliveryMode = getProducer().getDeliveryMode(); - int priority = getProducer().getPriority(); - long expiration = getProducer().getTimeToLive(); - Object mode = getHeader(HeaderType.JMSDeliveryMode); - if (mode != null) - deliveryMode = deliveryModeToJmsMode(mode); - - Integer v = getHeaderAsInteger(HeaderType.JMSPriority); - if (v != null) - priority = v.intValue(); - - Long l = getHeaderAsLong(HeaderType.JMSExpiration); - if (l != null) - expiration = l.longValue(); - - /* Get the body of the message. */ - Object body = null; - - // Check to see if any parameter has annotation. If it doesn't then don't bother checking them. - boolean hasAnnotation = method.getParameterAnnotations().length > 0; - for (int i = 0; i < args.length; i++) { - if (hasAnnotation) { - if (_context.getParameterPropertySet(method, i, Priority.class) != null) - continue; - if (_context.getParameterPropertySet(method, i, Property.class) != null) - continue; - if (_context.getParameterPropertySet(method, i, Expiration.class) != null) - continue; - if (_context.getParameterPropertySet(method, i, Delivery.class) != null) - continue; - if (_context.getParameterPropertySet(method, i, Type.class) != null) - continue; - if (_context.getParameterPropertySet(method, i, CorrelationId.class) != null) - continue; - } - - if (isBody) - throw new IllegalArgumentException("At most one parameter may be defined as the body of the JMS message"); - - body = args[i]; - isBody = true; - } - /* - * Get the method level annotation properties. - */ - Priority pri = _context.getMethodPropertySet(method, Priority.class); - if (pri != null && pri.value() != -1) - priority = pri.value(); - - Expiration exp = _context.getMethodPropertySet(method, Expiration.class); - if (exp != null && exp.value() != -1L) - expiration = exp.value(); - - Delivery del = _context.getMethodPropertySet(method, Delivery.class); - if (del != null && del.value() != DeliveryMode.Auto) - deliveryMode = deliveryModeToJmsMode(del.value()); - - Type t = _context.getMethodPropertySet(method, Type.class); - if (t != null && t.value().length() != 0) - jmsType = t.value(); - - CorrelationId id = _context.getMethodPropertySet(method, CorrelationId.class); - if (id != null && id.value().length() != 0) - correlationId = id.value(); - - /* Create a message of the appropriate type and set the body. */ - JMSControl.Message mess = _context.getMethodPropertySet(method, JMSControl.Message.class); - MessageType type = MessageType.Auto; - if (mess != null) - type = mess.value(); - - if (type.equals(MessageType.Auto)) { - if (body instanceof byte[]) - type = MessageType.Bytes; - else if (body instanceof Map || !isBody) - type = MessageType.Map; - else if (body instanceof String) - type = MessageType.Text; - else if (XMLOBJ_CLASS != null && XMLOBJ_CLASS.isAssignableFrom(body.getClass())) - type = MessageType.Text; - else if (body instanceof javax.jms.Message) - type = MessageType.JMSMessage; - else if (body instanceof Serializable) - type = MessageType.Object; - else throw new ControlException("Cannot determine message type from body"); - } - switch (type) { - case Object: - checkBody(body, Serializable.class); - m = session.createObjectMessage((Serializable) body); - break; - case Bytes: - BytesMessage sm; - checkBody(body, byte[].class); - m = sm = session.createBytesMessage(); - sm.writeBytes((byte[]) body); - break; - case Text: - if (XMLOBJ_CLASS != null && XMLOBJ_CLASS.isAssignableFrom(body.getClass())) { - try { - Method xmlText = XMLOBJ_CLASS.getMethod("xmlText", new Class[]{}); - body = xmlText.invoke(body, new Object[]{}); - } - catch (NoSuchMethodException e) { - throw new ControlException(e.getMessage(), e); - } - catch (IllegalAccessException e) { - throw new ControlException(e.getMessage(), e); - } - catch (InvocationTargetException e) { - throw new ControlException(e.getMessage(), e); - } - } - checkBody(body, String.class); - m = session.createTextMessage((String) body); - break; - case Map: - MapMessage mm; - checkBody(body, Map.class); - m = mm = session.createMapMessage(); - Map map = (Map)body; - Iterator iter = map.keySet().iterator(); - while (iter.hasNext()) { - String key = (String) iter.next(); - mm.setObject(key, map.get(key)); - } - break; - case JMSMessage: - checkBody(body, javax.jms.Message.class); - m = (javax.jms.Message) body; - break; - } - /* - * Set the correlation id if given. - */ - String correlationProp = props.sendCorrelationProperty(); - if (correlationProp != null && correlationProp.length() == 0) - correlationProp = null; - - if (correlationId == null) - correlationId = getHeaderAsString(HeaderType.JMSCorrelationID); - - Properties jmsProps = (Properties)_context.getMethodPropertySet(method, Properties.class); - if (jmsProps != null && jmsProps.value() != null) { - PropertyValue[] jprops = jmsProps.value(); - for (int i = 0; i < jprops.length; i++) { - PropertyValue jprop = jprops[i]; - Class cls = jprop.type(); - if (cls.equals(String.class)) - m.setStringProperty(jprop.name(), jprop.value()); - else if (cls.equals(Integer.class)) - m.setIntProperty(jprop.name(), valueAsInteger(jprop.value())); - else if (cls.equals(Long.class)) - m.setLongProperty(jprop.name(), valueAsLong(jprop.value())); - else - throw new IllegalArgumentException("Invalid type for property-value"); - } - } - /* - * Set the properties/headers of the message from - * the parameters to the invoke. - */ - if (hasAnnotation) { - for (int i = 0; i < args.length; i++) { - Property jmsProp = (Property) _context.getParameterPropertySet(method, i, Property.class); - if (jmsProp != null) - m.setObjectProperty(jmsProp.name(), args[i]); - - Priority jmsPriority = (Priority) _context.getParameterPropertySet(method, i, Priority.class); - if (jmsPriority != null) { - Integer p = valueAsInteger(args[i]); - if (p != null) - priority = p.intValue(); - } - Expiration jmsExpiration = (Expiration) _context.getParameterPropertySet(method, i, Expiration.class); - if (jmsExpiration != null) { - Long e = valueAsLong(args[i]); - if (e != null) - expiration = e.longValue(); - } - Delivery jmsDelivery = (Delivery) _context.getParameterPropertySet(method, i, Delivery.class); - if (jmsDelivery != null && args[i] != null) { - deliveryMode = deliveryModeToJmsMode(args[i]); - } - t = (Type) _context.getParameterPropertySet(method, i, Type.class); - if (t != null && args[i] != null) - jmsType = (String) args[i]; - - CorrelationId jmsId = (CorrelationId)_context.getParameterPropertySet(method, i, CorrelationId.class); - if (jmsId != null && args[i] != null) - correlationId = (String) args[i]; - } - } - if (correlationProp != null) - m.setStringProperty(correlationProp, correlationId); - else - m.setJMSCorrelationID(correlationId); - - /* Set the headers and properties from maps provided by setProperties() and setHeaders() */ - m.setJMSExpiration(expiration); - m.setJMSDeliveryMode(deliveryMode); - m.setJMSPriority(priority); - setMessageHeaders(m); - setMessageProperties(m); - expiration = m.getJMSExpiration(); - deliveryMode = m.getJMSDeliveryMode(); - priority = m.getJMSPriority(); - - _headers = null; - _properties = null; - - /* Send the message. */ - switch (getDestinationType()) { - case Topic: - ((TopicPublisher) getProducer()).publish(m, deliveryMode, priority, expiration); - break; - case Queue: - getProducer().send(m, deliveryMode, priority, expiration); - break; - } - } - catch (JMSException e) { - throw new ControlException("Error in sending message", e); - } - return m; - } - - - @EventHandler(field="_resourceContext", eventSet=ResourceContext.ResourceEvents.class, eventName="onAcquire") - public void onAcquire() { - } - - /* - * The onRelease event handler for the associated context This method will - * release all resource acquired by onAcquire. - */ - @EventHandler(field="_resourceContext", eventSet=ResourceContext.ResourceEvents.class, eventName="onRelease") - public void onRelease() { - close(); - } - - /** - * Release any JMS related resources. - */ - protected void close() { - try { - if (_producer != null) { - _producer.close(); - _producer = null; - } - if (_session != null) { - _session.close(); - _session = null; - } - if (_connection != null) { - _connection.close(); - _connection = null; - } - } - catch (JMSException e) { - throw new ControlException("Unable to release JMS resource", e); - } - } - - /** - * Deterimine whether we are working with a queue or a topic. - */ - protected void determineDestination() { - Destination props = getDestinationProperties(); - String factory = props.jndiConnectionFactory(); - ConnectionFactory cfactory = - (ConnectionFactory) getJndiControl().getResource(factory, ConnectionFactory.class); - - if (cfactory instanceof QueueConnectionFactory && cfactory instanceof TopicConnectionFactory) { - javax.jms.Destination dest = getDestination(); - if (dest instanceof Queue && dest instanceof Topic) { - /* Try to create a topic producer...if fail then assume that it is a queue */ - try { - createTopicSession(); - _producer = ((TopicSession) getSession()).createPublisher((Topic) getDestination()); - } - catch (Exception e) { - close(); - _destinationType = DestinationType.Queue; - return; - } - _destinationType = DestinationType.Topic; - } - else { - if (dest instanceof javax.jms.Queue) - _destinationType = DestinationType.Queue; - if (dest instanceof javax.jms.Topic) - _destinationType = DestinationType.Topic; - } - } - else { - if (cfactory instanceof QueueConnectionFactory) - _destinationType = DestinationType.Queue; - if (cfactory instanceof TopicConnectionFactory) - _destinationType = DestinationType.Topic; - } - } - - /** - * Get the queue/topic producer. - * - * @return the JMS producer. - */ - protected MessageProducer getProducer() { - if (_producer == null) { - // Acquire the publisher/sender. - try { - javax.jms.Session sess = getSession(); - switch (getDestinationType()) { - case Auto: - try { - _producer = ((QueueSession) sess).createSender((Queue)getDestination()); - } - catch (Exception e) { - /* todo: should never be catching an exception and running code like this */ - _producer = ((TopicSession) sess).createPublisher((Topic)getDestination()); - } - break; - case Topic: - _producer = ((TopicSession) sess).createPublisher((Topic)getDestination()); - break; - case Queue: - _producer = ((QueueSession) sess).createSender((Queue)getDestination()); - break; - } - } - catch (JMSException e) { - throw new ControlException("Unable to acquire JMS resource", e); - } - } - return _producer; - } - - - /** - * Creates a topic session. - */ - protected void createTopicSession() - throws JMSException { - Destination props = getDestinationProperties(); - String factory = props.jndiConnectionFactory(); - boolean transacted = props.transacted(); - - AcknowledgeMode ackMode = props.acknowledgeMode(); - TopicConnectionFactory connFactory = - (TopicConnectionFactory) getJndiControl().getResource(factory, TopicConnectionFactory.class); - - _connection = connFactory.createTopicConnection(); - _session = ((TopicConnection) _connection).createTopicSession(transacted, modeToJmsMode(ackMode)); - } - - - /** - * Creates a queue session. - */ - protected void createQueueSession() - throws JMSException { - Destination props = getDestinationProperties(); - String factory = props.jndiConnectionFactory(); - boolean transacted = props.transacted(); - AcknowledgeMode ackMode = props.acknowledgeMode(); - QueueConnectionFactory connFactory = - (QueueConnectionFactory) getJndiControl().getResource(factory, QueueConnectionFactory.class); - _connection = connFactory.createQueueConnection(); - _session = ((QueueConnection) _connection).createQueueSession(transacted, modeToJmsMode(ackMode)); - } - - /** - * Convert the enum to the JMS ack mode. - * - * @param mode the enum mode. - * @return the JMS mode. - */ - protected int modeToJmsMode(AcknowledgeMode mode) { - if (mode == AcknowledgeMode.Auto) - return Session.AUTO_ACKNOWLEDGE; - else if (mode == AcknowledgeMode.Client) - return Session.CLIENT_ACKNOWLEDGE; - else - return Session.DUPS_OK_ACKNOWLEDGE; - } - - /** - * Convert the object to the JMS delivery mode. - * - * @param value a integer valued string, integer or DeliveryMode. - * @return the JMS delivery mode. - */ - protected int deliveryModeToJmsMode(Object value) { - if (value instanceof DeliveryMode) { - DeliveryMode mode = (DeliveryMode) value; - switch (mode) { - case Persistent: - return javax.jms.DeliveryMode.PERSISTENT; - case NonPersistent: - return javax.jms.DeliveryMode.NON_PERSISTENT; - } - } - - if (value instanceof Number) - return ((Number) value).intValue(); - else if (value instanceof String) - return Integer.parseInt((String) value); - else throw new IllegalArgumentException("Invalid delivery mode value"); - } - - /** - * Check the given value to see if is appropriate for the given message value class. - * - * @param value the body. - * @param cls the expected class. - */ - protected void checkBody(Object value, Class cls) - throws ControlException { - - if (!cls.isInstance(value)) - throw new ControlException("Message body is not of correct type expected " + cls.getName()); - } - - /** - * Get the destination annotation info for the message. - * - * @return the destination method annotation. - */ - protected Destination getDestinationProperties() { - return _context.getControlPropertySet(Destination.class); - } - - /** - * Get the destination type as specified via the - * {@link org.apache.beehive.controls.system.jms.JMSControl.Destination#sendType()} - * annotation. - */ - protected DestinationType getDestinationType() - throws ControlException { - - /* - when previously unset, obtain from the value of the annotation. - this value tends to be overridden later based on the configuration - of the control instance. - */ - if (_destinationType == null) { - Destination d = getDestinationProperties(); - assert d != null : "Found a null Destination annotation"; - _destinationType = d.sendType(); - } - - return _destinationType; - } - - /** - * Set the properties of the given message. - * - * @param msg the message. - */ - protected void setMessageProperties(javax.jms.Message msg) - throws ControlException { - - if (_properties == null) - return; - - Iterator i = _properties.keySet().iterator(); - while (i.hasNext()) { - String name = (String) i.next(); - Object value = _properties.get(name); - try { - msg.setObjectProperty(name, value); - } - catch (JMSException e) { - throw new ControlException("Cannot set property '" + name + "' into JMS message"); - } - } - } - - /** - * Set the headers. Accessing msg may throw exception. - * - * @param msg the message. - */ - protected void setMessageHeaders(javax.jms.Message msg) - throws ControlException { - - if (_headers == null) - return; - - for (HeaderType name : _headers.keySet()) { - Object value = _headers.get(name); - setMessageHeader(msg, name, value); - } - } - - /** - * Set the header value of the given message. - * - * @param msg the message. - * @param type the header type. - * @param value the value. - */ - protected void setMessageHeader(javax.jms.Message msg, HeaderType type, Object value) { - switch (type) { - case JMSCorrelationID: - try { - if (value instanceof byte[]) - msg.setJMSCorrelationIDAsBytes((byte[]) value); - else if (value instanceof String) - msg.setJMSCorrelationID((String) value); - } - catch (javax.jms.JMSException e) { - throw new ControlException("Error setting JMSCorrelationID for message", e); - } - break; - case JMSPriority: - try { - if (value instanceof Integer) - msg.setJMSPriority((Integer)value); - else if (value instanceof String) - msg.setJMSPriority(Integer.getInteger((String) value)); - } - catch (javax.jms.JMSException e) { - throw new ControlException("Error setting JMSPriority for message", e); - } - break; - case JMSExpiration: - try { - if (value instanceof Long) - msg.setJMSExpiration((Long)value); - else if (value instanceof String) - msg.setJMSExpiration(Long.parseLong((String) value)); - } - catch (javax.jms.JMSException e) { - throw new ControlException("Error setting JMSExpiration for message", e); - } - break; - case JMSType: - try { - msg.setJMSType((String) value); - } - catch (javax.jms.JMSException e) { - throw new ControlException("Error setting JMSType for message", e); - } - break; - } - } - - /** - * Get the header type value. - * - * @param name the header type. - * @return the value or null. - */ - protected Object getHeader(HeaderType name) { - assert name != null : "Can't get header with null name"; - - if (_headers == null) - return null; - else return _headers.get(name.toString()); - } - - /** - * Get the header type value as a string. - * - * @param name the header type. - * @return the string value or null. - */ - protected String getHeaderAsString(HeaderType name) { - Object obj = getHeader(name); - return obj != null ? obj.toString() : null; - } - - /** - * Get the header type value as a int. - * - * @param name the header type. - * @return the int value or null. - */ - protected Integer getHeaderAsInteger(HeaderType name) { - return valueAsInteger(getHeader(name)); - } - - /** - * Return the given value as an integer. - * - * @param obj a string or number object. - * @return the integer value or null. - */ - protected Integer valueAsInteger(Object obj) { - if (obj instanceof String) - return Integer.parseInt((String)obj); - else if (obj instanceof Integer) - return (Integer)obj; - else if (obj instanceof Number) - return new Integer(((Number)obj).intValue()); - return null; - } - - /** - * Get the header type value as a long. - * - * @param name the header type. - * @return the long value or null. - */ - protected Long getHeaderAsLong(HeaderType name) { - return valueAsLong(getHeader(name)); - } - - /** - * Return the given value as a long. - * - * @param obj a string or number object. - * @return the long value or null. - */ - protected Long valueAsLong(Object obj) { - if (obj instanceof String) - return Long.parseLong((String) obj); - else if (obj instanceof Long) - return (Long) obj; - else if (obj instanceof Number) - return new Long(((Number)obj).longValue()); - return null; - } - - /** - * Get the JNDI control instance. - * - * @return the jndi-control. - */ - protected JndiControlBean getJndiControl() { - if (!_jndiInitialized) { - - _jndiInitialized = true; - Destination dest = getDestinationProperties(); - - String contextFactory = nullIfEmpty(dest.jndiContextFactory()); - if (contextFactory != null) - _jndiControl.setFactory(contextFactory); - - String providerURL = nullIfEmpty(dest.jndiProviderURL()); - if (providerURL != null) - _jndiControl.setUrl(providerURL); - - String userName = nullIfEmpty(dest.jndiUsername()); - if (userName != null) - _jndiControl.setJndiSecurityPrincipal(userName); - - String password = nullIfEmpty(dest.jndiPassword()); - if (password != null) - _jndiControl.setJndiSecurityCredentials(password); - } - return _jndiControl; - } - - /** - * Return null if the given string is null or an empty string. - * - * @param str a string. - * @return null or the string. - */ - protected String nullIfEmpty(String str) { - if (str == null || str.trim().length() == 0) { - return null; - } - return str; - } - - - @Context - private ResourceContext _resourceContext; - - @Context - private ControlBeanContext _context; - - @Control - private JndiControlBean _jndiControl; - - /** The destination */ - private transient javax.jms.Destination _destination; - - private transient DestinationType _destinationType = null; - - /** The JMS connection. */ - private transient javax.jms.Connection _connection; - - /** The JMS session */ - private transient Session _session; - - /** The message producer. */ - private transient MessageProducer _producer; - - /** The JNDI control has been initialized */ - private boolean _jndiInitialized = false; - - /** The headers to set in the next message to be sent. */ - private Map _headers; - - /** The properties to set in the next message to be sent. */ - private Map _properties; -} diff --git a/beehive-jms-control/src/main/java/org/apache/beehive/controls/system/jndi/JndiControl.java b/beehive-jms-control/src/main/java/org/apache/beehive/controls/system/jndi/JndiControl.java deleted file mode 100644 index 441c846..0000000 --- a/beehive-jms-control/src/main/java/org/apache/beehive/controls/system/jndi/JndiControl.java +++ /dev/null @@ -1,91 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ - -package org.apache.beehive.controls.system.jndi; - -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; -import java.lang.annotation.ElementType; -import javax.naming.InitialContext; - -import org.apache.beehive.controls.api.ControlException; -import org.apache.beehive.controls.api.bean.ControlInterface; -import org.apache.beehive.controls.api.bean.AnnotationMemberTypes; -import org.apache.beehive.controls.api.packaging.FeatureInfo; -import org.apache.beehive.controls.api.properties.PropertySet; - -/** - * The Jndi Control encapsulates access to the JNDI context. It - * provides annotation for setting the factory and provider URL. - */ -@ControlInterface (defaultBinding="org.apache.beehive.controls.system.jndi.impl.JndiControlImpl") -public interface JndiControl -{ - /** - * Get a JNDI based resource. - * @param resource the resource name. - * @param resourceClass the resource class. - * @return the resource object. - * @throws ControlException - */ - public Object getResource(String resource,Class resourceClass) throws ControlException; - - /** - * Get the JNDI initial context. - * @return the initial context. - * - * @throws ControlException - */ - public InitialContext getInitialContext() throws ControlException; - - @PropertySet - @Retention(RetentionPolicy.RUNTIME) - @Target({ElementType.TYPE,ElementType.FIELD}) - public @interface Properties { - /** - * The JNDI context factory class name. - */ - @FeatureInfo(shortDescription="JNDI context factory") - @AnnotationMemberTypes.Optional - String factory(); - - /** - * The JNDI provider URL. - */ - @FeatureInfo(shortDescription="JNDI provider URL") - @AnnotationMemberTypes.Optional - @AnnotationMemberTypes.URI - String url(); - - /** - * The JNDI security principal. - */ - @FeatureInfo(shortDescription="JNDI security principal") - @AnnotationMemberTypes.Optional - public String jndiSecurityPrincipal() default ""; - - /** - * The JNDI security credentials. - */ - @FeatureInfo(shortDescription="JNDI security credentials") - @AnnotationMemberTypes.Optional - public String jndiSecurityCredentials() default ""; - } -} diff --git a/beehive-jms-control/src/main/java/org/apache/beehive/controls/system/jndi/impl/JndiControlImpl.java b/beehive-jms-control/src/main/java/org/apache/beehive/controls/system/jndi/impl/JndiControlImpl.java deleted file mode 100644 index 47e1c10..0000000 --- a/beehive-jms-control/src/main/java/org/apache/beehive/controls/system/jndi/impl/JndiControlImpl.java +++ /dev/null @@ -1,117 +0,0 @@ -/* - * 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. - * - * $Header:$ - */ -package org.apache.beehive.controls.system.jndi.impl; - -import java.util.Hashtable; -import javax.naming.InitialContext; -import javax.naming.NamingException; - -import org.apache.beehive.controls.api.ControlException; -import org.apache.beehive.controls.api.bean.ControlImplementation; -import org.apache.beehive.controls.api.context.ControlBeanContext; -import org.apache.beehive.controls.api.context.Context; -import org.apache.beehive.controls.system.jndi.JndiControl; - -/** - * Implementation of the jndi control. - */ -@ControlImplementation -public class JndiControlImpl - implements JndiControl, java.io.Serializable { - - /** - * @see JndiControl#getResource(String, Class) - */ - public Object getResource(String resource, Class resourceClass) throws ControlException { - - try { - InitialContext cntxt = getInitialContext(); - Object obj = cntxt.lookup(resource); - if (resourceClass != null && !(resourceClass.isInstance(obj))) - throw new ControlException("JNDI resource '" + resource + "' is not an instance of '" + resourceClass.getName() + "'"); - else return obj; - } - catch (NamingException e) { - throw new ControlException("Cannot load JNDI resource '" + resource + "'", e); - } - } - - /** - * Get the initial context. - * - * @return the initial context. - */ - public InitialContext getInitialContext() throws ControlException { - if (_initialContext != null) { - return _initialContext; - } - Properties props = (Properties) _context.getControlPropertySet(Properties.class); - String url = nullIfEmpty(props.url()); - String factory = nullIfEmpty(props.factory()); - if (url == null && factory == null) { - try { - return new InitialContext(); - } - catch (NamingException e) { - throw new ControlException("Cannot get default JNDI initial context", e); - } - - } - if (url == null || factory == null) { - throw new ControlException("Both the provider-url and jndi factory need to be provided"); - - } - Hashtable env = new Hashtable(); - env.put(javax.naming.Context.INITIAL_CONTEXT_FACTORY, factory); - env.put(javax.naming.Context.PROVIDER_URL, url); - - String username = nullIfEmpty(props.jndiSecurityPrincipal()); - if (username != null) - env.put(javax.naming.Context.SECURITY_PRINCIPAL, username); - - String password = nullIfEmpty(props.jndiSecurityCredentials()); - if (password != null) - env.put(javax.naming.Context.SECURITY_CREDENTIALS, password); - - try { - return _initialContext = new InitialContext(env); - } - catch (NamingException e) { - throw new ControlException("Cannot get JNDI initial context at provider '" + url + "' with factory '" + factory + "'", e); - } - } - - /** - * Return null if the given string is null or an empty string. - * - * @param str a string. - * @return null or the string. - */ - protected String nullIfEmpty(String str) { - return (str == null || str.trim().length() == 0) ? null : str; - } - - @Context - ControlBeanContext _context; - - /** - * The initial context. - */ - private transient InitialContext _initialContext; -} diff --git a/beehive-netui-bootstrap/pom.xml b/beehive-netui-bootstrap/pom.xml deleted file mode 100644 index 068942c..0000000 --- a/beehive-netui-bootstrap/pom.xml +++ /dev/null @@ -1,101 +0,0 @@ - - - - - 4.0.0 - - com.moparisthebest.beehive - beehive - 1.0.5-SNAPSHOT - - beehive-netui-bootstrap - beehive-netui-bootstrap - - - javax.servlet.jsp - jsp-api - - - javax.servlet - servlet-api - - - commons-logging - commons-logging - - - commons-collections - commons-collections - - - xdoclet - xdoclet - - - xdoclet - xdoclet-web-module - - - xdoclet - xjavadoc - - - ant - ant - - - - - org.apache.ant - ant - - - - - - maven-antrun-plugin - - - tldgen - prepare-package - - run - - - - - - - - - - -